Posts

Showing posts from January, 2011

javascript - How do I extract the name from HTML collection? -

Image
here's step through of javascript. i have htmlcollection, want loop through , extract object id of fileuploadcontrol. how do it? here's code, how proceed? function uploadimage(lnk) { var row = lnk.parentnode.parentnode; var rowindex = row.rowindex - 1; var abc = row.cells[2].getelementsbytagname("input"); var arr = [].slice.call(abc); } this it: abc.nameditem('fileuploadcontrol') but beware that: different browsers behave differently when there more 1 elements matching string used index (or nameditem's argument). firefox 8 behaves specified in dom 2 , dom4, returning first matching element. webkit browsers , internet explorer in case return htmlcollection , opera returns nodelist of matching elements. from here . this means if in markup had this: <div id='id'>foo</div> <div id='id'>bar</div> browsers behave differently when executing following code

c++ - Boost, inserting static library in repository -

i'm working on large project, cross platform between linux , osx. i'm include boost functionalities, don't want force the collaborators install on machine (with totally different environment) boost libraries. if compile boost on machine, , put static libraries inside repository, problem face? can colleagues use same static libraries on environment? afaik there difference. static libraries not same on os x , linux. compilation depends on toolset (see boost guide ). , there can issues if ides different. however can compile both versions 1 platform (see cross-compilation ) , put them in repository, putting binary objects not best idea (even if don't depend on platform). i think try compile , link boost on different platforms, maybe succeed, can not cover scenarios sure. better create boost compilation script , tell use it.

php - Regular Expression for preg_match -

this question has answer here: how parse , process html/xml in php? 27 answers i got following string: elftksuqmcc" alt="" width="auto" height="auto" /></td> <td style="padding: 10px;">xx,x%</t and want have "xx,x", build following regular expression: /qmcc" alt="" width="auto" height="auto" \/><\/td>\n<td style="padding: 10px;">(.*?)%/ i tested online , got match xx,x when try execute in php following code preg_match_all('/regex/',$string,$match); it didn't match. have suggestions? string in there. var_dump($match) gives me empty array. thank you! problem in newline. in regex, there \n . use \r\n instead , work.

javascript - Jasper Async Report - Empty, why? -

