Posts

Showing posts from July, 2012

coq - Applying hypotesis to a variable -

let's i'm in middle of proof , have hypotheses these: a : nat b : nat c : nat h : somepred b and definition of somepred says: definition somepred (p:nat) (q:nat) : prop := forall (x : nat), p(x, p, q). how apply h c , p(c, a, b) ? the answer is: specialize h c.

c++ - What's the difference between an empty string and a '\0' char? (from a pointer and array point of view) -

as title of question? what's difference? if write: char *cp = "a"; cout << (cp == "a") << endl; or: string str = "a"; cout << (str == "a") << endl; they same , return true. if write: char *cp = ""; cout << (cp == "\0") << endl; it returns false. but: string str = ""; cout << (str == "\0") << endl; it returns true. i thought should same pointer , array perspective. turn out different. what's subtle difference between them? , how should write char array represent empty string? ok, what's above line might unclear said might "a compiler optimization". what want this: char *cp = "abcd"; can give me array this: ['a', 'b', 'c', 'd', '\0']. wondering how can use similar syntax array this: ['\0']. because tried: char *cp = ""; and seems not r

Delete leaves in a tree with regex (Python) -

i have syntax tree, saved in text file in "lisp-style", open , closed brackets show relations. want delete leaves. example, have " (det the)" want become " det". i'm not expert of regex, wonder how handle behaviour in more complex structure, nested brackets. example of tree (in file in 1 row, indented simpler visualization): (s (np i) (vp (vp (v shot) (np (det an) (n elephant))) (pp (p in) (np (det my) (n pajamas))))) i have like: (s np (vp (vp v (np det n)) (pp p (np det n)))) something this? re.sub("\((\w*) (\w*)\)", r"\1", t) where t variable holding syntax tree. for unicode support, see comments below.

r - How to use dplyr to make several simple regressions using always the same independent variable but changing the dependent one? -

i hope not simplest question. need make simple regression (yes, simple one: y = + bx + epsilon). data frame such each column has 1 variable (and each column has 20 rows (observations)). problem first 10 columns y1 y10 , last 1 independent variable. so, have run 10 regressions, changing yi (i = 1,...10). example: y1 = + bx + epsilon y2 = + bx + epsilon ... y10 = + bx + epsilon (yi , x vectors (20 x 1), it's exercise) i can 1 one, thinking them in 1 command. not veteran in programming , thinking if dplyr me this. i looking suggestions. thank you. you can try lapply(d1[paste0('y',1:10)], function(y) lm(y~d1[,'x'])) where d1 dataset

java - getting always 500 failed to load resources Spring -

i have jsp use spring form tags , work fines until before. had changed things in jsp , controller , started continuously getting 500 server error , no related log show error , on console. don't understand caused error , upon wasted time , feel required here. my pojo public class transferinvoiceform { private list<transferinvoice> trinvoicelist; //getters , setters my controller method @controller @requestmapping("/asset/invoice") //some other methods here @requestmapping(value ="transferinvoicehdrform", method = requestmethod.get) protected modelandview showform(final httpservletrequest request, final httpservletresponse response)throws exception { transferinvoiceform transferinvoice = new transferinvoiceform(); list<transferinvoice> transferinvoice= transferinvoicehdrservice.getassetcategoriesandtransfer(); transferinvoice.settrinvoicelist(transferinvoice); return new modelandview("asset/tr

Face Detection using Haar - OpenCV python -

i trying python code snippet: import numpy np import cv2 face_cascade = cv2.cascadeclassifier('haarcascade_frontalface_default.xml') eye_cascade = cv2.cascadeclassifier('haarcascade_eye.xml') img = cv2.imread('img.jpg') gray = cv2.cvtcolor(img, cv2.color_bgr2gray) faces = face_cascade.detectmultiscale(gray, 1.3, 3) (x,y,w,h) in faces: img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) roi_gray = gray[y:y+h, x:x+w] roi_color = img[y:y+h, x:x+w] eyes = eye_cascade.detectmultiscale(roi_gray) (ex,ey,ew,eh) in eyes: cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) cv2.imshow('img',img) cv2.waitkey(0) cv2.destroyallwindows() but error: traceback (most recent call last): file "test.py", line 14, in <module> roi_color = img[y:y+h, x:x+w] typeerror: 'nonetype' object has no attribute '__getitem__' i found program here . if sure image path right , still problem p

