Posts

Showing posts from February, 2011

angular - Typescript, @ngrx and default store values -

i think missing obvious trying work @ngrx . trying use nested reducers, , want able return default starting child values. child export const counter:reducer<number> = (state:number = 0, action:action = {type:null}) => { switch (action.type) { my question how use initialise counter. counters.ts looks like export const counters:reducer<number[]> = (state:number[] = [], action:action) => { switch (action.type) { case add_counter: return [counter(), ...state]; this works have typescript error on counter: supplied parameters not match signature of call target , i'm wondering how around this. i'm using @ngrx, provides this: export interface action { type: string; payload?: any; } export interface reducer<t> { (state: t, action: action): t; } export class store<t> extends behaviorsubject<t> { private _storesubscription: subscription<t> constructor(private _dispatcher:dispatche

javascript - how to render a partial by passing an id through jQuery? -

Image
i feel dumb , ashamed. started learning jquery , got stuck @ first day. basically, building of in ruby on rails, , have list of clients basic info name, address, phone number, etc. in picture below page layout (yes, know.. born artist). in left table, display clients have in database, first column represents client's id , second column shows names. in right table (it partial), display full client's info. my objective this: clicking on row, on left table, right table update , show info related client selected. here tried : <script> $('#table_clients tbody').on('click', 'tr', function() { $("#container_info").replacewith( '<%= j render :partial => "client_info", :locals => {:client => 1} %>' ); }); </script> notice manually specified client's id. my question is, how can identify row selected , pass id erb fragment ? i can id calling this: $(this).find(':nth-child

ggplot2 - R ggplot add new roc curve -

Image
i want add roc curve ggplot chart, returns error code. library(ggplot2) library(plotroc) set.seed(2529) d.ex <- rbinom(200, size = 1, prob = .5) m1 <- rnorm(200, mean = d.ex, sd = .65) m2 <- rnorm(200, mean = d.ex, sd = 1.5) test <- data.frame(d = d.ex, d.str = c("healthy", "ill")[d.ex + 1], m1 = m1, m2 = m2, stringsasfactors = false) plot<-ggplot(longtest, aes(d = d, m = m1 )) + geom_roc() + style_roc() plot its ok, if im add new roc line return error plot<-ggplot(longtest, aes(d = d, m = m1 )) + geom_roc() + style_roc() plot+ggplot(test, aes(d = d, m = m2)) + geom_roc() error in p + o : non-numeric argument binary operator in addition: warning message: incompatible methods ("+.gg", "ops.data.frame") "+" how can add new line , color line different color,and add legend melt data frame wide long format, map variable name line color within aesthetic

apache logs show tab character as \t from python scripts -

in python programs (django or web.py), write logs stderr. e.g. sys.stderr.write('tab\tcharacter') when serving these programs via apache, logfiles has literal "\t", , not real tab (ascii=9) if test program command line, see real tabs. it's in apache. is there feature in apache logs converts tab character \t ? is there way work around , see tabs in apache log files? edit i gave up. instead of \t i'm using character separator... try: a = "tab" + chr(9) + "character" sys.stderr.write(a) no?

perl - UNIVERSAL does not export anything -

hi getting following error when trying run perl script: pc:~/phd/lenovo/programs/vep/scripts/variant_effect_predictor$ perl variant_effect_predictor.pl --help universal not export @ /home/arron/phd/lenovo/programs/vep/scripts/variant_effect_predictor/bio/tree/treefunctionsi.pm line 94. where offending line is: use universal qw(isa) what issue? from documentation of universal : previous versions of documentation suggested using isa function determine type of reference: use universal 'isa'; $yes = isa $h, "hash"; $yes = isa "foo", "bar"; the problem code never call overridden isa method in class. instead, use reftype scalar::util first case: use scalar::util 'reftype'; $yes = reftype( $h ) eq "hash"; so method not exist anymore.

Facebook API: Can't retrieve Facebook Lead Ads -

i have set webhook point callback url , receives following example data: array ( [object] => page [entry] => array ( [0] => array ( [id] => 297269987142139 [time] => 1454876106 [changes] => array ( [0] => array ( [field] => leadgen [value] => array ( [ad_id] => 410908499427 [adgroup_id] => 238113717077 [created_time] => 1454847306 [form_id] => 577581087825 [leadgen_id] => 441393665441 [page_id] => 297269987142139 )

swift - Moving Data Using Protocol delegates in Navigation controller -

i working on app need pass data throw navigation controller , back. got work using tutorial: link in app have first view controller(in tutorial uiviewcontroller) beside push segue secondviewcontroller(in tutorial footwovc) own view controller. so question can use same protocol vc or need make protocol? import uikit class viewcontroller: uiviewcontroller,footwoviewcontrollerdelegate { @iboutlet var colorlabel : uilabel! override func viewdidload() { super.viewdidload() // additional setup after loading view, typically nib. } func myvcdidfinish(controller: footwoviewcontroller, text: string) { colorlabel.text = "the color " + text controller.navigationcontroller?.popviewcontrolleranimated(true) } override func prepareforsegue(segue: uistoryboardsegue, sender: anyobject!) { if segue.identifier == "mysegue"{ let vc = segue.destinationviewcontroller as! footwoviewcontroller

python - Celery gives no error with bad remote task names, why? -

using "send_task" celery never verifies remote task exists i.e: app.send_task('tasks.i.dont.exist', args=[], kwargs={}) celery seems still return message i.e.: <asyncresult: b8c1425a-7411-491f-b75a-34313832b8ba> is there way fail if remote task not exist? i've tried adding .get() , freezes. according documentation: if task not registered in current process can execute task name. you using send_task() method of celery instance if want verification consider using delay instead. you can read more how execute celery tasks here .

arrays - C Dynamic Memory vs Stack Memory Variables -

when c array created using malloc, array stored in heap, , when c array created statically stored in stack. however, happens if return element of c array initialized statically function? wording may strange, here example: #include <stdio.h> #include <stdlib.h> char getstaticelement(); char getdynamicelement(); int main() { char dynamicelement = getdynamicelement(); char staticelement = getstaticelement(); printf("dynamic element: %c\n", dynamicelement); printf("static element: %c\n", staticelement); return 0; } char getstaticelement() { char staticarray [] = {'a','b','c'}; return staticarray[1]; // returns b } char getdynamicelement() { char * dynamicarray = malloc(sizeof(char)*4); dynamicarray [0] ='a'; dynamicarray [1] ='b'; dynamicarray [2] ='c'; dynamicarray [3] ='\0'; return dynamicarray[1]; // returns b } so staticelement in memory?

java - How to do a search between a range offsets in a Binary file? -

i'm trying search between range of offsets in binary file. have loaded bin file byte array[] , encoded content string, later use search of string sequence. thing need search in range of offset input (start , ending)... , search differents string sequences, printing gives me this: 0x180 30 0x240 17 0x350 30 0x464 30 0x650 17 right i'm getting sequences 30 themselves. this code: byte[] model = read.readbytesfromfile(); string x = hexbin.encode(model); string v30 = "05805a6c"; string v17 = "0580336c"; string beg = txtbeg.gettext().tostring(); int beg2 = integer.parseint(beg); int start = (model.length + beg2) - model.length; string end = txtend.gettext().tostring(); int end2 = integer.parseint(end); int ending = (model.length + end2) - model.length; int index = 0; if (x.contains(v30) { if (cbxver.isselected()) { while ((index = x.indexof(v30, index)) != -1) { system.out.println("0x" + (integer.tohexstring((ind

sql - "Operator does not exist: integer =?" when using Postgres with Golang -

i have simple sql query called within queryrow method provided go's database/sql package. import ( "github.com/codegangsta/martini" "github.com/martini-contrib/render" "net/http" "database/sql" "fmt" _ "github.com/lib/pq") ) type user struct { name string } func show(db *sql.db, params martini.params) { id := params["id] row := db.queryrow( "select name users id=?", id) u := user{} err := row.scan(&u.name) fmt.println(err) } however, i'm getting error pq: operator not exist: integer =? looks code doesn't understand ? placeholder. how can fix this? postgresql works numbered placeholders ( $1 , $2 , ...) natively rather usual positional question marks. documentation go interface uses numbered placeholders in examples: rows, err := db.query("select name users age = $1", age) seems go interface isn't translating question marks numbe

stored procedures - How to loop through and copy every row of large MySQL table? -

scenario: i have mysql myisam table (table1) 11 million rows, of want copy better table (table2, has innodb engine along proper indices). since adding indexes myisam table takes long want loop through entire table , copy every row new table. is there way within mysql? conditions: there no time limit action (could looped "slowly"). the tables have same columns. table1 online , needs stay online (being read time; i've temporarily paused writing). problems: mysql server shared host (no file system access). mysqldump times out. adding index times out. simply inserting select of previous table times out. idea: perhaps 1 loop mysql statement, doing 10 000 @ time or that? this works 1 (1) record: insert products_indexed select * products products.p_product_id=( select products.p_product_id id products left outer join products_indexed on ( products.p_product_id = products_indexed.p_product_id ) products_indexed.p_product_id

c++ - How to find the low & high in Merge Sort -

i have basic understanding of merge sort algorithm. reason can't wrap head around values low , high coming from. code working merge. void practicemerge(int a[], int low, int mid, int high) { int b[10000]; int = low, j = mid + 1, k = 0; while (i <= mid && j <= high) { if (a[i] <= a[j]) b[k++] = a[i++]; else b[k++] = a[j++]; } while (i <= mid) b[k++] = a[i++]; while (j <= high) b[k++] = a[j++]; k--; while (k >= 0) { a[low + k] = b[k]; k--; } } let me explain commenting code: //sort array index low index high merging 2 //subarrays of go low mid , mid high. void practicemerge(int a[], int low, int mid, int high) { int b[10000]; //buffer int = low; //starting index in first sub array int j = mid + 1; //starting index in second sub array int k = 0; //starting index in buffer //while not go beyond limit of first subarray

java - Wicket @SpringBean and Spring @Autowired with injection via constructor -

i have wicket panel in want inject bean using @springbean public class somepanel extends panel { @springbean private blogsummarymailgenerator blogsummarymailgenerator; } but blogsummarymailgenerator has injection via constructor defined this: @component public class blogsummarymailgenerator { private blogrepository blogrepository; private blogpostrepository blogpostrepository; @autowired public blogsummarymailgenerator(blogrepository blogrepository, blogpostrepository blogpostrepository) { this.blogrepository = blogrepository; this.blogpostrepository = blogpostrepository; } } and when somepanel instantiated getting exception caused by: java.lang.illegalargumentexception: superclass has no null constructors no arguments given @ net.sf.cglib.proxy.enhancer.emitconstructors(enhancer.java:721) ~[cglib-3.1.jar:na] @ net.sf.cglib.proxy.enhancer.generateclass(enhancer.java:499) ~[cglib-3.1.jar:na] @ net.sf.cglib.core.defa

java.util.scanner - Java scanner object skipping lines? -

so been awhile since i've written console based java, i have method, below, should asking me each line, right? instead, 1 prompt, three.. did wrong herer? try { system.out.println("please enter product's long details: "); product.setlongdetails(sc.next()); //set products long details system.out.println("please enter product's short details: "); product.setshortdetails(sc.next()); //set short details system.out.println("please enter product's upc data: "); product.setupc(sc.next()); //set upc system.out.println("please enter product's stock: "); product.setstock(sc.nextint()); system.out.println("please enter products price. "); system.out.println("this must entered no dollar sign."); product.setprice(sc.nextbigdecimal()); inventorymanager.addproduct(product); //add product database }

python - networkx calculating numeric assortativity requires int? -

i trying use networkx calculate numeric assortativity based on numeric attribute set nodes. node attributes floats. when call assortativity function: assort = nx.numeric_assortativity_coefficient(g,'float_attr') i got following errors. file "/some dir.../networkx/algorithms/assortativity/correlation.py", line 229, in numeric_assortativity_coefficient = numeric_mixing_matrix(g,attribute,nodes) file "/some dir.../networkx/algorithms/assortativity/mixing.py", line 193, in numeric_mixing_matrix mapping=dict(zip(range(m+1),range(m+1))) typeerror: range() integer end argument expected, got float. i checked documentation page of networkx assortativity algorithm , did not numeric attributes have int. knows if that's required? btw, used same network , gender attribute (set 0 , 1) calculate both attribute , numeric assortativity. had no problem that. seems problem int/float type of node attribute. problem solved converting float variable i

nginx - Apply "autoindex on;" only at root of folder and index documents at following subfolders -

what i'd apply autoindex on; @ root folder , afterwards (as user selects folder) use traditional "index.php" files if available , defined in index index.html index.htm... etc. don't know number of folders inside root neither names. how can done, given these restrictions? you can define regular expression location match uri below root, example ./ this block should placed below location ~ \.php$ (or similar) php scripts continue handled correctly. see this document . location / { autoindex on; } location ~ \.php$ { ... } location ~ ./ { index index.php; }

sql server - Selecting correlated records from database -

i've been improving sql knowledge still failed understand how create queries. i have following tables in sql server database: user(id, name) loan(id_sender, id_receiver, amount, date, date_payment) what valid query to: select name of users have sent loans user both in 2014 , 2015 select pairs (id1, id2) of users have sent loans each other any suggestions appreciated! edit 1: my attempts: 1. select name user id in ( select id_sender loan id_receiver in (select distinct id_receiver year(date) = 2014) , id_receiver in (select distinct id_receiver year(date) = 2015) ) 2. select id1, id2 ( select distinct id_sender id1 loan id_receiver in ( select distinct id_sender loan id_receiver = ??? ) (?) ) example 1: in case date column has index, it's best not use function around column can utilize index. select name user id in (select id_sender loan date >= '1/1/2014' , date < '1/1/201

Order of complexity of fibonacci functions -

i have following 3 algorithms give fibonacci numbers. know how able find out each of order of complexity. know how might able determine this? method 1 ------------------------------------------------------------------------ long long fibb(long long a, long long b, int n) { return (--n>0)?(fibb(b, a+b, n)):(a); } method 2 ------------------------------------------------------------------------ long long int fibb(int n) { int fnow = 0, fnext = 1, tempf; while(--n>0){ tempf = fnow + fnext; fnow = fnext; fnext = tempf; } return fnext; } method 3 ------------------------------------------------------------------------ long long unsigned fib(unsigned n) { return floor( (pow(phi, n) - pow(1 - phi, n))/sqrt(5) ); } correct me if wrong, guess method 1 o(2^n) since recursive, medtod 2 o(n) , last 1 o(1) . methods 1 , 2 have complexity o(n) . reasons straightforward: method 1 recurses n-1 times, each recurs

java - Converting A Static "Level" Array To A Dynamic One And Still Get XYZ Coordinates -

okay, have static world (can't resized). know how can convert arraylist instead of current situation: for(int xp = 0; xp < world_size_x; xp++) { for(int zp = 0; zp < world_size_z; zp++) { for(int yp = 0; yp < world_size_y; yp++) { } } } my question is, how can make can use for(int = 0; < blocks.length; i++) {} but still [x][y][z] coordinates? currently i'm using block: blocks[x][y][z]; how xyz dynamic arraylist? if need more information, please tell me. i'll glad understand situation. arraylist's equivalent of .length .size() , , equivalent of [...] .get(...) . that said, arraylist<arraylist<arraylist<...>>> pretty unwieldy structure work with; , although it's theoretically "dynamic", in practice it's difficult resize, because resizing involves creating many new elements have initialize. if goal merely able specify size @ runtime (but

Change format for data imported from file in Python -

my data file tab separated , looks this: 196 242 3 881250949 186 302 3 891717742 22 377 1 878887116 244 51 2 880606923 166 346 1 886397596 298 474 4 884182806 115 265 2 881171488 253 465 5 891628467 305 451 3 886324817 ... ... .. ......... i imported them in python using numpy , here script: from numpy import loadtxt np_data = loadtxt('u.data', delimiter='\t', skiprows=0) print(np_data) i want print see result, gives me different format: [[ 1.96000000e+02 2.42000000e+02 3.00000000e+00 8.81250949e+08] [ 1.86000000e+02 3.02000000e+02 3.00000000e+00 8.91717742e+08] [ 2.20000000e+01 3.77000000e+02 1.00000000e+00 8.78887116e+08] ..., [ 2.76000000e+02 1.09000000e+03 1.00000000e+00 8.74795795e+08] [ 1.30000000e+01 2.25000000e+02 2.00000000e+00 8.82399156e+08] [ 1.20000000e+01 2.03000000e+02 3.00000000e+00 8.79959583e+08]] there point . in every number in print(np_data) . how format them orig

sails.js - Empty response on long running query SailsJS -

i'm running sailsjs on raspberry pi , working when execute sails.models.nameofmodel.count() when attempt respond result end getting empty response. getlistcount: function(req,res) { var mainsource = req.param("source"); if(mainsource) { sails.models.gatherer.find({source: mainsource}).exec( function(error, found) { if(error) { return res.servererror("error in call"); } else { sails.log("number found "+found.length); return res.ok({count: found.length}); } } ); } else {

css - Font Face Selectors with weight and style properties - browser ignores all but last selector -

i using multiple web fonts of same family avoid browsers rendering in faux-bold , faux-italics. when declaring selectors, set same name all"font-family" properties , using "font-weight" , "font-style" differentiate. here's example i'm using exo. @font-face { font-family: "exo"; src: url("../fonts/exo/exo-regular.eot"); src: url("../fonts/exo/exo-regular.eot?#iefix") format("embedded-opentype"), url("../fonts/exo/exo-regular.woff2") format("woff2"), url("../fonts/exo/exo-regular.woff") format("woff"), url("../fonts/exo/exo-regular.ttf") format("truetype"), url("../fonts/exo/exo-regular.svg#exo") format("svg"); font-weight: "normal"; font-style: "normal"; } @font-face { font-family: "exo"; src: url("../fonts/exo/exo-bold.eot"); src:

python - How can I get user input for an array? -

i want create list user's input , return random value list. this have far code can't figure out how input array. import random movie_array = ["moviea", "movieb", "moviec"] print(random.choice(movie_array)) i know input function i'm not sure how use create array/list. tried following didn't work movie_array = input() but when run random.choice on selects individual character. you can this: >>> import random >>> movie_array = [input("input movie: ") in range(3)] input movie: moviea input movie: movieb input movie: moviec >>> print(random.choice(movie_array)) moviec

python - Pyplot.imshow() and pyplot.show() displaying intermittently -

i have been working pyplot.imshow() week. everytime debug , hit pyplot.imshow(), image displays. now, of sudden, no image displays until hit pyplot.show(). what going on here? has changed? here setup: i using pycharm. i loaded matplotlib, sklearn, numpy, pandas. i created couple of classes in separate file, , running classes produce images in file in question. during production of images, had "imshow" (my experience level python few months). after implementing "imshow", images appeared when passed "imshow" line in debugging session. way behaved. i used repeatedly days. then, all of sudden (and may have closed , reopened pycharm, can't remember), "imshow()" function started intermittently displaying image (sometimes did, didn't). so started adding "show()" beneath "imshow()" calls...and worked (sort of). soon, that started working intermittently. pass "show()" during debugging s

tsql - Replace() in SQL isn't working with " -

Image
i'm receiving json string database i'm trying convert comma delimited list. current state: my sql looks like: begin transaction select id, prioritygroups , replace( replace( replace(prioritygroups, '["', ''), '"]', ''), '"."', ', ') 'updated comma delimited' dbo.ca id= 51 rollback transaction for whatever reason when try replace "." with comma , space it's not making changes output. i've tried escaping double quotes i'm being told it's invalid syntax , i'm not sure else try! its not "." replaced in string. characters replaced "," select id, prioritygroups , replace( replace( replace(prioritygroups, '["', ''), '"]', ''),

android - IllegalArgumentException: java.io.IOException: Cannot run program,error=13, permission deny -

when try platform , plugin updates, event log said: illegalargumentexception: java.io.ioexception: cannot run program "/home/xieyi/linuxsdk/platform-tools/adb": error=13, 权限不够(permission deny). what wrong? running root, why permission deny? solution change permission in ubuntu:) go platform-tools directory of android sdk. /android/sdk/platform-tools# ls this show adb not in green color. execute /android/sdk/platform-tools# chmod +x * after restart studio , again check in command line pervious command ls, notice adb in green color. hope work :) enjoy

javascript - Should i close the Mongo connection after some operation? -

i understand best practice dealing database operations. i use mongoose package, change mongodb package, cause don't need much, , know if should end connection after operation or leave open?? also, i'm using redis queue node-resque , have same doubt. i'm leaving both open, never close, doing wrong? also, extending express instance - app - queue operation, can use in anywhere, wrong too? thanks. mongodb it best practice open connection on application initialization , either have mongodb driver of choice manage connection pool (as drivers do, including js driver) or derive new connections "master" connection (as practice in go driver). the reason why makes sense have driver manage connection pool simple: when number of connections left in pool drops below threshold, relative expensive operation of creating new socket connection mongodb , maybe authenticating done in background. when new connections requested application, not need created. r

matlab - Why are "size mat" and "size(mat)" different? -

i have these results: >> size fives 1 5 >> size(fives) 4000 17 the latter accurate. i'm not sure former doing @ all. when type size no args error: error using size not enough input arguments. so i'm not sure why "fives" , "(fives)" both count arguments different things. in matlab, size without parenthesis gets size of literal string. example, size abcdefg 1 7 if abcdefg not defined variable.

html - break list item in two columns on small screen in bootstrap -

i want break list items 2 columns on small screen must in 1 column on md screen <div> <ul> <li> list item 1 </li> <li> list item 2 </li> <li> list item 3 </li> <li> list item 4 </li> </ul> </div> i want break list item item 3 , item 4 must displayed in second column in front of item 1 on small screen output should list item 1 list item-4 list item 2 list item 3 try below code .clear-left { clear: left } .clear-right { clear: right } ul { padding: 0 !important; margin: 0 !important; } li { padding: 10px; border: 1px solid #aaa; background: rgba(0, 0, 0, 0.07); list-style-type: none; } .block-1 { background: rgba(0, 0, 0, 0.05); } .block-2 { margin-top: 20px; background: rgba(0, 0, 0, 0.05); } <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="style

java - Multiple database connection issue in Spring project -

i'm going configure 2 databases connections in 1 spring project. created 2 data source beans in following way. @bean(destroymethod = "close") public bonecpdatasource getdatasource() { .... .... return datasource; } @bean(destroymethod = "close") public bonecpdatasource getdatasource2() { .... .... return datasource; } this way created entity managers. @bean @qualifier("entitymanagerfactory") public localcontainerentitymanagerfactorybean entitymanagerfactory() { ... em.setdatasource(getdatasource()); em.setpersistenceunitname("entitymanagerfactory"); ... return em; } @bean @qualifier("entitymanagerfactory2") public localcontainerentitymanagerfactorybean entitymanagerfactory2() { ... em.setdatasource(getdatasource2()); em.setpersistenceunitname("entitymanagerfactory2"); ... ret

android - The item you requested is not available for purchase - Unity3D on mobile -

i'm trying integrate android market in-app purchases app, unfortunately coming across annoying error every time try purchase real inapp product. i'm using unity3d , sommla framework that. surprising issue can purchase inapp products fine when test run app in unity editor every time try test on mobile device annoying error: the item requested not available purchase i googled error nothing seems work me, have made sure that: the apk signed , uploaded developer console alpha. installed app on device through unity build app have test account in developer console in app product configured in developer console , activated the app version number , version code same on developer console. any ideas guys? if can purchase via test in app purchase id android.test.purchased , trying real id product in development build of android don't worry. once gets live, error no longer visible , you'd see actual product actual price.

python - How to get data from list with dictionary -

hello have python variable list plus dictionary >>> print (b[0]) {'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'} ----------------------------------------------------------------------- >>> print (b) [{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}] >>> i have tried couldn't 'addr' extracted. help please. try this: print (b[0]['addr']) print(b[0]) gives dictionary, in dictionary can fetch value key dict[key] => returns associated value. so print(b[0]['addr']) give value of addr read python data structure here data structure

ios - UITextField difference between keystroke and copy/paste -

how can find out whether user has typed letter in uitextfield or copied source , pasted in uitextfield? you can sub class uitextfield , override paste method. whenever paste in textfield method triggered -(void)paste:(id)sender{ [super paste:sender]; //set flag know text pasted }

python--recursive list comprehension to apply lstrip on a list -

i have 2 lists follows f = ['sum_','count_','per_'] d = ['fav_genre','sum_fav_event','count_fav_type','per_fav_movie'] so want apply lstrip of each strings in f on items of list d,,so can get d = ['fav_genre','fav_event','fav_type','fav_movie'] and want using list comprehension. know can in other ways also, using re.sub, applying replace on each time on list items of d #example d = [re.sub(r'.*fav', 'fav', x) x in d] #####gives want ## if fav (which in case matching pattern) not there in d solution won't work ## d = ['fav_genre','sum_any_event','count_some_type','per_all_movie'] #re.sub can't applied on d(as before) no matching char 'fav' found so list compression choose do.. so far have tried .. d_one = [x.lstrip('count_') x in d] ###only count_ stripped # o/p- d-one = ['fav_genre', 'sum_

ios - Cannot subscript a value of type 'String' with an index of type 'String' -

i want display of name on tableview cell stored in postfromfriends array when wrote code shown below give me error of " cannot subscript value of type 'string' index of type 'string' " on declaration of name constant. if can help.thanx var postsfromfriends = [string]() this array appending name. override func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell { let cell = tableview.dequeuereusablecellwithidentifier("cell") as! friendstasktableviewcell if let name = postsfromfriends[indexpath.row]["name"] as? string { cell.name?.text = name } return cell } you have declared postsfromfriends array of string , sounds want array of dictionary: var postsfromfriends = [[string:string]]()

Pass excel Column/cell range to a MySQL/ MS query as parameter -

i have mysql query in have pass excel cells/columns parameter. i.e select * employee name=? , joining_date=? the above query has pick 2 parameters cells in 2 columns name & joining_date sheet 1 , populate in sheet 2. is there way give more 1 cell or whole column parameter in ms query.

python reference about floating point number -

this question has answer here: why id function behaves differently integer , float? 5 answers before question, here sample code. take @ first,please. >>> id(1) 1636939440 >>> = 1 >>> b = 1 >>> c = 1 >>> id(a) 1636939440 >>> id(b) 1636939440 >>> id(c) 1636939440 >>> id("hello") 43566560 >>> = "hello" >>> b = "hello" >>> c = "hello" >>> id(a) 43566560 >>> id(b) 43566560 >>> id(c) 43566560 >>> id(3.14) 34312864 >>> = 3.14 >>> b = 3.14 >>> c = 3.14 >>> id(a) 34312864 >>> id(b) 34312600 >>> id(c) 34312432 as see above, in terms of integer , string, python variable references object same way. floating point number works in different way.

Django: fullcalendar drag events and save -

i 'm trying drag events , store them in database getjson javascript file : <script type='text/javascript'> function savemydata(event, daydelta, minutedelta) { $.getjson("{% url events_drag %}", {'title': event.title, 'start': event.start, 'end': event.end}, function(data) { }); } </script> <script type='text/javascript'> $(document).ready(function() { $('#eventfiltercalendar').fullcalendar({ eventdrop: function(event, daydelta, minutedelta) { savemydata(event); }, eventresize: function (event, daydelta, minutedelta) { savemydata(event); }, </script> views : def eventsdrag(request): print 'events...' untitre= request.get['title'] unstart= request.get['start'] unend= request.get['end'] print 'untitre', untitre print

HTML5 - view excel file -

we display excel file consist of graphs onto our html5 web page. i tried couple of approach haven't got exact solution- if used iframe source excel file opens attachment , dialog box appears. dont want. if convert excel file mht , open using iframe. works ie , not mozilla or chrome. can please suggest how view entire excel workbook on html5 page? note: not want use google docs in case. check out link: http://www.labnol.org/software/embed-tables-spreadsheet-data-in-websites/7435/ it has multiples ways of embedding spreadsheets html pages

cpu - A concept in CSAPP: what is the definition of instruction? -

Image
i reading csapp, in chapter 4, there discussions cpu pipelining features author talks how many instructions non-pipelining cpu can execute within 1 second vs pipelining cpu. post screenshot follows: in figure 4.32(a) shows unpipelined cpu. in implementation, must complete 1 instruction before beginning next. big box combinational logic. author regard whole process instruction , calculates throughput 3.12 gips shown in formula. then author use figure 4.33 show pipeline computation: in pipeline computation, combinational logic can divided 3 stages i1, i2 , i3. here question: in opinion, because these 3 stages combined product effect of combinational logic, think of 3 stages single instruction author did in unpipelined example. however, author seems regard 3 stages 3 instructions, , got throughput of 8.33 gips follows: so curious definition of instruction? (if think of writing registers instruction, author's answer correct)

javascript - Is there a way to get the iteration number with angular foreach on an object -

is there way can iteration number inside angular foreach (when iterating through object : {'foo': 'blah', 'blah': 'foo'} ? iterator function in case, value 'blah' , 'foo' while key 'foo' , 'blah' angulars foreach when iterating object doesn't tell how many times iterated objects keys. when iterating array doesn't tell how many times ran current position in array. it's me being pedantic there difference. however alternative give current position in objects keys use native object.keys() . return array of objects keys, can iterate on them normal array , current position in array. var obj = {'foo': 'blah', 'blah': 'foo'}; object.keys(obj) .foreach(function (key, index) { console.log('key', key, 'value', obj[key]); console.log('ive ran ', index); }); docs: https://developer.mozilla.org/en-us/docs/web/javascript/r

Python: Matching Index values to List values -

having output of list of lists containing index values of grouped elements (somewhat) corresponding list of tuples, how combine them list of grouped tuples? data=[(1, 1), (1.5, 2), (3, 4), (5, 7), (3.5, 5), (4.5, 5), (3.5, 4.5)] clusters=[[0], [], [4], [1, 2, 3, 5, 6]] these sample values/groups. example of i'm asking about: coordinates= [[(1,1)], [], [(3.5,5)], [(1.5,2),(3,4),(5,7),(4.5,5),(3.5,4.5)]] i've tried list comprehensions , zips when comes getting value of [i] in clusters gets confusing. i think two-level list comprehension want: coordinates = [[data[index] index in cluster] cluster in clusters]

java - Postgresql timestamp update set null -

i have problem timestamp field in postgresql database scheduled_time timestamp without time zone, and posibility set null on update. still error: column "scheduled_time" of type timestamp without time zone expression of type bytea wskazówka: need rewrite or cast expression. i tried set null, tried set empty string "" tried find solutions @ internet, know work when set @ pgadmin null, when set parameter in querystring = "update upload set additional_info=:additionalinfo, customer_id=:customerid, scheduled_time=:scheduledtime upload_id=:uploadid"; final query query = entitymanager.createnativequery(querystring); query.setparameter("scheduledtime", upload.getscheduledtime()); more setparameters .... query.executeupdate(); its still me message type bytea. can tell me how solve that? i checking if scheduled null. when true, make update upload set additional_info=:additionalinfo, custom

linux - GNU Radio, debian compilation error -

have problem when trying compile gnuradio 3.6.5 on latest debian version (8.3). my gcc version output : using built-in specs. collect_gcc=gcc collect_lto_wrapper=/usr/lib/gcc/x86_64-linux-gnu/4.9/lto-wrapper target: x86_64-linux-gnu configured with: ../src/configure -v --with-pkgversion='debian 4.9.2-10' --with-bugurl=file:///usr/share/doc/gcc-4.9/readme.bugs --enable-languages=c,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.9 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.9 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-4.9-amd64/jre --enable-java-home --with-jvm-root-dir=/

arrays - How to sort multikey in php? -

this question has answer here: how can sort arrays , data in php? 7 answers array ( [0] => stdclass object ( [id] => 18 [accno] => 1 [title] => hardware [description] => mobile. [manudate] => 8th july 1942 [muscat] => album [month] => 7 [date] => 8 ) [1] => stdclass object ( [id] => 20 [accno] => 2 [title] => food [description] => apple. [manudate] => 27th july 1942 [muscat] => album [mon

javascript - Grid inside tabpanel gets broken -

Image
i have tabpanel. inside second tab have grid. code point view everyting ok, absolutely ok. , if move grid first tab, evrything works nice. problem somehow related fact when put grid tab not active, broken. how looks like:

c++11 - C++ Reverse a smaller range in a vector -

what best way following? i reverse smaller range in vector , haven't found better solution this: extract smaller range newly created vector, reverse , add newly created vector @ former position in original vector. another way explain want this: original vector: 1 2 3 4 5 6 7 8 9 10 11. wanted result:   1 2 3 4 5 6 7 10 9 8 11. copy 10, 9, 8 in order new vector 3 element or copy element 8, 9, 10 new vector reverse it. original vector consists of 9 elements because elements 8, 9, 10 erased in procedure. 2.the new vector 3 elements 10, 9, 8 copied/appended original vector @ position 8 vector or element element @ position 8, 9, 10 respectively. i sure there better solutions method mentioned above. you in fact write in-place swap, that gets last , first index swap, swap these, decreases last index , increases first index, and repeats until last_index - 1 <= first_index . now, sounds less copying me, stroustrup himself once said: i don't

android - fragment callback using interface -

i have activity starts fragmen t. inside fragment have edittext . , when text user types there, want activity of interface . i'm using this guide on mainactivity i'm implementing commentlistener interfac e , i've managed result inside oncommententered method. on donelistener , triggered when user presses button finishing activity, i'm getting null. obviously oncommententered runs after donelistener . any suggestions on how result on donelistener ? class mainactivity implements fragment.commentlistener{ static string comment; protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.addtransaction); done=(textview)findviewbyid(r.id.done_button); } // called when user presses button , mainactivity finishes. public void donelistener(view v){ // here null system.out.println(comment); finish(); } @override public void oncommententered(string data) { co

makefile - Including a separate binary into an ELF executable -

i developing operating system. include small asm program main kernel elf can serve first process load. having trouble getting work. program initcode.s . using following makefile modified xv6 operating system source task: initcode: $(as) $(asflags) initcode.s -o initcode.o ld $(ldflags) -n -e start -ttext 0 -o initcode initcode.o objcopy --input binary --output elf32-i386 --binary-architecture i386 initcode.out initcode kernel.elf: $(objects) initcode ld -t link.ld -melf_i386 $(objects) -o kernel.elf initcode the kernel compiles , links fine. objcopy creates markers enable me find binary within kernel code. contents of initcode trashed. contents not resemble assembler step produced within initcode.out . how can achieve including initcode.s separate binary somewhere in main kernel.elf markers generated can find within kernel? suggestions? i can think of 2 simple methods. there more complex methods if prefer. write small utility convert initc

Javascript display image on audio current time -

im beginner in javascript , im stuck @ problem. when click play function play() shows if <= 2.5 not when > 2.5 .(i displayed 'reddot' in html display hidden). function play() { var audio = document.getelementbyid("audio"); audio.play(); if (audio.currenttime <= 2.5) { document.getelementbyid('reddot').style.display = 'block'; } if (audio.currenttime > 2.5) { document.getelementbyid('reddot').style.display = 'none'; document.getelementbyid('reddot2').style.display = 'block'; } } function () { } function pause(){ var audio = document.getelementbyid("audio"); audio.pause(); } function load(){ var audio = document.getelementbyid("audio"); audio.pause(); audio.currenttime = 0; } function rewind() { var audio = document.getelementbyid("audio"); audio.play(); audio.currenttime = (audio.current

javascript - AJAX on load loading spinner -

i'm wanting place on website. here codepen . @-webkit-keyframes rotate-forever { 0% { -webkit-transform: rotate(0deg); -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); -moz-transform: rotate(360deg); -ms-transform: rotate(360deg); -o-transform: rotate(360deg); transform: rotate(360deg); } } @-moz-keyframes rotate-forever { 0% { -webkit-transform: rotate(0deg); -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); -moz-transform: rotate(360deg); -ms-transform: rotate(360deg); -o-transform: rotate(360deg); transform: rotate(360deg); } } @keyframes rotate-forever { 0% { -webkit-transform: rotate(0deg); -moz-transform: rotate(0deg);