Posts

Showing posts from August, 2012

javascript - multiselect box will not populate without alert -

i can't post code try important pieces in here. problem have populate multiselect box database selected items , add selected attribute. works in ie 7 testers using, unfortunately i'm on ie 9 , of users on ie 9. code doesn't work on ie 9 or on firefox. weird thing work if stick alert after call function populates multiselect. after getting selected values database through ajax call use var oldvalues.push($(this).find("value_id).text()); i alert of oldvalues there 31,32,45 use $("drop2-input").val(oldvalues); if put alert after line works. i have spent majority of day checking every line of code there no missing semicolons, no curly brackets out of place, , no parentheses out of place. know of way make work. oh tried using timeout pause code stoped rest of page loading. this should work you. take @ jsfiddle put togethre you: http://jsfiddle.net/douglasloyo/netjd/ var json = [ {name:"texas", value:1}, ...

Is Node.js useful for "classic" style websites? -

i considering using nodejs make non-realtime app. example, website blog, forum, or image boards. i have read nodejs when used asynchronous jobs. wondering result when used serve lot of static files, big images, css & js files, etc. is true when sending file (suppose it's 2-3mb), whole server blocked until transfer complete? have read might possible use os's sendfile() syscall job. in case, express support this? no not true. can send files large (much larger 2-3 mb) without blocking. people complain things blocking node event loop don't know they're doing. you don't need use express behavior. that being said, if want file server, there's no reason use nodejs. point apache @ directory, , let fly. why reinvent wheel use new sexy technology, when old faithful fine? if use node simple http server, may recommend simple command line module. https://npmjs.org/package/http-server i haven't looked @ code of module, not optimized la...

sql - Get a Row if within certain time period of other row -

i have sql statement using return number of rows database: select as1.assettagid, as1.tagid, as1.categoryid, as1.description, as1.homelocationid, as1.parentassettagid assets as1 inner join assetsreads ar on as1.assettagid = ar.assettagid (ar.readpointlocationid='readpoint1' or ar.readpointlocationid='readpoint2') , (ar.datescanned between 'lastscan' , 'now') , as1.tagid!='000000000000000000000000' i wanting query row oldest datescanned query , row database if there 1 within period of time row (say 5 seconds example). oldest record relatively simple selecting first record in descending sort, how second record if within time period of first? i know process multiple queries, there way combine process 1 query? the database using sql server 2008 r2. also please note datescanned times placeholders , taking care of in application using query. here general way approach it. oldest scan date using min() w...

Php hash return type: Not string(64)? -

i performing hash on various data. on data, after result of hash, can var_dump of hash, , print: > string(64) "<hash goes here>" however, 1 of data hashing, result prints hash, no "string(64)" preceding it, , no quotes around it. > <hash goes here> what cause of this? possibly due size of data? code example, of should see: $string= "hello"; $hash = hash( 'sha512', $string, true ); var_dump($hash); this should print: string(64) "<hash value of 'hello'>" in case, replace "hello" contents of long php file. reason var_dump not printing value in quotes "string(64)" in front of it. you using third parameter set true in hash function, output in binary format, not suitable viewed in standard output. previous hash may contain control chars suppresses part of next output. binary data should viewed in hex form (third parameter set false ) or saved file , browsed hex...

javascript - jquery .hide() function - Hide mobile, Display Desktop -

i'll try best set scenario can understand question. my site taking advantage of css media queries span between screen resolutions. have main drilldown menu can not hidden on page load, otherwise menu not correctly calculate it's height, , not display properly. as way still able hide menu when needed, have found workaround hides menu, yet still allows menu correctly calculate it's height on page load. $(document).ready(function () { $(".hide-menu").hide(); var $drilldown = $("#drilldown"); }); this great pages not require main menu displayed on both mobile , desktop resolutions. however, product pages solution not work. need menu hide on load mobile resolutions, display on load desktop resolutions. can think of solution work? i'm stumped. here html: <div class="drill-down-wrapper hide-menu hide-on-load hide-pd-page"> <div id="drilldown-breadcrumbs" class="breadcrumbs skin-colorful">...

Counting elements in a list of lists in python -

hope u can me w/ python function: def comparapal(lista):#lista list of lists each list has 4 elements listapalabras=[] item in lista: if item[2] in eagles_dict.keys():# filter list if 3rd element corresponds key in dictionary listapalabras.append([item[1],item[2]]) #create new list elements 2 , 3 the listapalabras result: [ ['bien', 'np00000'], ['gracia', 'ncfp000'], ['estar', 'vaip1s0'], ['bien', 'rg'], ['huevo', 'ncms000'], ['calcio', 'ncms000'], ['leche', 'ncfs000'], ['proteina', 'ncfs000'], ['francisco', 'np00000'], ['ya', 'rg'], ['ser', 'vsis3s0'], ['cosa', 'ncfs000'] ] my question is: how can compare 1st element of each list if word same, compare tags 2nd element. sorry being ambiguous, fuunction has return list of lists w/ 3...

android - Is there anyway to find out the colour of the underlying view? -

im developing floating app tell colour of underlying app. there anyway this?. android sandboxes individual applications, can interact other apps through exposed services - intents , content providers. read more.

ruby - Rails - two attributes one input field - Whats the Syntax? -

i need html output form <input class="text valid" id="contacts_custom_field_phone_number_50754" name="contacts[custom_field][phone_number_50754]" size="30" type="text"> this got far = f.label "phone" %br = f.text_field :custom_field=>{:phone_number_50754=>"123-213-2134"} this wrong works in rails console , posts data api how write code output need? when in rails console :custom_field=>{:phone_number_50754=>"123-123-2134"} it posts api you can use fields_for : - f.fields_for :custom_field |custom_fields| = custom_fields.text_field :phone_number_50754

ios - Disable a Navigation Bar Button upon Application Launch -

i have application requires select client work when application launched. initiating segue app delegate modal view allows user make selection. view has left bar button says "cancel" , dismissed view. want disabled when user first selects client, enabled subsequent times user opens client select pane. i have iboutlet in select client view called cancelbutton. in prepareforsegue method in view controller launching segue, have if ([segue.identifier isequaltostring:@"selectclient"]) { if (firstsegue) { selectclientviewcontroller *select = (selectclientviewcontroller *)segue.destinationviewcontroller; select.cancelbutton.enabled = no; } firstsegue = no; } however, button remains enabled on first launch. appreciated. when prepareforsegue called view hasn't been loaded. if don't make during method view won't loaded till later. if view hasn't been loaded outlets aren't available (they haven't been loaded yet either). ...