opengl - How can I check if the display is selected? -

i'd check if lwjgl display selected or not, i.e. if in foreground. is there display.isinforeground() method? display#isactive returns: true if window active, is, foreground display of operating system. or if using lwjgl 3 , glfw equivalent glfwgetwindowattrib glfw_focused .

exception - New "File" in java -

1. new file in new file("scores.dat") line mean? create new file? 2. when run piece of code, output: " java.io.filenotfoundexception: scores.dat (the system cannot find file specified) " know problem is? 3. there not " finally " section in code; putting " finally " optional in exceptions ? import java.util.scanner; import java.io.file; import java.io.ioexception; public class readandprintscores { public static void main(string[] args) { try { scanner s = new scanner( new file("scores.dat") ); while( s.hasnextint() ) { system.out.println( s.nextint() ); } } catch(ioexception e) { system.out.println( e ); } } } new file() constructor of file class. new instance of file created. scores.dat must file exists in same directory of code. yes finally optional check java

C++ Strange behavior in my own stack class -

here program stack class , functions. readthefile() - reads numbers, stored in num_file.txt , , returns vector numbers. intervalcheck() - adds numbers of specific range input vector , returns vector numbers only. vectomystack() - adds numbers vector stack. #include <iostream> #include <string> #include <vector> #include <fstream> #define stack_empty -1 #define out_of_stack -2 using namespace std; template <class t> class stack { private: struct node{ t element; node *prevelement; }; size_t numberofelements; node *tempadr; node *topelement; node *newelement; node *erasedelement; public: stack(){ topelement = new node; topelement->prevelement = nullptr; numberofelements = 0; } ~stack(){ cout << endl << "i'm destructor"; while(numberofelements !=0 ){ tempadr = topelement->prevelement; delete

Python Pool Multiprocessing with functions -

okay i've been playing code partly better understanding of python, , partly scrape data web. part of want learn if using python multiprocessing , pool. i've got basics working, because wrote procedure single threaded first, , moved use pool multi-thread process, have both global variables, , calls globally defined functions. i'm guessing both of these both bad, searching web, things seem complicated fast or don't answer questions. can confirm firstly global variables bad, , lead problems, me makes sense because 2 threads access same variable @ same time, hence problems. secondly, if have globally defined function, sake of argument processes string , returns it, using standard string functions, okay call within pool process? multithreading , multiprocessing quite different when comes how variables , functions can accessed. separate processes (multiprocessing) have different memory spaces , therefore cannot access same (instances of) functions or variab

android - How to run PhoneGap app on device? -

i tried run simple app on usb connected device: phonegap create my-app cd my-app phonegap run android -device=0123456789abcdef but error: unknown platform: -device=0123456789abcdef ant installed , 'path' variable have path ant ant ant/bin folders. whats can wrong? maybe usb driver of device isn't installed

implementing nested linked list in c++ -

is kind of implementation of nested linked list valid in c++? if yes,then how declare head nested linked lists? syntax accessing data in lists inside? here part of general code. i'm trying perform library management system in c++. struct course { string course_name; struct course_books { struct wait_list { long stu_num; //date inserted wait_list * next_wait_stu; }; struct voters_list { long stu_num; int vote; voters_list * next_voter; }; struct deposit_list { long stu_num; //date given //bring date deposit_list * next_depositor; }; }; course * next_course;

android - Detect uninstall event in phonegap app -

when user installs app register registration id (android) or device token (ios) , send push notifications work fine. want remove user server when app uninstalled. how can accomplish in phonegap: event after can unregister user registration id (android) or device token (ios)? note: using pushplugin afaik, cannot know when app uninstalled. for android app, observe response gcm returns when send notification. if sends notregistered message, can remove id server. read how unregistration works for ios : read question , answer on so

php - I need to show logged user's name -