lets start , firstly parameters specific report exmaple var config = { url : "http://exmaple.com/jasperserver/rest_v2/reports/reportfolder/examplereport/inputcontrols", method: "get", headers: { accept: "application/json;" }, } everything ok, response array of inputs, the array contains, 2 objects : first: { description: "date_from", id: "date_from", label: "date from", type: "singlevaluedate" } second: { description: "date_to", id: "date_to", label: "date_to", type: "singlevaluedate" } both inputs have property: validationrules[0].datetimeformatvalidationrule.format = "yyyy-mm-dd" so want run async report (i pass async parameter false now, se there less code here) var params ={ reportunituri: "/reportfolder/examplereport", outputformat: "html", freshdata : true, savedatasnapshot : f

python - Django REST: create CRUD operations for OneToOne Field -

i'm trying create basic crud operations onetoone field. user not required set profile when signing in. how create/update/delete profile when needed (assuming user in db)? my models default user models django rest and: class userprofile(models.model): user = models.onetoonefield(user) location = models.charfield(max_length=50,blank=true) title = models.charfield(max_length=80,blank=true) #picture = models.imagefield(upload_to='user_imgs', blank=true) website = models.urlfield(blank=true) my viewsets are: class userviewset(viewsets.modelviewset): queryset = user.objects.all() serializer_class = userserializer filter_fields = ['id', 'username', 'email', 'first_name', 'last_name'] class userprofileviewset(viewsets.modelviewset): queryset = userprofile.objects.all() serializer_class = userprofileserializer filter_fields = ['user_id', 'location', &

Java: Equivalent to Python's str.format() -

in python, there nice method simplifies creation of strings, making code beautiful , readable. for example, following code print exampleprogram -e- cannot something print_msg('e', 'cannot something') def print_msg(type, msg): print 'exampleprogram -{0}- {1}'.format(type, msg) i.e. can specify "slots" within string, using {x} syntax, x parameter index, , returns new string, in replaces these slots parameters passed .format() method. currently java knowledge, implement such method ugly way: void printmsg(string type, string msg) { system.out.println("exampleprogram -" + type + "- " + msg); } is there equivalent python's .format() string method? messageformat has exact usage. int planet = 7; string event = "a disturbance in force"; string result = messageformat.format( "at {1,time} on {1,date}, there {2} on planet {0,number,integer}.", planet, new date(), eve

Preserving whitespace / indentation in Rails database column -

i have blocks of pseudo-code text stored in database printed off line-by-line , displayed in html. pseudo-code entered in text column in database: while (counter <= 10) { printf("enter grade: "); scanf("%d", &grade); total = total + grade; counter = counter + 1; } /* end while */ controller: def index @code = code.first // filler time being end index: - @code.cont.each_line |line| - += 1 .line %span= %li.line= line - = 0 somewhere along way ruby automatically strips out whitespace , leaves me text. i'd know how preserve this: while (counter <= 10) { printf("enter grade: "); scanf("%d", &grade); total = total + grade; counter = counter + 1; } /* end while */ doesn't come out this: while (counter <= printf("enter grade: "); scanf("%d", &grade); total = total + grade; counter = counter + 1; } /* end while */ i'm pretty

io redirection - Bash read function returns error code when using new line delimiter -

i have script returning multiple values from, each on new line. capture values bash variables using read builtin (as recommended here ). the problem when use new line character delimiter read , seem non-zero exit code. playing havoc rest of scripts, check result of operation. here cut-down version of doing: $ read -d '\n' b c < <(echo -e "1\n2\n3"); echo $?; echo $a $b $c 1 1 2 3 notice exit status of 1. i don't want rewrite script (the echo command above) use different delimiter (as makes sense use new lines in other places of code). how read play nice , return 0 exit status when reads 3 values? update hmmm, seems may using "delimiter" wrongly. man page: -d *delim* first character of delim used terminate input line, rather newline. therefore, 1 way achieve desired result this: read -d '#' b c < <(echo -e "1\n2\n3\n## end ##"); echo $?; echo $a $b $c perhaps there's nicer way though

java - Webapp from Roo-Script in maven project -

assumed maven-project exists in subversion: + myproject + src | + main | + resources | + script.roo + pom.xml this pom: <project> <groupid>foo</groupid> <artifactid>bar</artifactid> <version>1.0-snapshot</version> <packaging>war</packaging> </project> how execute script.roo without having spring-roo installed? currently there noway archive this. spring roo development tool (like eclipse) need download , install execute roo commands or roo script.

php - How to insert all values frow row into mysql database using insert record? -

hello have problem php last value in rows inserted in mysql database: last value inserted rows mysql database show last value inserted insert record i want 3 of data inserted not last values... how do that? here insert record behavior code: if ((isset($_post["mm_insert"])) && ($_post["mm_insert"] == "form1")) { $insertsql = sprintf("insert ordering (productcode, name, paymentmethod, quantity, totalprice) values (%s, %s, %s, %s, %s)", getsqlvaluestring($_post['productcode'], "int"), getsqlvaluestring($_post['name'], "text"), getsqlvaluestring($_post['paymentmethod'], "text"), getsqlvaluestring($_post['quantity'], "int"), getsqlvaluestring($_post['totalprice'], "double")); mysql_select_db($database_perfume_connection, $perfume_connection); $r

android - Turn screen on programmatically without using WAKE_LOCK permission -

is there way turn on screen when device locked. listening proximity sensor events turn on screen, acquiring wake lock needs wake_lock permission. is there alternative. gravity app in playstore without wake_lock permission. hint?

Using SAML and https or http -

i working on service provides authentication service using saml sso protocol communication security. brief intro :- saml sso recognizes identity provider (ip or idp) , service provider, “trusts” , delegates user authentication idp. here how trust established: 1. service provider (sp): - trusted idp name , certificate - single sign on (sso) url 2. identity provider (idp): - relying sp name , certificate - sso consumer url whenever sp needs authenticate user, redirects sso endpoint , passes samlrequest wither in query string or form field (get or post method). what know is requirement client requires authentication should sending request through "https" protocol or request can relayed across using http channel. asking saml protocol mandates use https or not saml not require use of https. should protect messages in way. might using xml signature/encryption, https or other way. https easiest way implement this.

ios - How to play video in fully visible cell in UITableView -

in application playing video in uitableviewcell using following code. works perfectly. cell2.movieplayer = [[mpmovieplayercontroller alloc]initwithcontenturl:vidurl]; cell2.movieplayer.controlstyle = mpmoviecontrolstyledefault; [cell2.movieplayer.view setframe:cell2.playvw.frame]; cell2.movieplayer.controlstyle=mpmoviecontrolstyleembedded; [cell2.contentview addsubview:cell2.movieplayer.view]; [cell2.movieplayer setfullscreen:no animated:yes]; only video play cells visible, managed following code. woking - (void)scrollviewdidenddecelerating:(uiscrollview *)scrollview { nsmutablearray *arr = [[nsmutablearray alloc]init]; (nsindexpath *indexvisible in tblfeedtable.indexpathsforvisiblerows) { cgrect cellrect = [tblfeedtable rectforrowatindexpath:indexvisible]; bool isvisible = cgrectcontainsrect(tblfeedtable.bounds, cellrect); if (isvisible) { [arr addobject:[nsstring stringwithformat:@"%ld",(long)indexvisible.row]]; } } nslog(@"%@"

html - CSS, create a line next to text -

this question has answer here: line before , after title on image 2 answers i've read multiple threads without success. i'm looking creating line next text in css. i'm not allowed change html code adding span element html code not solution me. this looks like. <legend>text</legend> and want create line http://imgur.com/bvq2txt any solution without changing html-code? you can this: legend { height: 18px; position: relative; background: #fff; display: inline-bock; margin-left: 5px; } legend:before { content: ""; display: block; font-size: 0; line-height: 0; text-indent: -4000px; position: absolute; top: 8px; left: -5px; right: -100px; height: 1px; border-top: 1px solid red; z-index: -1; }

safari - Javascript: How to redirect a user to the appstore on iOS 9 -

on ios 8 , earlier, when user clicks "play now" button on our website, loading our game.html file check if user on ios , if forward them appstore: var isios = ua.indexof("ipad") > -1 || ua.indexof("iphone") > -1 || ua.indexof("ipod") > -1; if (isios) { alert('we forwarding appstore now.'); window.top.location = iosurl; return; } however not work on ios 9 anymore. noticed redirect work if replace iosurl generic url " http://www.google.de ", urls " https://itunes.apple.com " or "itms-apps://itunes.apple.com" not open. reason , how can recreate same behavior on ios 9? thanks

python - List Index Out of Range Error - cannot get code to run -

question all. i'm coding assignment school in have simulate physical process of water flowing between 3 ponds, , how pollutant dumped pond 1 flows between ponds. keep getting error "indexerror: list index out of range". have tinkered around different things day cannot error go away. here code below: (fyi python says have error on line 49, 32, , 38). pond_1 = [0] pond_2 = [0] pond_3 = [0] # pond 1 def pond1(timeinput): pollutants = inflow3(timeinput-1)-outflow2(timeinput-1)+pond_1[timeinput-1] total = leakinginput*timeinput if total <= maximuminput: pollutants += leakinginput return pollutants def inflow3(timeinput): return 0.005*pond_3[timeinput] def outflow2(timeinput): return 0.005*pond_1[timeinput] #pond 2 def pond2(timeinput): return inflow1(timeinput-1)-outflow3(timeinput-1)+pond_2[timeinput-1] def inflow1(timeinput): return 0.005*pond_1[timeinput] def outflow3(timeinput): return 0.005*pond_2[timeinput] #

colors - Haskell RGB to CMYK -

rgb2cmyk r g b = ((w - (r/255))/w,(w - (g/255))/w,(w - (b/255))/w,k = 1 - w) w = max(r/255,g/255,b/255) could please me code? no matter do, same failure "parse error on input '='" don't use tabs, indentation significant in haskell, use spaces. following ( max takes 2 arguments, maximum takes list). rgb2cmyk r g b = ((w - (r/255))/w, (w - (g/255))/w, (w - (b/255))/w, 1 - w) w = maximum [r/255, g/255, b/255]

absolute - Cooliris relative path Issue -

take on codes: > <object id="o" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" > width="100%" height="100%"> <param name="movie" > value="cooliris.swf"/> <param name="allowfullscreen" value="true"/> > <param name="allowscriptaccess" value="never"/> > <param name="flashvars" value="feed=http://ip/xml/cooliris.xml"/> > <param name="wmode" value="opaque"/> <embed > type="application/x-shockwave-flash" > src="cooliris.swf" > width="100%" > height="100%" > allowfullscreen="true" > allowscriptaccess="never" > flashvars="feed=http://ip/xml/cooliris.xml" > wmode="opaque"> </embed> </object> it's working fine when change pa

php pthreads: 'PHP Fatal error' , 'Fatal error' in CLI -

i ran example of https://github.com/krakjoe/pthreads/tree/seven/examples in cli. after executing each one, php fatal error , fatal error ,in addition expected result. example in case https://github.com/krakjoe/pthreads/blob/seven/examples/closurefuture.php i'll get: object(volatile)#6 (2) { [0]=> string(5) "hello" [1]=> string(5) "world" } array(2) { [0]=> string(5) "hello" [1]=> string(5) "world" } php fatal error: cannot declare class future, because name in use in /var/www/test/index1.php on line 42 fatal error: cannot declare class future, because name in use in /var/www/test/index1.php on line 42 in example error occured when extended class closed. do know reason of these errors , how correct them? appreciated. class future extends thread { private function __construct(closure $closure, array $args = []) { $this->closure = $closure; $this->args

arrays - Will an arraylist be empty after adding the object to another arraylist -

public void enqueue(packet...packets) { arraylist<packet>type1 = new arraylist(); arraylist<packet>type2 = new arraylist(); boolean t = true; for(packet packet : packets) { if(packet.getclasstype() == t ) { type1.add(packet); } else { type2.add(packet); } } if(queue.isempty()) { if(type1.isempty()) { //do nothing } else { queue.addall(type1); } if(type2.isempty()) { //do nothing } else { queue.addall(type2); } } else { for(int = 1 ; i<=queue.size() ; i++ ) { if (queue.get(i).getclasstype() != t) { if(type1.isempty()) { // nothing } else { queue.addall(i, type1); } }

Normalize different date data into single format in Python -

this question has answer here: parsing date can in several formats in python 4 answers i analyzing dateset contains many different date types 12/31/1991 december 10, 1980 september 25, 1970 2005-11-14 december 1990 october 12, 2005 1993-06-26 is there way normalize date data single format 'yyyy-mm-dd' ? familiar datetime package in python, what's best way approach problem can handle different date types. if okay using library, can use dateutil library (i believe comes installed python 3 +) , dateutil.parser.parse function, , parse dates datetime objects, , use datetime.datetime.strftime() parse them strings in format - 'yyyy-mm-dd' . example - >>> s = """12/31/1991 ... december 10, 1980 ... september 25, 1970 ... 2005-11-14 ... december 1990 ... october 12, 2005 ... 1993-06-26""" >>

Twitter API, get Tweet as Image -

i understand can specific url of tweet using twitter api creating url this https://twitter.com/username/status/tweet-id however, possible image of tweet? can media images, images people posted in tweet. want know if possible image of tweet itself. twitter's api includes ability oembed. https://dev.twitter.com/rest/reference/get/statuses/oembed

javascript - var card= cleanNum: function(){....} what does this cleanNum: mean? -

i want know cleannum means in following code. function name or represent else? //code snippet 1 var creditcard = { cleannum : function(number){ return number.replace(/[- ]/g,""); } }; q1. not meaning of cleannum. can please explain significance of cleannum(). q2. if using in function called another_func(), how call code snippet 1? is below code snippet same above? //code snippet 2 function cleannum(number){ //sample code } first thing´s first: var x = {} defines new object, every variable declared within {} becomes field of object. the following create object (referenced variable creditcard ) field number var creditcard = { number: '3432-2342-34243' }; so q1, significance of cleannum, it's member of of object creditcard . instead of containing int/string/date etc, contains function var creditcard = { cleannum : function(number){ return number.replace(/[- ]/g,""); } }; as q2, function same, scope not.

sql - Hide Delete Button in Gridview if RowID links to Foreign Key -

vb.net - i've found other questions related this, none situation. i'm dealing 2 tables - "task" , "task_run." i have gridview rows listing "tasks." come "task" table , each task has "tsk_id." want have delete button each task (row) , want delete button visible row if task not have run associated task "task_run" table. (i.e. not want user able delete task if has been run.) table1 - "task" pky = "tsk_id" table2 - "task_run" pky = "run_id" fky = "run_tsk_id" i assume need have template field in gridview , have delete button conditionally show based on whether there rows in run table associated particular task id, stuck on how this. makes sense. appreciated. thanks! you first task_id task_run table accordingly user if exist otherwise return 0 value , , placed task_id in gridview on label or textbox or hidden field visible=false property if not showing u

objective c - How can we change table-list title color when we tapped on it in ios -

Image
hi beginner in ios , in project have added labels , image on table-list cell ok have added ok here main requirement when tapped on table-list cell labels colors must change , image need change below image for have written code that's not working pleas me my code:- -(uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath{ nsstring *cells=@"cell"; uitableviewcell *cell=[tableview dequeuereusablecellwithidentifier:cells]; if (cell==nil) { cell=[[uitableviewcell alloc]initwithstyle:uitableviewcellstylesubtitle reuseidentifier:cells]; } strip = [[uiview alloc]initwithframe:cgrectmake(0, 0, 7, cell.frame.size.height)]; strip.backgroundcolor = [uicolor orangecolor]; [cell.contentview addsubview:strip]; titlelbl = [[uilabel alloc] initwithframe:cgrectmake(65, 7, 130, 35)]; titlelbl.text =[right_menu_array objectatindex:indexpath.row]; titlelbl.textcolor=[uicolor darkgrayco

c - Correctly passing an array from a function -

i have code generate array of size [user_input] in function called array_generator, using size of array scanf in main(), , filling numbers 0 user_input (0, 1, 2, 3, if user input 4). array fills correctly printf prints `the array contains value 1` `the array contains value 2` `the array contains value 3`, etc. however when pass array main , printf array values equal statements filled garbage numbers. i'm 90% sure have been passing arrays , pointers incorrectly (new them). the code below: #include <stdio.h> int *array_generator(int number_songs); int main(void) { int input; int *p; int i; int x; printf("enter number of songs wanted in random playlist: "); scanf("%d", &input); p = array_generator(input); x = *p; (i = 0; < input; i++) { printf("the array contains values %d\n", x); } return 0; } int *array_generator(int n) { int a[n]; int *p; int i; (i

c# - Show/Don't Show Remove Button for Edit/New Page -

this pretty simple. have uwp application has page save button , edit button (call page1). page buttons take (page2) same, except when user clicks edit, page2 has remove button , when user clicks save, page2 not have remove button. i sending parameter page2 in savebtn_click , editbtn_click methods: frame.navigate(typeof(page2), param1); and figured send true/false depending on button clicked. since 2 parameters, thought create payload class these values assigned member variables , send payload object (payload). then, in onnavigatedto method of page2's code behind, can set variable (visible) value of payload.visible , set button's visibility property value. however, thinking there has more elegant way this. in advance. i think solution there someways that. common way using onnabigatedto , onnabigatedfrom send parameters. if using mvvm can use messages or payloads between viewmodels. way using static class save variables. in case think solution fine

mysql - Getting sum of diffrent totals using different dates -

i have transaction table want sum total amount different dates, bellow code select sum( total_amount ) total transaction execution_date between "2015-08-1" , "2015-08-31" , execution_date between "2015-09-1" , "2015-09-30" the code returns null. welcome. you should write or instead and .since want display transactions in both range 2015-08-1" , "2015-08-31 , 2015-09-1" , "2015-09-30 , contradiction, results null select sum( total_amount ) total transaction execution_date between "2015-08-1" , "2015-08-31" or execution_date between "2015-09-1" , "2015-09-30" or select sum( total_amount ) total transaction execution_date between "2015-08-1" , "2015-09-30" hope helps

java - Why casting the object is redundant -

i have 2 constructors expandable list shown below, , have 1 interface shown below well. want use same expandlist adapter 2 different activities that's why created 2 constructors. problem when initialise constructors, see in 1st constructor when initilaise interface object 2nd parameter in constructor, receive "redundant casting" while in 2nd constructor mandatory initialise interface object 2nd parameter activity should implement interface please explain why casting in 1st constructor rundant while manadory in 2nd one? update both activities extends appcompatactivity *code : public myexpandablelist(context ctx, actmain actmain, arraylist<group> grouplist) { this.mctx = ctx; this.mgrouplist = grouplist; this.mbtutils = new btutils(ctx); this.mdevdetailsobserver = (idevicedetailspasser) actmain;//redundant casting, not necessary } public myexpandablelist(context ctx, actconnect actconnect, arraylist<group> grouplist) { this.m

c# - Filtering by plain date SQL to Linq syntax -

i have following sql , result: select eventtime incidents -- result -- 2015-10-20 00:00:00.000 2015-10-20 05:00:00.000 2015-10-20 05:50:00.000 2015-10-20 07:00:00.000 2015-10-20 09:00:30.000 2015-10-21 05:00:00.000 2015-10-21 06:10:00.000 2015-10-22 09:10:00.000 i use following sql filter plain date (sql 2014): select distinct convert (date, [eventtime]) eventdate incidents -- result -- eventdate 2015-10-20 2015-10-21 2015-10-22 so easy in sql. linq try logic: var q = db.timelines.select(x => x.time.date).distinct(); // show q.tolist().foreach(x => { console.writeline("eventdate: {0}", x); }); breaks with: additional information: specified type member 'date' not supported in linq... ...how write second sql in linq? if change query list before using operators aren't translatable sql, work. var q = db.timelines.tolist.select(x => x.time.date).distinct(); // show q.foreach(x => { console.writeline("eventdate: {0}", x

C: I can't change my struct but the error is: must use 'struct' tag. It's my teacher's fault? -

[c language] teacher give me , i'm not allowed change it: struct nodescl { int info; struct nodescl* next; }; typedef nodescl* typescl; // problem here i have make program take 2 typescl equal length, , return new typescl called "min_list", minor element taken each "i" position. program: typescl minelements(typescl l1, typescl l2) { if(l1 == null) { return null; } typescl min_list = (typescl) malloc(sizeof(typescl)); if (l1->info <= l2->info) { min_list->info = l1->info; } else { min_list->info = l2->info; } min_list->next = minelements(l1->next, l2->next); return min_list; } i got problem "must use 'struct' tag refer type 'nodescl'. real problem can't change struct , wasn't able find same problem (everybody allowed change struct solve problem). can fix problem without change struct? help. p.s. sorry... it's c lan

math - Is the double asterisk ** a valid Javascript operator? -

i solved kata on codewars , looking through of other solutions when came across double asterisk signify power of. have done research , can see valid operator in python can see nothing in javascript documentation. var findnb = m => { var n = math.floor((4*m)**.25); var sum = x => (x*(x+1)/2)**2; return sum(n) == m ? n : -1; } yet when run solution on codewars, seems work. wondering if new in es6, although have found nothing it. yes. ** exponentiation operator , equivalent of math.pow . it introduced in ecmascript 2016 (es7). for details, see proposal , chapter of exploring es2016 .

arrays - iterate json subarray data in jquery+ajax -

i'm trying data form json array , populate select field jquery , ajax, json this: { "regioni": [ { "nome": "abruzzo", "capoluoghi": ["chieti", "l'aquila", "pescara", "teramo"], "province":["ch","aq","pe","te"] }, { "nome": "basilicata", "capoluoghi": ["matera", "potenza"], "province":["mt","pz"] }, { "nome": "calabria", "capoluoghi": ["catanzaro", "cosenza", "crotone", "reggio calabria", "vibo valentia"], "province":["cz","cs","kr","rc","vv"] } ]} what want take "name" field , iterate cycle, seems not work properly:

Laravel Eloquent - Update() function always return true -

consider code return user::find($user_id)->update($data_array)?true:false; if $data_array have columns not present in user related table. above statement return true . e.g: $data_array=['not_in_the_table'=>'value']; return user::find($user_id)->update($data_array)?true:false; returns true. condition when update returns 0 i.e. false ? you cannot error false there because validation of laravel use library. for laravel 4.2 public function update($user_id) { $data_array = input::all(); $validator = validator::make( $data_array, array('name' => 'required|min:5') ); if ($validator->passes()) { // success true user::find($user_id)->update($data_array) } else { //failed false } } for more information validator hope you

database performance - Is it possible to run queries on 200GB data on mongodb with 16GB RAM? -

i trying run simple query find number of records particular value using: db.colname.find({id_c:1201}).count() i have 200gb of data. when run query, mongodb takes ram , system starts lagging. after hour of futile waiting, give without getting results. what can issue here , how can solve it? i believe right approach in nosql world isn't trying perform full query that, accumulate stats overtime. for example, should have collection stats arbitrary objects should own kind or id property can take value "totalusercount" . whenever add user, update count. this way you'll instant results. it's getting property value in small collection of stats. btw, slowness should originated querying objects non-indexed property in collection. try index id_c , you'll quicker results.

ruby - Getting wrong number when using count - Rails -

i trying total number of questions based on specific categories. used below line of code returns wrong number , cannot understand why cannot access questions directly "where" query. def questions_total number = category.where("tag ?",'1-%').includes(:questions).count end please guide me through mistakes thanks use group by sql syntax: question.group(:category_id) .joins(:category).where('categories.tag ?', '1-%') .count you can delete joins line if don't want apply filter based on category attribute.

android - Retrofit 2.0 OnFailure - Raw Response -

i'm using retrofit call web service , retrofit throwing failure, the message 'throwable` giving me java.lang.illegalstateexception: expected begin_object string @ line 1 column 1 path $ i'm assuming because .net web service throwing error , not returning json. prove need able see raw response in onfailure . there anyway can this? this code i'm using public void userloginrequestevent(final authenticateuserevent event) { call call = sapi.login(event.getusername(), event.getpassword(), os_type, deviceinfoutils.getdevicename()); call.enqueue(new callback<loggedinuser>() { @override public void onresponse(response<loggedinuser> response, retrofit retrofit) { // response.issuccess() true if response code 2xx if (response.issuccess()) { loggedinuser user = response.body(); appbus.getinstance() .post(new userisauthenticatedevent(user, event.getusername(), event.getpassword())); } els

Moving my public NPM package from Bitbucket to Github -

i bitbucket better github, sadly there's few options continuous integration bitbucket. the packages in question written me, , hosted on bitbucket: https://www.npmjs.com/package/grunt-asset-compress https://www.npmjs.com/package/node-file-parser i want these moved github, without breaking anything. afraid changing repository data not enough. "repository": { "type": "git", "url": "https://stephanbijzitter@bitbucket.org/skelware/grunt-asset-compress.git" }, image user has version 1 installed, hosted on bitbucket. change version 2 , change url github url. proceed push, both github , bitbucket. if user updates, updating version 2 , includes url of github. push more fixes , release version 3 on github, user updates again , fine. however, if user did not update version 2 , before version 3 released? npm try download version 3 bitbucket url points in version 1 ! i not want keep repositories in sync; wan

swift2 - createFileAtPath not accepting NSURL anymore -

let singleimage = "current.jpg" let path = nsurl(fileurlwithpath: nstemporarydirectory()).urlbyappendingpathcomponent(singleimage) let filemanager = nsfilemanager.defaultmanager() filemanager.createfileatpath(path, contents: imagedatafromurl, attributes: [:]) createfileatpath stopped working after upgrade swift 2 , gives following error: cannot convert value of type 'nsurl' expected argument type 'string' unfortunately nsfilemanager has no creation method operates on nsurl . in code try avoid string path usage , 1 of rare places still fall path using nsurl.path property filemanager.createfileatpath(pathurl.path!, contents: imagedatafromurl, attributes: [:])

json - Javascript forEach return value interpolated into string -

stack_html += "<div class='co-stack-layer-title'>application , data" + "<div class='row'>" + response['application , data'].foreach(generatestackitem) + "</div>" + "</div>"; stack_html += "<div class='co-stack-layer-title'>business tools" + "<div class='row'>" + response['business tools'].foreach(generatestackitem) + "</div>" + "</div>"; stack_html += "<div class='co-stack-layer-title'>devops" + "<div class='row'>" + response['devops'].foreach(generatestackitem) + "</div>" +

String pointer in C prints weird symbol -

Image
i having difficulties when trying print out string pointer after dynamically insert character @ front of char array. the parameter *str dynamic char array main whereas input single character should append first element of dynamic array after executing insert(). int main(){ //code snippet. removed other part keep question short printf("how many characters want input: "); scanf("%d", &n); str = malloc(n + 1); printf("input string class: "); scanf("%s", str); //switch statement case '1': printf("what character want insert: "); scanf(" %c", &input); insert(&str, input); break; } return 0; } void insert(char *str, char input) { char *new_str; int i, len = strlen(str); new_str = malloc(len + 1); new_str[0] = input; strncpy(&new_str[1], str, len - 1); new_str[len] = 0; (i = 0; < len; i++) { printf("%c", new_str[i]); } } when tr

xsd - HL7 2.7.1 XML schemas missing <escape> element definition -

we attempting exchange hl7 2.7.1 messages using xml encoding syntax, release 2 specification. of messages contain escape sequences in obx-5 field. hl7 version 2.7.1 messaging schemas don't define <escape> element anywhere. , "obx.5.content" type isn't defined mixed. causing schema validation fail on our message xml documents. is defect in schema? doesn't appear match written specification. need customize schema make work or has found solution? definitely defect in schema. you'll have customize make work

Select distinct rows and sum columns in DataTable VB.Net 2005 -

i have datatable contains: id pocount pototal        1              10        2              20 b        4              10 i want result of new data table bellow: id pocount pototal        3              30 b        4              10 how can using datatable? project in vb.net 2005 , cannot use linq method. best way this? i found link kinda near want. skip rows instead of summing columns when id similar. http://www.dotnetfunda.com/forums/show/2603/how-to-remove-duplicate-records-from-a-datatable linq better - upgrade later vs express - free! here 1 approach using class , dictionery public class posummary public property id string public property count integer public property total integer sub new(poid string, pocount integer, pototal integer) id = poid count = pocount total = pototal end sub end class private sub button12_click(sender object, e eventargs) handles button1

Cannot start Xampp Apache service -

i need apache , mysql services project cannot start apache service. here log: 5:45:22 pm [main] initializing control panel 5:45:22 pm [main] windows version: windows 8 64-bit 5:45:22 pm [main] xampp version: 5.6.12 5:45:22 pm [main] control panel version: 3.2.1 [ compiled: may 7th 2013 ] 5:45:22 pm [main] not running administrator rights! work 5:45:22 pm [main] application stuff whenever services 5:45:22 pm [main] there security dialogue or things break! think 5:45:22 pm [main] running application administrator rights! 5:45:22 pm [main] xampp installation directory: "c:\xampp\" 5:45:22 pm [main] checking prerequisites 5:45:23 pm [main] prerequisites found 5:45:23 pm [main] initializing modules 5:45:23 pm [main] enabling autostart module "apache" 5:45:23 pm [main] starting check-timer 5:45:23 pm [main] control panel ready 5:45:23 pm [apache] autostart active: starting... 5:45:23 pm [apache] attempting start apache serv

Can't print Unicode Bitcoin symbol in Python 2 -

i trying print unicode bitcoin symbol \u2043 in python 2. have tried adding #-*- coding: utf-8 -*- . $ python2 -c 'print u'\u0243'' raises unicodeencodeerror: 'ascii' codec can't encode character u'\u0243' in position 0: ordinal not in range(128) . however, doing python shell works. $ python2 >>> print u'\u0243' Ƀ why isn't code working? bitcoin = u'\u0243' quote = u'{:,.2f}'.format(float(val), '.2f') print bitcoin, quote on unix, if sys.stdout.isatty() returns true sys.stdout.encoding 'ansi_x3.4-1968' (ascii) should configure locale (check lang , lc_ctype , lc_all envvars) use non-ascii encoding if need print non-ascii characters. if sys.stdout.isatty() false configure pythonioencoding envvar outside script. print unicode, don't hardcode character encoding of environment inside script.

Yeoman generator gulp-angular deployment on Azure websites -

i have developed frontend using gulp-angular (yeoman generator). it's working fine on local environment. want deploy on azure websites. have uploaded code on azure websites unable start server. gulp serve //to start server on local gulp build //to create build production how can run gulp build command on azure websites. is there deployment script run on azure websites? if want build project on server creating own custom deployment script . the challenge here you'll have npm install dev tools well, , might cause issues max_path. give shot , see if works.

templates - Doxygen complains about recursive C++ class -

i have simple recursive template implements (the optimised version of) euclid's algorithm. doxygen complains it: /usr/home/kamikaze/stark/yggdrasil/src/units/units.hpp:335: warning: detected potential recursive class relation between class units::euclid , base class units::euclid< rhs, lhs%rhs >! /usr/home/kamikaze/stark/yggdrasil/src/units/units.hpp:335: warning: detected potential recursive class relation between class units::euclid , base class euclid< rhs, lhs%rhs >! /usr/home/kamikaze/stark/yggdrasil/src/units/units.hpp:335: warning: detected potential recursive class relation between class units::euclid , base class units::euclid< rhs, lhs%rhs >! /usr/home/kamikaze/stark/yggdrasil/src/units/units.hpp:335: warning: detected potential recursive class relation between class units::euclid , base class euclid< rhs, lhs%rhs >! i'm dumbfounded why complaint/warning. think recursive types common , legal. it's 1 of many recursive templates, 1

javascript - how to show the hidden <dl> elements one by one or all at the same time? -

i trying show hidden <dl> tags when click "view more". in example have 3 <dl> elements, more or less. html <dl class="dl"> <dt><b>name:</b></dt> <dd>my name</dd> <dt><b>department</b></dt> <dd>my department</dd> <dt><b>email</b></dt> <dd>my email</dd> </dl> <br/> <dl class="dl"> <dt>name:</dt> <dd>my name</dd> <dt>department</dt> <dd>my department</dd> <dt>email</dt> <dd>my email</dd> </dl> <br/> <dl class="dl"> <dt>name:</dt> <dd>my name</dd> <dt>department</dt> <dd>my department</dd> <dt>email</dt> <dd>my email</dd> </dl> jquery $(function(){ $("#dl").each

bootstrap, row into navbar -

is possible turn col navbar? i've got top navbar. i'd 1 below turn navbar md , lower screens. <div class="row" id="bottominforow"> <div class="col-md-4"> <ul class="list-inline"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </div> </div> honestly, maybe you're looking isn't clear far functionality goes it's pretty simple. the example uses columns in conjunction navbar-nav class while using css adjust custom navbar class enclosed in. (**most of css better display in general , not neccessary) see working example snippet @ full page. .navbar.nav-lower { background: #eee; margin-top: -20px; border-radius: 0; border: none; text-align: center; } .navbar.nav

Patterns for collections of polymorphic objects in Polymer? -

say have 2 separate lists of polymorphic objects: shape -> circle , shape -> rectangle. shape contains properties "name" , "description", while circle contains properties "center" , "radius" , rectangle contains "length" , "width" properties. i'd have single polymer component, "shape-list", able handle display of either list of circles or list of rectangles , display specific properties of each type in list. "shape-list"'s template might so: <template> <ul> <template is="dom-repeat" items="[[shapes]]" as="shape"> <li> <shape-entry shape="[[shape]]"> <!-- user of shape-list knows whether want display rectangles or circles. want customize display of each shape-entry information specific each shape using sort of prototype element supplied

sql - How do I update a table with a form in access using VBA or a Macro? -

i doing best build first database, have come against problem cannot find answer to. complete newbie in forum , writing sort of code please gentle. i trying create new record in table when student's name double clicked inside list box inside form. list box want take first (studentid) column value = lststudent combo box want take second (courseid) column value from: cbocourseid text box want take third (noteid) column value = txtcoursenoteid the new record being created in desired table , there no incorrect code errors there no values being carried across fields. autonumber being created (attendanceid) other columns blank. here code: private sub lststudent_dblclick(cancel integer) currentdb.execute "insert tblattendance (studentid, courseid, noteid) values ('me.lststudent','me.cbocourseid','me.txtcoursenoteid')" end sub the fields populated, isn't issue. formatting correct target fields , can't think of else in way.

How to tell if a string has exactly 8 1's and 0's in it in python -

i want return boolean value true or false depending on if string contains 1's , 0's. the string has composed of 8 1's or 0's , nothing else. if contains 1's or 0's, return true , if not return false . def isitbinary(astring): if astring == 1 or 0: return true else: return false this have far i'm not sure how compare both of numbers see if has length of 8 1's , 0's. you can use all , check length make sure 8. all(c in '10' c in astring) , len(astring) == 8 example: astring = '11110000' all(c in '10' c in astring) , len(astring) == 8 >>> true the main benefit of doing on other methods short-circuit if finds 0 or one.

python 2.7 - Why do the power spectral density estimates from matplotlib.mlab.psd and scipy.signal.welch differ when the number of points per window is even? -

Image
matplotlib.mlab.psd(...) , scipy.signal.welch(...) both implement welch's average periodogram method estimate power spectral density (psd) of signal. assuming equivalent parameters passed each function, returned psd should equivalent. however, using simple sinusoidal test function, there systematic differences between 2 methods when number of points used per window (the nperseg keyword scipy.signal.welch ; nfft keyword mlab.psd ) even , shown below case of 64 points per window the top plot shows psd computed via both methods, while bottom plot displays relative error (i.e. absolute difference of 2 psds divided absolute average). larger relative error indicative of larger disagreement between 2 methods. the 2 functions have better agreement when number of points used per window odd , shown below same signal processed 65 points per window adding other features signal (e.g. noise) diminishes effect, still present, relative errors of ~10% between 2 methods when num