Android: Emulator in Android Studio doesn't start/launch -

the problem when want start emulator nothing happens only appears: waiting device. "c:\program files (x86)\android\android-studio\sdk\tools\emulator.exe" -avd test-avd -netspeed full -netdelay no even if create complete new project doesn't work. i waited 60 mins nothing happens. thats why i'm asking. does have idea how fix ? best regards well, android studio waiting start virtual device. can avd manager --> 'select device chose in android studio' --> start. hope answers question

Using bash variables for range in sed -

sed -n '5,10 p' < /proc/cpuinfo prints 5-10 lines of file /proc/cpuinfo i want use start=5 end=10 sed -n '$start,$end p' < /proc/cpuinfo so can change values of start , end form script. you need use double quotes variable expansion: start=5 end=10; sed -n "$start,$end p" < /proc/cpuinfo

php - Saving Data: Check if value has changed? -

lets form has bunch of fields, , 1 or 2 of them changed , need saved. you: just update database values, regardless if have changed. use form states, , post values have changed. check new value against old value, externally class. check new value against old value, internally, in set_property() method. then you'd have keep array of updated fields saved... i might wrong, seems examples i've seen #1. if have large list of 100+ posts in 1 table, don't want loop through , save them every time update 1 field... i'd use #2 , keeping track of has changed since last saved.

ios - In ARC, what happens to the memory of an object that is reinitialized? -