i using webpage password protector, used external code box big http://paste.ofcode.org/xjvfynz9dblekjri2dwru9 it's working fine want make loged user's name appears in protected page after logging in successfully. may please helpe me ? modify part of code: else { // set cookie if password validated setcookie("verify", md5($login.'%'.$pass), $timeout, '/'); // programs (like form1 bilder) check $_post array see if parameters passed // need clear password protector variables unset($_post['access_login']); unset($_post['access_password']); unset($_post['submit']); } to read as: else { // set cookie if password validated setcookie("verify", md5($login.'%'.$pass), $timeout, '/'); echo "username: " . $login; // programs (like form1 bilder) check $_post array see if parameters passed // need clear password protector variab

javascript - angular-charts.js wont properly update with new data -

Image
the chart html <!-- data-component block theres chart , table. since table doesn't ever have issues, displays real async data... because chart wont render async data, start off fake data can see --> <div class="data-component"> <canvas id="bar" class="chart chart-bar" data="data" labels="labels"> <table> ... real data ... </table> </div> initial (fake) data: $scope.data= [ [1,2,3] ]; $scope.labels = [1,2,3]; $scope.series = ['field1']; results in this: data update: $http.get( _url ) .success(function(distribution) { $scope.loading = false; console.log(distribution); var seriesdata = []; var labels = []; for(var in distribution) { var step = distribution[i]; //this data returned //[{"segment":null,"count":308,"percentage":0.77}, //{"segment":1,"count"

PHP, Bitwise operation, not negative -

when trying code in php: $result = 4 << 29; var_dump($result); // int(2147483648) but in other languages, example in java or javascript -2147483648 . why? this depends on php version you're running. while ago there bug in 32-bit int math when comes overflows. has been solved in php 5.3.

ios - How do I apply an array of NSSortDescriptors in a case insensitive way? -

because nshttpcookiestorage has awful limitations i'm implementing own , 1 of methods re-implement - (nsarray *)sortedcookiesusingdescriptors:(nsarray *)sortorder . gets array of nssortdescriptor s , applies surprise, results tests seems indicate these sort descriptors applied in case insensitive fashion. i couldn't find way apply nssortdescriptor s in case insensitive way other setting selectors :@selector(caseinsensitivecompare:) since property selector read only, best managed this: nsmutablearray *insensitivesortorder = [nsmutablearray array]; (nssortdescriptor* sorter in sortorder) { [insensitivesortorder addobject: [nssortdescriptor sortdescriptorwithkey: sorter.key ascending:sorter.ascending selector:@selector(caseinsensitivecompare:)]]; } is implementation correct? there better way achieve this? one thing worries me i'm ignoring comparator property of nssortdescriptor.

macvim - Can't type {} or @ in Vim editors -

im trying start using vim once again, got dead-end. im using portuguese layout keyboard, , can't type curly brackets or @ symbol inside vim. anyone knows need change have them work normally? update: barton points out, should have provide more complete information, here goes: when type alt+2 (in keyboard it's how type @) 2 exponent symbol. for curly brackets type alt+shift+8 / 9, gives me { , }, in vim shows small quote symbol , © symbol. when run :abbreviate command "no abbreviation found". update2: i've noticed on iterm can type symbols in vim mode, not on vim gui's. thanks help. finally discovered causing problems: set macmeta it wasn't easy catch one.

Java - Try/catch method issue -

this question has answer here: why try/catch block create new variable scope? 5 answers i have problem trying use try/catch in code. whenever try , return result; error "cannot resolve symbol 'result'". here code. public object remove(int index) { try{ object result = this.get(index); (int k = index; k < size-1; k++) items[k] = items[k + 1]; items[size] = null; size--; return result; }catch(arrayindexoutofboundsexception e){ system.out.println("exception occurred in 'remove' method."); return result; } } you have defined result variable within try block. if declare variable within {} braces variable avialble use within braces , wont available outside world. so resolve issue, like: object result = null; try { .... } catch ... { } return result

android - How much data can you get using HttpUrlConnection -

i following examples android course @ udacity made google , replaced url of example other 1 can see, using log small portion of url downloading. public class fetchweathertask extends asynctask<void, void, void> { private final string log_tag = fetchweathertask.class.getsimplename(); @override protected void doinbackground(void... params) { // these 2 need declared outside try/catch // can closed in block. httpurlconnection urlconnection = null; bufferedreader reader = null; // contain raw json response string. string forecastjsonstr = null; try { // construct url openweathermap query // possible parameters available @ owm's forecast api page, @ // http://openweathermap.org/api#forecast url url = new url("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7"); // create request open

playframework - How execute code after returning result in Play framework -

how execute code after returning result client? example: return ok("first"); after need send response websocket actor myactor.tell("second",null) main goal - need send message socket after sending response you can't directly, return statements ends action. if problem long rendering of template, can render first, send message , send pre-rendered result, like result res = ok("first"); myactor.tell("second",null); return res; if doesn't satisfy still, can use akka scheduler schedule message let's 1 second delay. (check akka's documentations details) finally can send content , message @ once within current result i.e. wrapping within json object, or adding message response header - of course if you're handling js on client side.

Android Canvas.ClipPath -

i wanna clip circle region, somehow got rectangle, not circle. , here code: protected boolean drawchild(canvas canvas, view child, long drawtime) { mrevealpath.reset(); mrevealpath.addcircle(mcenterx, mcentery, mrevealradius, path.direction.cw); final int state = canvas.save(); canvas.clippath(mrevealpath); boolean isinvalidate = super.drawchild(canvas, child, drawtime); canvas.restoretocount(state); return isinvalidate; } i add linearlayout textview in child test.

python 3.x - When I was started hadoop cluster but cluster did not start and an issue of lacement Group -

invalidplacementgroup.unknown the placement group '30633_20150226' unknown.e4dc06ca-8d9e-469a-aa3f-dcddc045a9b6 check hadoop daemons runnning using command jps if not seeing required services have restart processes. sudo service hadoop-master stop sudo service hadoop-master start

How do I combine two tables in MySQL keeping all columns? -

i have 2 tables different structures. want query mysql columns both tables in single query. so example, if have person table , animal table, want query return: person_name|person_age|animal_type|animal_name ______________________________________________ ryan |31 |null |null fred |23 |null |null null |null |cat |whiskers null |null |dog |wishbone i have basic knowledge of mysql , couldn't understand of material reading , googling, , didn't seem match want. thanks! you want union query concatenates 2 result sets select person_name, person_age, null animal_type, null animal_name person union select null person_name, null person_age, animal_type, animal_name animal each select query shapes result set in similar way, , union puts them together.

python - Exception gevent.hub.LoopExit: LoopExit('This operation would block forever',) -

i getting error when running flask app websockets. have tried follow guide - http://blog.miguelgrinberg.com/post/easy-websockets-with-flask-and-gevent i have flask app provides gui interface network sniffer. sniffer inside thread shown below : ( l thread sniffer; isrunning boolean check if thread running) try: if l.isrunning == false: # if thread has been shut down l.isrunning = true # change true, loop again running = true l.start() # starts forever loop / declared top global variable print str(running) else: running = true print str(running) l.start() except exception, e: raise e return flask.render_template('test.html', running=running) #goes test.html page the sniffer runs fine without socketio , able sniff network while traversing gui.however, when included socketio in code, first see socketio working in index page , able receive messages server page. traverse fine other static paages in gui

c# - Binding querystring values to a dictionary -

i'm using web api (part of asp.net mvc 5), , i'm trying bind querystring values dictionary<int, bool> . my web api method simply: [httpget] [route("api/items")] public iqueryable<item> getitems(dictionary<int, bool> cf) { // ... } if try invoke url: /api/items?cf[1009]=true&cf[1011]=true&cf[1012]=false&cf[1015]=true the parameter cf null . how can pass in dictionary of values via querystring web api method? there no built-in way of doing this. on case, "cf[1009]" name of parameter, not "cf". can write own query string parser achieve need. better signature be: /api/items?cf=1009&cf=1011&cf=1015 and bind using: public iqueryable<item> getitems(list<int> cf) { // ... }

How to wrap some text in a rectangle in QML? -

i have perform simple task: want display piece of text inside rectangle , size of rectangle should precisely width of text. in c++, it's easy do. define qstring , apply qfontmetrics width. define rectangle graphics element have size. it's done within 5 minutes. i have heard qml easier use. therefore, expecting solve problem in less 5 minutes. didn't, , i'm still stuck @ it. here's have tried: rectangle { width: mytext.contentwidth height: mytext.contentheight text { anchors.fill:parent id: mytext font.family: "helvetica" font.pointsize: 50 text: qstr("the string want display") } } this doesn't work reason don't understand. have found way in way doesn't suits needs: rectangle { width: 100 height: 100 mousearea { id: mymousearea anchors.fill: parent onclicked: parent.width=mytext.contentwidth hoverenabled: true } t

windows - ^M of CRLF shows up in git, but not vim -

to django web project, i'm adding html files template. in vim, these html files don't show wrong, i.e. no cr characters visible. when git diff, show up. since they're not visible in vim, i'm not able :%s/^m//g or :%s/\r//g , both of them show pattern not found error. they're still visible in git diff. don't want them seen in git. git config --global core.autocrlf true doesn't either i got answer after little bit of googling after seeing @torek's answer. i had :set fileformat=unix in vim!

For loop behavior in python -

i have these 2 function calculate numbers of animals based upon input in function. want know behavior of function. if input 20 heads , 56 legs 8 pigs , 12 chickens ultimately. there questions. def solve(numlegs, numheads): numchick in range(0, numheads + 1): #we have got 12 chickens here? numpigs = numheads - numchicks totlegs = 4 * numpigs + 2* numchicks if totlegs == numlegs: return [numpigs, numchicks] return[none, none] def barnyard(): heads = int(raw_input('enter number of heads:')) legs = int(raw_input('enter number of legs:')) pigs, chickens = solve(legs, heads) if pigs = none: print 'there no solution' else: print 'number of pigs:' , pigs pirnt 'number of chickes:', chickens i stuck here for numchick in range(0, numheads + 1): . if number chickens in loop line can proceed calculating number of pigs right? how 12 chickens line commented above? p

file - matlab importdata exception -

i have saved variable 2d-matrix on file named 'handwaving_78.table' , when use importdata filename exception error using videoreader/read (line 145) not seek frame. frame accurate seeking not supported file on current platform. error in importdata (line 192) out = read(videoobj); error in createnewdatasetfromreadfiles (line 28) data = importdata(strcat(baseclassfileaddress,'/',allfiles(j).name)); changed name of file 'handwaving_78.txt' , worked fine. using matlab r2014a on ubuntu 14.0.4 , want know problem because not want change file extensions. from documentation of importdata : if importdata recognizes file extension, calls matlab helper function designed import associated file format (such load mat-files or xlsread spreadsheets). otherwise, importdata interprets file delimited ascii file. it's mystery why .table files recognized videos, there little can change default behavior. the soluti

java - Flat line instead wave -

i want plot sine wave, instead application generates flat line. when use series random jchartfree example works fine. use debugger check if values good. values different zero public void createdataset() { xyseriescollection dataset = new xyseriescollection(); xyseries series1 = new xyseries("object 1"); double = 1; double t = 1; double fs = 10; double f = 200; int rozmiar = (int) (t*fs); double[] x = new double[rozmiar]; (int = 0; < rozmiar; i++) { x[i] = * math.sin(2 * math.pi * f * / fs); series1.add(i, x[i]); } dataset.addseries(series1); data = dataset; } //... public void createchartpanel() { //pwykres = new jpanel(); //if(java.util.arrays.aslist(getcomponents()).contains(pwykres)){ //getcontentpane().remove(pwykres); //} if(pwykres != null){ pwykres.removeall(); pwykr

javascript - console.log not working inside angular controller -

hi have been trying angular.j. have tried following code. console.log() not seems working. missing?? angular concepts or something? var foodsharemodule= angular.module('food',['ui.router','ngresource']); console.log("main file getting included"); foodsharemodule.controller("personcontroller", function($scope) { console.log($scope); $scope.firstname = "john"; $scope.lastname = "doe"; console.log($scope.firstname); console.log($scope.lastname); }); foodsharemodule.controller('scratchlistcontroller', function($scope,$state,notes){ console.log("working"); $scope.scratchpad =food.query(); $scope.deletescratch = function (scratch,flag) { if(flag === 0) { //checks if bulk delete or single delete if(confirm("you clicked delete !! sure ?")) { scratch.$delete(function() { //single de

How to repeat characters in Python without string concatenation? -

i'm writing short program frequency analysis. however, there's 1 line bothering me: "{0[0]} | " + "[]" * num_occurrences + " total: {0[1]!s}" is there way in python repeat characters arbitrary number of times without resorting concatenation (preferably inside format string)? don't feel i'm doing in pythonic way. the best way repeat character or string multiply it: >>> "a" * 3 'aaa' >>> '123' * 3 '123123123' and example, i'd use: >>> "{0[0]} | {1} total: {0[1]!s}".format(foo, "[]" * num_occurrences)

regex - use shell command tesseract in perl script to print a text output -

hi have script want write, first took html image, , wanted use tesseract take output txt it. cant figure out how it. here code: #!/usr/bin/perl -x ########## $user = ''; # enter username here $pass = ''; # enter password here ########### # server settings (no need modify) $home = "http://37.48.90.31"; $url = "$home/c/test.cgi?u=$user&p=$pass"; # html code $html = `get "$url"`; #### add code here: # grab img html code if ($html =~ /\img[^>]* src=\"([^\"]*)\"[^>]*/) { $takeimg = $1; } @dirs = split m!/!, $takeimg; $img = $dirs[2]; ######### die "<img> not found\n" if (!$img); # download img server (save as: ocr_me.img) print "get '$img' > ocr_me.img\n"; system "get '$img' > ocr_me.img"; #### add code here: # run ocr (using shell command tesseract) on img , save text ocr_result.txt system ("tesseract", "tesseract o

ruby on rails - Multiple recipients of activity -

i want use this (public_activity) gem create newsfeed. there recipient_id column, 1 recipient of activity. but, in cases, have multiple recipients (e.g show activity people following specific record) - number of recipients can more 100, lot of separate records create @ once , display. what best way go doing this? i found this suggestion , although can't work , lot of errors. one solution might create custom column t.text :user_recipients store ids of users should activity (because, example, might following specific record). then, check if current_user.id belongs_to set of numbers. set of numbers ("1, 3, 4") first converted array ([1, 3, 4]) , can use array.include?(current_user.id) is way it? also, records have empty user_recipients column not shown. at end, should this: @activities = publicactivity::activity.where(/records current_user.id belongs user_recipients array/ + /column not empty/) when searching inside string there's 4 pos

c++ - Qt multiple UIs -

i have qt project 2 ui classes/forms. main class creates second_window object , opens second window so: second_window* sec_win = new second_window(this); qt::windowflags flags = sec_win->windowflags(); sec_win->setwindowflags((flags | qt::windowminmaxbuttonshint) & ~qt::windowcontexthelpbuttonhint); sec_win->show(); the second window opens , displays fine. still able interact main window, clicking main window not bring front of second window. second window on top of first. idea how change this? have researched qt::windowflags , none of them seem need. have researched alternatives show() method no luck yet. qwidget::raise() in case, if widgets non-modal. or pass nullptr instead of this . , don't forget release widgets memory.

2d games - PCG pseudomaze algorithm? -

Image
i created set of tiles using photoshop: i'm looking way fill screen of these 80x80 tiles, areas connected. game board pac man style game, not maze entry , exit. my goal here never have opening facing wall. i'm doing choosing next tile randomly subset based on last tile, if last tile has wall on left, next tile can't have opening on left. i'm limiting corners smaller subset. works first row. my problem calculating rest of rows, have based on tile left, or right. think cumbersome build tables hand. (not there wrong hard work, inefficient work isn't good). current output looks this: here code wrote getting allowed next tiles based on recent tile on left: function getallowed(last_tile,x,y) object cselect={u : ["u","r","v","rx"] v : ["u","d","r","v","rx"] l : ["u","d","v","rx"] d : [&qu

c# - Looking for a more efficient pop count given a restriction -

the popcount function returns number of 1's in input. 0010 1101 has popcount of 4. currently, using algorithm popcount : private int popcount(int x) { x = x - ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); return (((x + (x >> 4)) & 0x0f0f0f0f) * 0x01010101) >> 24; } this works fine , reason ask more because operation run awfully , looking additional performance gains. i'm looking way simplify algorithm based on fact 1's right aligned. is, input 00000 11111 (returns 5) or 00000 11111 11111 (returns 10). is there way make more efficient popcount based on constraint? if input 01011 11101 10011 , return 2 because cares right-most ones. seems kind of looping slower existing solution. here's c# implementation performs "find highest set" (binary logarithm). may or may not faster current popcount, surely slower using real clz and/or popcnt cpu instructions: s

python - Django, Extend BaseUserManager, -

i'm trying extend django's baseusermanager , when create super user, i'm checking if organization exists (if not create one) , assign user foreignkey . the error i'm gettting is: creating demo data... traceback (most recent call last): file "manage.py", line 10, in <module> execute_from_command_line(sys.argv) file "/users/manos/projects/devboard/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line utility.execute() file "/users/manos/projects/devboard/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 377, in execute self.fetch_command(subcommand).run_from_argv(self.argv) file "/users/manos/projects/devboard/env/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **options.__dict__) file "/users/manos/projects/devboard/env/lib/python2.7/site-packages/dja

c# - Collision script on an object to be collided with from the player for pickup -

i'm trying write script allows player walk pack of ammo (or health) , gain doing so. i'm struggling actual collision part of no matter can't seem work. have script on ammo pack object. void ontriggerenter(collider collision) { if (collision.gameobject.tag == "player") { debug.log ("collided"); } } my ammo pack object has collider on (currently capsule, box final product) has "is trigger" enabled. player has capsule collider (non-trigger) , rigidbody gravity enabled , else default. tagged "player". when player walks ammo pack, there no message printed. i've tried several solutions involve changing triggers on colliders , rigidbody kinematic settings none of them seem work. i'm using unity 5 , wondering if i'm doing wrong. appreciated. this function never called because capitalisation wrong. capitalise first letter of function name. void ontriggerenter(collider c) instead of: voi

vbscript - Get the server's cpu utilization -

i've searched around , got code apparently works everyone: set objwmiservice2 = getobject("winmgmts:{impersonationlevel=impersonate}!\\.\root\cimv2") set colitems = objwmiservice2.execquery("select * win32_perfformatteddata_perfos_processor name = '_total'") each objitem in colitems response.write( "cpu usage percentage: " & objitem.percentprocessortime & "%" ) next executing blank page, not error. actually os virtualized on server, problem? , if so, there's workaround? what's error you're getting? here's i'm using same thing (stripped down bit). shows load per physical processor. strcomputer = "." dim arrprocessors : redim arrprocessors(2,0) set objwmiservice = getobject("winmgmts:" _ & "{impersonationlevel=impersonate}!\\" & strcomputer & "\root\cimv2") set colcpusystems = objwmiservice.execquery("select addresswi

html - Bootstrap collapse panel going too big when expanding -

i trying collapse panel work (new this), , minimizes well, when expanding, expands right bottom of page, , returns expected size. http://www.bootply.com/1obli5zmtd click little expand/collapse icon on top right. watch goes way big, , returns size should. how can make expand right size? i not sure causing this, did find solution. move #collapseclosed outside of .panel-group . think there strange nesting issue here default css, i'd have spend more time figure out wrong. here adjusted bootply , jsfiddle .

image - Why do browsers display grafics different and how to change that? -

Image
i working on website right now. sadly png logo , background uses same colors displayed on computers firefox in lila. chrome blue looks expected. the used monitor has effect, chrome looks fine. where issue come from, , how can fix that? here image here see photo of monitor. lila firefox (on left) visible slightly. big issue color used in background of website, looks lila than, firefox, , displayed color not match other colors in css @ website anymore. the above picture firefox: the above picture chrome: firefox handles images contain srgb profile differently untagged images , html colors, default. has 3 modes of operation can select going "about:config", searching gfx.color_management.mode. default "2". change "0" (no color management) or "1" (color manage everything) , you'll match. see four-year-old bug #621474 @ https://bugzilla.mozilla.org , scroll down comment #49 see current status of patch. because of

autocomplete - PhpStorm 8: Reset file type for a specific file -

i created file in phpstorm 8, accidentally creating without ".php" extension, , phpstorm refuses recognise php file, or syntax highlight, autocomplete, etc, after changed extension .php... i have tried deleting file , recreating it, invalidating cache through file menu, deleting .idea folder in project, , deleting whole project , pulling git server again, phpstorm still refuses acknowledge php file, after multiple attempts create .php extension first time. settings (preferences on mac) | editor | file types | text files find , remove unwanted pattern there

javascript - Function bringing back error 'token {'? -

i'm new javascript , i'm having hard time functions. tried this: (function data { // part that's broken seems? var data = 1; var real = 2; console.log(data + real) // }) i error: uncaught syntaxerror: unexpected token { i'm not sure means though? seems me, bit confused brackets... try this: function data(){ var data = 1; var real = 2; console.log(data+real); } the error suggests there problem token didn't expect there... hope helps!

python - How do I connect asyncio.coroutines that continually produce and consume data? -

i trying learn how (idiomatically) use python 3.4's asyncio . biggest stumbling block how "chain" coroutines continually consume data, update state it, , allow state used coroutine. the observable behaviour expect example program periodically report on sum of numbers received subprocess. reporting should happen @ same rate source object recieves numbers subprocess. io blocking in reporting function should not block reading subprocess. if reporting function blocks longer iteration of reading subprocess, don't care if skips ahead or reports bunch @ once; there should many iterations of reporter() there of expect_exact() on long enough timeframe. #!/usr/bin/python3 import asyncio import pexpect class source: def __init__(self): self.flag = asyncio.event() self.sum = 0 def start(self): self.flag.set() def stop(self): self.flag.clear() @asyncio.coroutine def run(self): yield self.flag.wait()

ios - How do I add spaces between table view cells in swift or using the storyboard? -

in table view cells stuck without spacing how make space between cells in swift code or using storyboard thanks actually bit tricky: set cell height lets 75. set background-color clearcolor. place view height of 50 on top of cell , center it. place labels etc on view. dont forget background-color view (maybe white?). if these steps, fake distance between rows :) hope you!

image processing - Set alpha value to a particular figure on MATLAB GUI -

i have matlab gui contains 2 axes. want change alpha value of plane plotting in 1 of axes. reason command alpha(0.5) getting defaulted first axes. can me please? here code: point1 = [2000,0,-1000] point2 = [-2000,0,-1000] point3 = [-2000,0,1000] point4 = [2000,0,1000] points = [point1' point2' point3' point4'] fill3(points(1,:),points(2,:),points(3,:),[1,0.4,0.5],'parent',handles.axes2) alpha(0.3,handles.axes2)//notworking thank you!

java - Android RecyclerView, recycling not working properly -

i have recyclerview using. have used recyclerview before never had problem. when scroll , down of items disappear, , of items disappear appear again in bottom. code: viewholder : public class viewholder extends recyclerview.viewholder { public textview txt; public viewholder(view view) { super(view); txt = (textview) view.findviewbyid(r.id.txt); } } adapter : public class myadapter extends recyclerview.adapter<viewholder> { private final activity activity; private final arraylist<hashmap<string, string>> mitems; public myadapter (activity activity, arraylist<hashmap<string, string>> mitems) { this.activity = activity; this.mitems= mitems; } @override public viewholder oncreateviewholder(viewgroup viewgroup, int i) { return new viewholder(layoutinflater.from(activity).inflate(r.layout.items, viewgroup, false)); } @override public void onbindviewhold

Using variable value as 'name identifier' javascript/html -

i have function in javascript adds rows html table when called. in row, 1 of additions radio checkbox, allows 1 box checked every radio under same 'name'. reason, each time function called add row, 'name' attribute must change. var namedata = "daynight" + rowcount; //irrelevant intermediary code. creates new row , cell. then: newcell.innerhtml = '<input type="radio" name=namedata value="am">'; //and newcell.innerhtml = '<input type="radio" name=namedata value="pm" checked>'; i tried (and few other variations) 'name' option, every time click button add row, every addition goes under same name (so 1 box can checked in newly created rows, instead of each row individually). namedata contain desired name plus row number, insuring each 'name' different. how 'name' attribute of 'input' receive value of 'namedata'? , fix problem? try this:

c# - WEB API With database Post Method -

i need make api post method insert data database. the database has 3 fields: 1 field has default values given database, 1 have insert new guid.newguid() method, , 1 inserted user. how can this? never seen in tutorial. if can give me example appreciate. i'm new in web apis , have seen bunch of tutorials since wednesday , can't reach solution. edit: here code: public httpresponsemessage post(company value) { try { if(modelstate.isvalid) { bd.companies.add(value); bd.savechanges(); return request.createresponse(httpstatuscode.ok); } else { return request.createresponse(httpstatuscode.internalservererror, "invalid model"); } } catch (exception ex ) { return request.createresponse(httpstatuscode.inter