let's have method called test. test{ nsstring *answer = [[nsstring alloc] initwithstring:@"value 1"]; answer = [[nsstring alloc] initwithstring:@"value 2"]; } when answer got reinitialized, happens memory of first initialization under arc? the first string released (the string created in [[nsstring alloc] initwithstring:@"value 1"]; ) answer in case object strong ownership qualification. docs , happens when assign answer : for __strong objects, new pointee first retained; second, lvalue loaded primitive semantics; third, new pointee stored lvalue primitive semantics; , finally, old pointee released. not performed atomically; external synchronization must used make safe in face of concurrent loads , stores.

windows - How to connect to a sub-domain FTP in JAVA -

i trying write java program connect ftp. have downloaded .jar file apache , added lib folder in project. when try connect ftp per code below, java.net.unknownhostexception if use ftp:// subdomain.example.com - java.net.unknownhostexception ftp.subdomain.example.com - java.net.unknownhostexception ftp:// example.com - java.net.unknownhostexception ftp.example.com - works! all files @ ftp:// subdomain.example.com/ , don't want change in ftp. if try open ftp:// subdomain.example.com/ in google chrome browser, asks username , password. import java.io.ioexception; import java.net.socketexception; import org.apache.commons.net.ftp.ftpclient; import org.apache.commons.net.ftp.ftpfile; public class connecttoftp { public static final void main(string[] args) throws socketexception, ioexception { ftpclient ftp = new ftpclient(); try { ftp.connect("ftp://subdomain.example.com"); } catch (exception e) { system.out.println...

r - How to call on.exit() from parent? -

quite few of functions accept file argument (which defaults null ) sets graphics output file. e.g., foo() plot screen, , foo(file="bar.png") write plot file "bar.png" . they have code snippet in them: if (!is.null(file)) { cat("*** writing",file,"\n") do.call(tools::file_ext(file),list(file = file)) # set device on.exit(dev.off()) } i wish create function replace these 5 lines, but, alas, cannot because on.exit reset graphics device early. what people in such situation? this sort of repetition best dealt creating function takes code block , evaluates in special context . example, write: capture_png <- function(file, code) { if (!is.null(file)) { message("writing ", file) png(file) on.exit(dev.off()) } code } capture_png(null, plot(1:10)) capture_png("test.png", plot(1:10))

java - LocalVariableTableParameterNameDiscoverer does not work -

i want parameter names of method of interface outside package. looks localvariabletableparameternamediscoverer can parameter names of methods local classes. not parameter names of methods interfaces outside package. please help private localvariabletableparameternamediscoverer namer =new localvariabletableparameternamediscoverer(); class currentclass = class.forname("com.soa.process.bpel.runtime.script.scriptedalertreporter"); methods=currentclass.getdeclaredmethods(); (int j = 0; j < methods.length; j++) { method=currentclass.getmethod(methods[j].getname(),methods[j].getparametertypes()); parameternames = namer.getparameternames(method); if(parameternames!=null && parameternames.length>0) { } } it's nothing whether interface outside of package. l...

text - How do I replace line breaks with spaces in Processing? -

i imported txt file processing. replace line breaks imported text file spaces. possible using processing? a couple of things... since imported txt file, guess loadstrings() method assume left array of strings. mean 2 things, either join array 1 string or find , replace line breaks (or combination). lets see both possibilities. first assume similar string array loadstrings() gives you: string [] importedtext = {"aaaa bbb","cccc dddd","eeee ffff gggg"}; if want join array 1 single string, iterate on array , add elements string so: string singlelinetext = ""; for(int = 0;i < importedtext.length; i++) { singlelinetext += importedtext[i] + " "; } this simplest , less confusing way it, unless have huge array of strings , after performance ( a debatable matter these days ) can use stringbuilder this: stringbuilder strb = new stringbuilder(); for(int = 0;i < importedtext.length; i++) { strb.append(importedt...

javascript - Is it possible to combine Morris.js (RaphaelJS) with Web Workers? -

i'm trying use web workers improve performance of website, generates graphs using library morris (which in turn uses raphael). problem morris manipulates dom (not much, pass div graph drawn). understand web workers not allow manipulate dom. has tried combine these 2 elements (morris -or raphael- , web workers)? thanks in advance! pd: excuse bad english. raphael creates svg nodes in dom bigger issue. seaching way let time consuming rendition of complex stuff in worker.

how do I create a "blank" redirect page in HTML that has Google Analytics code in it? -

how create "blank" html page redirects subfolder while still having block of google analytics code in google analytics can "see" tracking code on "home page"? use javascript redirect "blank" page place google code on blank site use javascript redirect wherever want , make sure have same google analytics code on landing page sending them.

convert strings in separate lists to unicode - python -

what's best way convert every string in list (containing other lists) unicode in python? for example: [['a','b'], ['c','d']] to [[u'a', u'b'], [u'c', u'd']] >>> li = [['a','b'], ['c','d']] >>> [[v.decode("utf-8") v in elem] elem in li] [[u'a', u'b'], [u'c', u'd']]

Animation when add or remove item from GridView XAML -

how create own animation when item add or remove gridview? example change colour dark light. if item grid: <grid.transitions> --> there can predefinied *themetransitions? </grid.transitions> is other way this? tim correct transitions pre-defined @ point. however, should able achieve scenario using storyboard. there several ways this, e.g. retemplating gridviewitem , adding new "loading"/"unloading" visual states. here simple way achieve scenario putting storyboard in itemtemplate: mainpage.xaml: <gridview x:name="mygv"> <gridview.itemtemplate> <datatemplate> <grid loaded="grid_loaded" x:name="templateroot" opacity="0" background="white"> <grid.resources> <storyboard x:key="loadedstoryboard"> <doubleanima...

windows 8 - Shutting down mysqld in Cygwin -

how supposed shutdown mysqld faster cygwin (without killing process in task manager) , prevent these errors? this how started it: $ /usr/bin/mysqld_safe & [1] 4440 chloe@xps ~ $ 130809 17:27:09 mysqld_safe logging '/var/lib/mysql/xps.err'. chown: invalid user: `mysql' 130809 17:27:10 mysqld_safe starting mysqld daemon databases /var/lib/mysql when try shut down, prints forever , won't respond ^c: $ /usr/sbin/mysqld.exe shutdown 130809 17:29:26 [warning] setting lower_case_table_names=2 because file system /var/lib/mysql/ case insensitive 130809 17:29:26 [note] plugin 'federated' disabled. 130809 17:29:26 innodb: innodb memory heap disabled 130809 17:29:26 innodb: mutexes , rw_locks use gcc atomic builtins 130809 17:29:26 innodb: compressed tables use zlib 1.2.7 130809 17:29:26 innodb: initializing buffer pool, size = 128.0m 130809 17:29:26 innodb: completed initialization of buffer pool innodb: unable lock ./ibdata1, error: 11 innodb: check not ...

ios - UICollectionViewLayout doesn't update zIndex when changing layouts -

Image
i have 2 uicollectionviewlayouts work fine when used on own when switching between 2 layouts using setcollectionviewlayout:animated: zindex of layout being animated doesn't use own zindex values, instead uses zindex values of original layout. here 2 layouts on own: in layout 1 cells stacked item 0 on top. in layout 2 cells stacked item 0 on bottom. in layout 1 set zindex with: [attributes setzindex:100 - [indexpath item]]; in layout 2 set zindex with: [attributes setzindex:100 + [indexpath item]]; if start layout 1 , change layout 2 end this: if start layout 2 , change layout 1 end this: i've experimented setting zindex in both layoutattributesforelementsinrect: , layoutattributesforitematindexpath: , i've found when switching layouts, layoutattributesforelelmentsinrect: gets called once on layout being animated , layoutattributesforitematindexpath: gets called many times on both layouts animated transition happening. i noticed calls layout...

database - I am trying to display data from rows by date column in android app -

i writing edittext , textview database in app. want display added specific column; have date_selected. having major block , appreciated. below code section: public class calendardbadapter { public static final string key_title = "title"; public static final string date_selected = "date"; public static final string weight_input = "weight"; public static final string reps_input = "reps"; public static final string key_body = "body"; public static final string key_rowid = "id"; private static final string tag = "calendardbadapter"; private databasehelper mydbhelper; private sqlitedatabase mydatabase; private static final string database_name = "exerciselog"; private static final string database_table = "exercises"; private static final int database_version = 1; //database creation sql statement private static final string database_creat...

javascript - How do I prevent PHP file from popping up after submitting contact form? -

right now, whenever click submit button on contact form on website, brings me page www.mysite.com/php/function/email.php, rather running email.php in background want to. the website supposed allow submit contact form, button fade away , fade in "your message has been sent!", fade button. html: <form name="contact form" id='contact_form' method="post" action="php/function/email.php"> <div class="row half"> <div class="6u"> <input name="name" placeholder="name" type="text" class="text" /> </div> <div class="6u"> <input name="email" placeholder="email" type="email" class="text" /> </div> </div> <div class="row half"> <div class="12u"> <textarea name="message" placeholder="messag...

java - extract multiple instances of a pattern occuring in string? -

i have string following: string text = "this awesome wait what? [[foo:f1 ]] [[foo:f2]] [[foo:f3]] texty text [[foo:f4]] now, trying write function: public string[] getfields(string text, string field){ // somethng } enter code here should return [f1,f2,f3,f4] if pass text field = "foo" how do cleanly? use pattern: pattern.compile("\\[\\[" + field + ":\\s*([\\w\\s]+?)\\s*\\]\\]"); and values of first capturing group. string text = "this awesome wait what? [[foo:f1]] [[foo:f2]]" + " [[foo:f3]] texty text [[foo:f4]]"; string field = "foo"; matcher m = pattern.compile( "\\[\\[" + field + ":\\s*([\\w\\s]+?)\\s*\\]\\]").matcher(text); while (m.find()) system.out.println(m.group(1)); f1 f2 f3 f4 you can put matches in list<string> , convert array.

symfony - Is it possible to implement sonata_type_collection within sonata_type_collection? -

viewing post believe possible, don't know how has configured entities. sonata admin bundle type collection customisation i have admin files identical him. these other post found capability not supported sonata. https://github.com/sonata-project/sonataadminbundle/issues/262 https://github.com/sonata-project/sonataadminbundle/issues/802 please, suggest figure out it! update: (dour high arch) .../simbundle/admin/empleadoadmin.php protected function configureformfields(formmapper $formmapper) { $formmapper ->with('tecnico') ->add('empleadotecnico', 'sonata_type_collection'), array('edit' => 'inline','sortable'=>'pos','inline' => 'table')) ->end() ; } .../simbundle/admin/tecnicoadmin.php protected function configureformfields(formmapper $formmapper) { $formmapper ->add('salariohora',n...

javascript - GeoLocation in Android Webview -

i have android app uses web view. web view works well, except js uses getcurrentposition locate user. have read issue , understand need have right permissions, , have set setjavascriptenabled(true); . have done these things, still having lot of trouble android app. prompt requests permission obtain user's location doesn't come up. can me fix this? have included relevant java file, permissions manifest.xml, , js gets user's location. wonderful! here java file: package com.website.appname; import android.app.activity; //other imports here class myclient extends webchromeclient { @override public void ongeolocationpermissionsshowprompt(string origin, callback callback) { callback.invoke(origin, true, false); } } public class locationpage extends activity { webview webview; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.embed); ...

c# - One of the parameters of a binary operator must be the containing type -

got error 1 of parameters of binary operator must containing type can not see wrong operator overloadin error @ public static complex operator + (complex c1, complex c2) namespace testcomplex { class program { public static complex operator +(complex c1, complex c2) { return new complex(c1.real + c2.real, c1.imaginary + c2.imaginary); } public static complex operator /(complex c1, complex c2) { return new complex(c1.real / c2.real, c1.imaginary / c2.imaginary); } public static complex operator *(complex c1, complex c2) { return new complex(c1.real * c2.real, c1.imaginary * c2.imaginary + c1.real * c2.imaginary + c2.real * c1.imaginary); } public static complex operator -(complex c1, complex c2) { return new complex(c1.real - c2.real, c1.imaginary - c2.imaginary); } //public static complex sqrt -(complex c1, complex...

converting JSON python time to regular time -

i have following python time value in json format...any inputs on how convert to regular time format u'lastupdated': 1358294533 datetime.fromtimestamp datetime module should it. for example: >>> datetime import datetime >>> d = datetime.fromtimestamp(1358294533) >>> d.isoformat() '2013-01-15t19:02:13' for getting more controlled string representation of datetime use datetime.strftime function.

python - Multithreaded screen scraping help needed -

i'm relatively new python, , i'm working through screen- scraping application gathers data multiple financial sites. have 4 procedures now. 2 run in couple minutes, , other two... hours each. these 2 information on particular stock symbols have in csv file. there 4,000+ symbols i'm using. know enough know vast majority of time spent in io on wire. it's essential these down 1/2 hour each (or, better. ambitious?) of practical use me. i'm using python 3 , beautifulsoup. i have general structure of i'm doing below. i've abbreviated conceptually non essential sections. i'm reading many threads on multiple calls/ threads @ once speed things up, , seems there lot of options. can point me in right direction should pursue, based on structure of have far? it'd huge help. i'm sure it's obvious, procedure gets called along other data download procs in main driver module. in advance... from bs4 import beautifulsoup import misc modules class stock...

c - Why vectorizing the loop does not have performance improvement -

i investigating effect of vectorization on performance of program. in regard, have written following code: #include <stdio.h> #include <sys/time.h> #include <stdlib.h> #define len 10000000 int main(){ struct timeval sttime, endtime; double* = (double*)malloc(len*sizeof(*a)); double* b = (double*)malloc(len*sizeof(*b)); double* c = (double*)malloc(len*sizeof(*c)); int k; for(k = 0; k < len; k++){ a[k] = rand(); b[k] = rand(); } gettimeofday(&sttime, null); for(k = 0; k < len; k++) c[k] = a[k] * b[k]; gettimeofday(&endtime, null); file* fh = fopen("dump", "w"); for(k = 0; k < len; k++) fprintf(fh, "c[%d] = %f\t", k, c[k]); fclose(fh); double timee = (double)(endtime.tv_usec + endtime.tv_sec*1000000 - sttime.tv_usec - sttime.tv_sec*1000000); printf("time elapsed: %f\n", timee); return 0; } in code, in...

nosql - Google App Engine - use key_name or ReferenceProperty for quick lookup -

i have user account model , profile model each user. setting key_name of both unique generated id. id stored in session object , way can lookup either user account or profile model using same id key_name. best option or should use referenceproperty instead connect account , profile? class useraccount(db.model): datecreated = db.datetimeproperty(auto_now_add=true) userid = db.stringproperty() password = db.stringproperty() emaillower = db.stringproperty() class profile(db.model): datecreated = db.datetimeproperty(auto_now_add=true) firstname = db.stringproperty() firstnameupper = db.stringproperty() lastname = db.stringproperty() lastnameupper = db.stringproperty() topictags = db.stringlistproperty() = db.stringproperty(multiline=true) experience = db.stringlistproperty() account = useraccount(key_name=uniqueid) profile = profile(key_name=uniqueid) later can either id. imagine limits me 1 profile per user account should fine. th...

javascript - zoom an image on a coordinate using jquery on onclick -

i want zoom jpeg image predefined image coordinates using onclick function. have set of coordinates (x1,y1) , (x2,y2) , want zoom on these coordinates onclick button. please give me solution using jquery or ajax. you enlarge image keep container fixed size e.g: $('button').on('click', function () { var coords = '100,100'.split(','); $('img').width('400px'); $('img').css('marginleft', '-' + coords[0] + 'px'); $('img').css('margintop', '-' + coords[1] + 'px'); }); demo: http://jsfiddle.net/qy7ba/

apache - .htaccess deny from all doesn't work -

my problem want deny access folder can't. i've put .htaccess file in folder these lines: order deny,allow deny any idea of can happening? i it! due apache configuration. in foo.conf of sites-avaiables directory had: allowoverride none as apache doc says, allowoverride description: types of directives allowed in .htaccess files when changed to: allowoverride it works perfectly! can configure specific options: allowoverride directive-type directive-options at: apache.org

github - What is git-repo init and git-repo sync? -

i'm using google's git-repo plugin. according understanding repo sync download whole source code (i.e. previous revisions) repository. why taking lot of time complete whole process. can download latest commit repository? i don't use repo, appears can pass --depth flag repo init . using repo init -u url --depth=1 . depth flag gets passed git-clone , create repo part of history: --depth <depth> create shallow clone history truncated specified number of revisions. shallow repository has number of limitations (you cannot clone or fetch it, nor push nor it), adequate if interested in recent history of large project long history, , want send in fixes patches.

c++ - set get position of an element -

i want solve following problem: given vector of n elements, find number of swaps insertion sort algorithm needs sort. ex: n = 5 2 1 3 1 2 answer: 4 explanation(step step insertion sort algorithm): initialy: 2 1 3 1 2 1 2 3 1 2 ; 1 swap 1( 1 goes left) 1 2 3 1 2 ; 0 swaps 1 1 2 3 2 ; 2 swaps ( 1 goes 2 pos left ) 1 1 2 2 3 ; 1 swap ( 2 goes 1 pos left) my solution i keep position of every item in initial array can remove set later based on value , position.(1st loop) count number of elements smaller current number add them counter , remove element set. ( 2nd loop ) as can see, problem std::distance has linear complexity cause set has bidirectional iterators. how can o(1) complexity without having implement own tree? int count_operations(vector<int> &v) { set<pair<int, int>> s; // o(n * logn) for(int = 0; < (int) v.size(); ++i) { s.insert(make_pair(v[i], i)); } int cnt = 0; // desired: o(n * log n...

testing - go test some functions/suites from package only -

is possible split testing process in go package ? go test package - uses function test* in *_test.go files in package. if have lot of tests , try tdt rather boring receive test logs. see 'go test' , 'go testflag'. quoting later: ... -run regexp run tests , examples matching regular expression. ...

jquery mobile multipage app, chrome navigates multiple times to domain -

i have jquery-mobile multipage app (pure client-side) works on ff, chrome navigates multiple times domain i included alerts (indicating event , hash of url) in 2 events: - $( document ).one("pageshow", '.page',function() { - $( window ).on("navigate", function() { pageshow has .one attachment, still triggered multiple times. that caused src="#" attributes of iframes inside popup divs. changed src="#" src="". (i change src of iframe when popup poping-up prevent unnesesery loads of map.html)

php - JQuery don't recognized my (well formed) HTML tag. Possible BOM -

jquery print syntax error when try interpret ajax response apache server. file printed in php smarty template engine. here simple minimal working exemple of "bug" (from chromium javascript terminal) > $.post('newtasklist',{name: 'hello'},function(ans){console.log($(ans))}) xhr finished loading: "http://localhost/narasimha/newtasklist". jquery-1.9.1.js:8526 uncaught error: syntax error, unrecognized expression: <li><a><input type="hidden" class="listid" value="4" />hello(0)</a></li> as see, it's not problem in html tag. thought bom (i work under gedit 3.6.2), i've bomstrip-files every .php , .tpl files of project directory... hasn't changed anything. in addition, i've add ans.replace(/^\ufeff/, '') answer script, don't work either. does think solution? edit: i've tried count number of bytes in answer. tell me "75", 2 bytes mor...

jquery - bootstrap/html -- How do I get the mobile slide-down nav to work on desktop resolutions? -

i've been trying mobile nav style work on desktop, can't seem work. i'm using bootstrap. i'd there single 'drop down' button on mobile reveals nav items. this attempted in html, leaving bootstrap css untouched: <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <div class="nav-collapse collapse"> <ul class="nav"> <ol id="toc"></ol> <script type=...

jquery - Detect if anchor is linked to an ID -

i wan smooth scroll when anchor clicked, first want check if anchor link linked id . if there hash don'nt scroll. like: <a href="#">do not scroll</a> <a href="#anyid">yes scroll</a> my current code scroll on click every anchor have hash. please fix code not scroll if anchor has hash $('a[href^="#"]').click(function (e) { e.preventdefault(); var target = this.hash; if (typeof($(target).offset()) != 'undefined') { $('html, body').animate({ scrolltop: $(target).offset().top - 60 }, 1000); } }); if sure element exist each anchor not contain hash, change selector to: $('a[href^="#"][href!="#"]') explicitly testing existence of element though.

In C#, SQLite randomly throws "Constraint failed\r\nColumn ... is not unique" -

i'm using entityobjects in c# , backend sqlite. system information: windows xp (up-to-date), vs2010 premium, system.data.sqlite 1.0.88.0 (3.7.17) the table schema is: create table [transaction] ( [primary_key_col] integer primary key autoincrement, [transaction_code] int not null, [account_code] int not null, [category_code] int not null, [transaction_date] date not null, [description] varchar(50)); public partial class transaction : entityobject represents table. to add new transaction, call following code: transaction transaction = new transaction() { description = _desc, transaction_code = generatehash(_desc), account_code = _acccode, category_code = _catcode, transaction_date = datetime.now }; dbentities.transactions.addobject(transaction); dbentities.savechanges(system.data.objects.saveoptions.acceptallchangesaftersave); works fine after adding few rows, following exception: constraint failed\r\ncolumn account_code not ...

c - Does Intel array notation and elementary functions vectorize well with Xeon Phi ISA? -

i try find proper material explains different ways write c/c++ source code can vectorized intel compiler using array notation , elementary functions. materials online take trivial examples: saxpy, reduction etc. there lack of explanation on how vectorize code has conditional branching or contains loop loop-dependence. for example: there sequential code want run different arrays. matrix stored in major row format. columns of matrix computed compute_seq() function: #define n 256 #define stride 256 __attribute__((vector)) inline void compute_seq(float *sum, float* a) { int i; *sum = 0.0f; for(i=0; i<n; i++) *sum += a[i*stride]; } int main() { // initialize float *a = malloc(n*n*sizeof(float)); float sums[n]; // following line not going valid, somthing this: compute_seq(sums[:],*(a[0:n:1])); } any comments appreciated. here corrected version of example. __attribute__((vector(linear(sum),linear(a)))) inline void compute_seq(float *sum...

C# richtextbox data clipped while reading from serial port -

i writing c# program continuously take data serial port , display on rich text box of wpf. problem when use below code, first bit of every hex value clipped , output (say) b 3c 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f 3f instead of getting 0b 3c ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff. why happening , mistake making? have checked terminal software , data receiving correct. while displaying in program clips first bit. also how separate first 2 , last 2 bytes , stop being displayed on richtextbox. code below: string received_data = serialport1.readexisting(); char[] store_char_array = received_data.tochararray(); string display_text = "" ; foreach (var in store_char_array) { string hex_value = string.format("{0:x}", convert.touint32(i)); display_text += hex_value + " "; } invoke(new action(() => richtextbo...

Create list of numbers mirrored around zero (python) -

i think should simple question... it's been holding me time :( i wish create list of numbers, centred (as were) on zero, input specifies maximum , increment. so, max = 100 increment = 1 would return [-100,-99,-98,...,-1,0,1,...,99,100] and max = 35 increment = 0.2 would return [-35.0,-34.8,...,-0.2,0,0.2,...34.8,35.0] if increment doesn't divide neatly maximum, needs make short last step (e.g. if counting 1 in 0.3 increments, run [-1.0,-0.6,-0.3,0.0,0.3,0.6,0.9,1.0] list(numpy.linspace()) seems way go seem having complete mental block on how make work in way described simplest cases. suggestions appreciated! edit: own solution was def mylist(stop,step): = list(np.arange(0,-stop,-step))+[-stop] a.reverse() b = list(a) c = list(np.arange(0,stop,step))+[stop] d = b+c d.remove(0) e = list(d) return e which horribly clunky, can see. the best answer was: def mirrored(maxval, inc): x = np.arange(inc, maxval, inc...