Posts

Showing posts from April, 2015

javascript - Bootstrap carousel zoom transition -

i have images in bootstrap carousel , transition effect want zoom active image , show next image. - http://cssdeck.com/labs/solitary-css3-slider-zoom-transition , zoom of active slide. i tried change bootstrap's css, doesn't scale active slide, next one. .carousel-inner .item{ transition-property: transform; transform: scale(1); } .carousel-inner .item.active{ transform: scale(1.5); } /* turning off default transition effect */ .next, .prev, .active.left, .active.right { left: 0; transform: translate3d(0, 0, 0); } the problem when slide.bs.carousel event occures next slide active 1 , want zoom effect before switching carousel's slide. maybe triggering effect js before next slide shown help. how can achieve this? here need : http://codepen.io/statix/pen/dnlmxb simply create carousel-item responsive image inside , transition : .carousel-holder .carousel-item { position: absolute; left: 0; top: 0; -webkit-transition: 1s e

python - error in printing a N-Dimensional Numpy Matrix -

im having problems printing numpy 6-dimentional matrix. import numpy np qmatrix = np.zeros((((((5,6,10,12,10,8)))))) i used , after populating matrix tried print matrix using print (qmatrix) then comes bunch of zeros. when search value in matrix gives me correct value. print (qmatrix[1][2][4][2][5][7]) >>> 12.45 do have convert matrix in sort before printing matrix here full code used class q_matrix_base(object): def __init__(self, leadvehspd,leadvehipos,estdisctime,folvehspeed,folvehpos,rgt): self.leadvehspd = leadvehspd self.leadvehipos = leadvehipos self.estdisctime = estdisctime self.folvehpos = folvehpos self.folvehspeed = folvehspeed self.rgt = rgt # initialize matrix , fill zeroes self.qmatrix = np.zeros((((((leadvehspd,leadvehipos,estdisctime,folvehspeed,folvehpos,rgt)))))) #self.qmatrix.fill(0) def setitem (self ,leadvehspd,leadvehipos,estdisctime,folvehspeed,folvehpos

java - How to avoid nested ActionListeners? -

in program, want user to: pick/open database (like access) on own pick table database select column(s) table in code, have class this: mntmopendatabase.addactionlistener(new actionlistener() { public void actionperformed(actionevent e) { //open database //display tables buttons tablebutton.addactionlistener(new actionlistener() { // select table public void actionperformed(actionevent e) { //display columns of table selected buttons colbutton.addactionlistener(new actionlistener() { public void actionperformed(actionevent e) {// add list of columns exported } and results big block of code. there cleaner, simpler way this? the solution refactor: create separate , separately testable class code open database. and separate , separately testable class display of data. in actionlistener, either create instances of these classes, or interact them, if exist. learn

javascript - Node js error handling with callbacks in nested functions -

i know kind of error handling not right, promises should used instead, wondering if work is: router.get('/main', function(req, res, next) { var mycallback = new function(err, data){ if(err) { res.status(500).send({ error: "error (best handling ever)" }); return; } res.send("success"); return; }; mainprocess(mycallback); }); function mainprocess(callback){ request.post(requestparams, function(error, response, body) { if (error) { console.log(error.message); callback.return(error, ""); } else { request.post(requestparams, function(error, response, body) { if (error) { console.log(error.message); callback.return(error, ""); } else { // success callback.return(null, "success"); }

python - Pandas new column from groupby averages -

i have dataframe >>> df = pd.dataframe({'a':[1,1,1,2,2,2], ... 'b':[10,20,20,10,20,20], ... 'result':[100,200,300,400,500,600]}) ... >>> df b result 0 1 10 100 1 1 20 200 2 1 20 300 3 2 10 400 4 2 20 500 5 2 20 600 and want create new column average result corresponding values 'a' , 'b'. can values groupby: >>> df.groupby(['a','b'])['result'].mean() b 1 10 100 20 250 2 10 400 20 550 name: result, dtype: int64 but can not figure out how turn new column in original dataframe. final result should this, >>> df b result avg_result 0 1 10 100 100 1 1 20 200 250 2 1 20 300 250 3 2 10 400 400 4 2 20 500 550 5 2 20 600 550 i looping through combinations of 'a' , 'b' slow , u

ios - Autogrowing UITextView inside UITableView cell -

i have static uitableview , 1 of cell contains text view , want make text view autogrowable, , make cell grow @ same time. wrapping text instead of cutting it. in isoalted text view dont face issue due have fixed size , show long texts have scroll inside textview, in case doesnt want scroll, uitextview set nonscrolable because parent (uitableview) have scroll , want avoid nested scrolls. my approach sort out overrayde height.... , reload view every time user types using sizethatfits(size: cgsize) know requerid size, , set uitextview cell size, , show text correctly. but cell grows bit, , not enough, researched sizethatfits know if understand it, method mesure of object fit inside objets, or there other parameters care paddings, margins, or constriant , i'm not able find things explained. then have questions, did missunderstood method? how shoud use it? in correct path reach goal? or there better way it? thank much. override func tableview(tableview:

javascript - NVD3 Chart responsive issue -

Image
nvd3 responsive issue i have code second page used same chart here. on page responsive , trying figure out why chart not responsive here. var colors = ["rgba(74, 210, 255, .8)", "rgba(85, 172, 238, .8)", "rgba(205, 32, 31, .8)"]; d3.scale.colors = function() { return d3.scale.ordinal().range(colors); }; var colors = d3.scale.colors(); /*var colors = d3.scale.category20();*/ var keycolor = function(d, i) {return colors(d.key)}; var chart; nv.addgraph(function() { chart = nv.models.stackedareachart() .useinteractiveguideline(true) .x(function(d) { return d[0] }) .y(function(d) { return d[1] }) .showcontrols(false) .showyaxis(true) .showlegend(false) .rightalignyaxis(true) .controllabels({stacked: "stacked"}) .color(keycolor) .duration(500);

merge - How to intersect values from two data frames with R -

i create new column data frame values intersection of row , column. i have data.frame called "time": q 1 2 3 4 5 1 13 43 5 3 b 2 21 12 3353 34 c 3 21 312 123 343 d 4 123 213 123 35 e 4556 11 123 12 3 and table, called "event": q dt 1 b 3 c 4 d 2 e 1 i want put column called inter on second table fill values in intersection between q , columns dt first data.frame. result this: q dt inter 1 1 b 3 12 c 4 123 d 2 123 e 1 4556 i have tried use merge(event, time, by.x = "q", by.y = "dt") , generate error aren't same id. have tried transpose time data.frame cross section values didn't have success. library(reshape2) merge(event, melt(time, id.vars = "q"), by.x=c('q','dt'), by.y=c('q','variable'), all.x = true) output: q dt value 1 1 1 2 b 3 12 3 c 4 123 4 d 2 123 5 e 1

java - MvcUriComponentsBuilder and inccorect binding in Spring MVC -

code i have controller method this: @requestmapping("/{userid}/{configid}") def edit(@pathvariable("userid") user user, @pathvariable("configid") configuration configuration) { /* code here*/ } when call method browser works well, , user, , configuration args bind database id. problem but, when used mvcuricomponentsbuilder class, got exceptions incorrect arguments type in expected method. mvcuricomponentsbuilder.frommethodname(mycontroller.class, "edit", 1, 2).build() exception java.lang.illegalargumentexception: source convert must instance of @org.springframework.web.bind.annotation.pathvariable user; instead java.lang.long faced body similar problem? there solution? note : i'm using spring web mvc 4.1.8.release a bit more descriptions i'm using mvcuricomponentsbuilder in thymeleaf template this: th:action="${#mvc.url('cc#edit').arg(0, configuration.access.id).arg(1, configurati

java - DrawLine over GridBagLayout shows nothing -

i have mappanel class extends jpanel. display objects in grid , want of them linked line. trying draw lines mappanel.paintcomponent no line has been shown. check line parameters (x1,y1,x2,y2) system.out.println() , right ( kind of 0 < param < 600, measures fit panel). try draw 1 line fixed parameters have same problem. public class newmappanel extends jpanel { private static final long serialversionuid = 1l; private gamemap gamemap; private grid grid; private jpanel contentpanel; public newmappanel() { this.setbackground(color.white); } public void updatemap(gamemap gamemap) { this.gamemap = gamemap; ...load object custom object grid ... contentpanel = new jpanel(new gridbaglayout()); contentpanel.setbackground(color.green); gridbagconstraints c = new gridbagconstraints(); // draw grid (city city : gamemap.getcities().values()) { citypanel citypanel = new citypanel

c++ - Using boost's skewed_normal_distribution -

i new c++ , boost. i want create set of numbers derived skewed distribution using boost's skewed_normal_distribution class. i'm not sure how start. want define distribution mean 0.05, variance 0.95, skew of 0.5. following code doesn't work , realise need set variate_generator well. can provide pointers? not finding boost documentation page on skew_normal_distribution intuitive might because of inexperience. note main problem getting message: ‘ skew_normal_distribution ’ not member of ‘ boost ’ many thanks #include <boost/random.hpp> #include <boost/random/normal_distribution.hpp> #include <boost/math/distributions/skew_normal.hpp> int main () { boost::skew_normal_distribution<> normal(0.05, 0.95, 0.5); return 0; } use boost::math::skew_normal_distribution instead of boost::skew_normal_distribution message skew_normal_distribution not member of boost

Rails: Delete nested form object dinamically -

i have form add nested objects, this: this principal form: #purchasing_goals.html.erb <%= f.fields_for :group_goals |builder| %> <%= render partial: 'group_goal_fields', locals: { f: builder } %> <% end %> <div> <%= link_to_add_fields("add", f, :group_goals) %> </div> and nested form: <div class="group-goal"> <%= f.text_field :num_of_users, label: "no. usuarios" %> <%= f.text_field :discount_percentage, label: "descuento" %> <%= f.hidden_field(:_destroy) %> <%= link_to_remove_fields("delete", f, "'.group-goal'") %> </div> and these helpers add , remove group_goals items: def link_to_remove_fields(name, f, removal_class) link_to name, "javascript:void(0);", onclick: "remove_fields(this, #{removal_class})" end def link_to_add_fields(name, f, association) new_object

osx - Creating a PDF in Swift -

this question has answer here: create pdf in swift 1 answer how export view pdf in os x? 1 answer i want able able create pdf of view controller. essentially, need screenshot of view controller exported pdf. apple don't seem have documentation on (for os x development) in swift, got ideas? thanks just in case wondering.. solution problem follows (apologies not posting sooner - assumed 'duplicate' question answer lie elsewhere.. // define bounds of view let rect: nsrect = self.view.bounds // create pdf version , save desktop self.view.datawithpdfinsiderect(rect).writetofile("/users/jay/desktop/test.pdf", atomically: false) // automatically open newly generated file nsworkspace.sharedworkspace().openfile("/users/jay/desktop/test.p

finding modulus of huge numbers in java -

this question has answer here: how calculate modulus of large numbers? 10 answers for(i=0; i<n+1; i++) { y=y+(a[i]*(int)math.pow(j,i)); } int r=y/786433; s[k]=y-(r*786433); k++; now in code j value can 786432 . when try modulus of number (1+2*(786432)^2+3*(786432)^3)%786433 -521562 not correct using modulus operator before got same answer approach getting same answer. in approach modulus of number stored in array s[k] . can help? if use math.pow using double types. convert int. rounding can happen , truncating if values big. to solve problem need use biginteger : immutable arbitrary-precision integers in particular method mod : returns biginteger value (this mod m). method differs remainder in returns non-negative biginteger.

android - Drawing multiple lines on canvas with paint with shader cause performance issues -

inside surfaceview in separate thread on canvas draw ~50 bezier curves paint been set have gradient in following code: lineargradient gradient = new lineargradient(0, 0, 0, height, color.black, color.white, shader.tilemode.mirror); paint.setshader(gradient); setting shader paint causes serious performance issues - view starts lagging. if comment out setting shader paint works brilliant, issue in gradient. thread code: private class drawingrunnable implements runnable { private final surfaceholder surfaceholder; private final myview surfaceview; public drawingrunnable(surfaceholder surfaceholder, myview surfaceview) { this.surfaceholder = surfaceholder; this.surfaceview = surfaceview; } @override public void run() { while (isrunning) { canvas canvas = null; try { canvas = surfaceholder.lockcanvas(null); if (canvas != null) { canvas.drawcolor(color

jquery - select matching elements whose sibling element has a specific class -

i want select links direct child of table cell, have following selector: $('td a') but want add filter this. want select table cell links have direct sibling class of 'moda'. in other words, following match: <td> <a data-target="#unresolvedtasks" data-toggle="modal" href="#" style="">dfsgdfg fghfghjhgj</a> <div class="modal fade" id="unresolvedtasks" tabindex="-1" role="dialog" aria-labelledby="mymodallabel" aria-hidden="true"> </td> i did google search , conditions, gave me this link. different type of , condition: a=$('[myc="blue"][myid="1"][myid="3"]'); that select element meets criteria. want select element meets specific criteria , check if sibling meets specific criteria. i tried this: $('td a, td + div[class="modal"]') but doing or condition not , condit

linux - monodevelop program hangs on readline -

Image
i saw many questions on "readline gets ignored" problem different. i have simple program : using system; namespace test { class mainclass { public static void main(string[] args) { console.writeline(console.readline()); } } } simple isn't ? when execute using monodevelop : as can see doesn't matter how many lines put. ctrl+c doesn't work, nor ctrl+d(end-of-file character on linux ;) ) i have mono 4.4.0, strange when execute above program using mono program.exe works expected. i saw this question went options -> run -> general , have execute program on external console checked. i saw other questions "program hangs on readline" talk readline other streams, i'm talking simple console.readline() . i have monodevelop 6.0.1 on arch linux(installed monodevelop-stable aur package if matters).

php - MySql Query with INNER JOIN, GROUP BY and Max -

i have 2 tables, 1 looks this: id, datetime, user_id, location , status // rest not relevant and other looks this: id, lastname // rest not relevant now want entry of first table highest datetime per user_id , ask other table lastname of user_id . simple... i tried way (whick looks promising false nontheless): select w.datetime, w.user_id, w.status, e.lastname worktimes w inner join employees e on w.user_id=e.id right join (select max(datetime) datetime, user_id worktimes datetime>1467583200 , location='16' group user_id order datetime desc ) v on v.user_id=w.user_id group w.user_id order e.nachname; could give me hint please? i'm stuck @ while , begin knots in brain... :( you close, actually: select w.datetime, w.user_id, w.status, e.lastname worktimes w inner join employees e on w.user_id = e.id left join (select max(datetime) datetime, user_id worktimes datetime > 1467583200 , location = 

ios - Collapse Expand UITableView -

i tried expand/collapse uitableview inside uiviewcontroller . put uitableview height constraint 0 , make animation func collapseexpandroomsection() { isroomcollapsed = !isroomcollapsed tableheightconstraint.constant = isroomcollapsed ? 0.0 : totaltableheight uiview.animatewithduration(0.3) { self.view.layoutifneeded() } } the collapse effect works fine when tried expand table cells gone. thanks look have updated constraint , should doing in order believe: self.view.setneedsupdateconstraints() self.view.setneedslayout() self.view.layoutifneeded() as have updated constraint, therefore should firstly update set update constraints , set needs layout. followed layoutifneeded() have change apply immediately. as discussed briefly on comments, code applicable if override updateconstraint . not correct in answering question above.

javascript - Looping through a JSON Array gives "undefined" results -

this question has answer here: why using “for…in” array iteration bad idea? 22 answers javascript for…in vs for 21 answers i have json string being parsed (in response var) ajax: the json { "thearray":[ { "almostthere": { "whatwearelookingfor":"hello" } }, { "almostthere": { "whatwearelookingfor":"goodbye" } } ] } the json being parsed var jsondata = json.parse(response); //response string version of json code! now, need loop json array, hereby mentioned thearray . this: looping thearray for (var contents in jsondata["thearray"]) { } and inside there, value of whatwearelookingfor element:

asp.net - AsyncTimeoutAttribute is not working with Controller Actions -

we tried use following code increase request timeout our backup process runs on iis , asp.net mvc : [asynctimeout(79200000)] public async task<actionresult> dailybackup(guid secret) { httpcontext.server.scripttimeout = 22*3600; await backups.create(); return null; } however, didn't change timeout , after short period of time, asp.net mvc returns empty page , await backups.create() continue run separately in background. what should in order increase timeout actions without changing our web.config file?

User is unable to login with Facebook after app update on Android with Parse SDK -

i using parse sdk on android device. in our app, user can login facebook. everything works fine if user install app first time , tries login facebook. however, if user has installed , logged in app , tries update new version, app shows login screen. , when user tries login facebook again, fails , no error shown. in mainactivity (launching activity), code: if (parseuser.getcurrentuser() == null) { intent intent = new intent(this, loginactivity.class); parseloginconfig config = new parseloginconfig(); config.setfacebookloginenabled(true); intent.putextras(config.tobundle()); startactivityforresult(intent, login_request); } loginactivity derives parseloginactivity. any in regard appreciated.

c# - I have some issue with ObservableCollection, in my list there are values added but they are not showing in my list view -

this code have written far, observablecollection list populated string values list view won't show text. there aim missing or doing wrong? happy if give me reply on this! public class interactivelistviewcode : contentpage { public static observablecollection<string> items { get; set; } public interactivelistviewcode() { items = new observablecollection<string>() { }; //list<string> items = new list<string>(); listview lstview = new listview(); lstview.ispulltorefreshenabled = true; //lstview.refreshing += onrefresh; lstview.itemselected += onselection; lstview.itemtapped += ontap; lstview.itemssource = items; var temp = new datatemplate(typeof(textviewcell)); lstview.itemtemplate = temp; content = lstview; } internal void insertcomanyname(string[] companyname, string[] idforcompany) { (int = 0; < companyname.length; i++)

html - How to add a single border for 2 divs next to each other? -

first thing, sorry if it's dumb question... have created 2 divs, 1 on left of page, other 1 on right. problem is, want put single border around 2 divs (and not 1 border each div). don't know how target 2 divs , make border surround both divs 1 element. here html: <div class="left2"> <img src="images/mistake.jpg" class="img2"/> </div> <div class="right2"> <p>###########</p> </div> and here css: div.right2 { width: 40%; padding: 2% 5% 0 0; float: right; } div.left2 { width: 40%; padding: 2% 0 0 5%; float: left; padding-bottom: 50px; } thank help!! one way put both of divs in outer div , make border around that. html: <div id="outer"> <div id = "left"></div> <div id = "right"></div> </div> css: #outer { bor

c - Abort trap:6 for fopen -

i'm trying read in file called "pg.txt" , print out content, , getting abort trap:6 error. don't understand why getting it. here main file : #include <stdio.h> #include <stdlib.h> #include <ctype.h> int main(){ char s1[10]; int d1; int n1; int n2; int n3; int n4; file * fp; fp = fopen ("pg.txt", "r"); int i; fscanf(fp, "%d", &d1); printf("numtypes |%d|\n", d1 ); (i = 0; < d1; i++){ fscanf(fp, "%s %d %d %d %d", s1, &n1, &n2, &n3, &n4); printf("type1 |%s|\n", s1 ); printf("avg cpu |%d|\n", n1 ); printf("avg burst |%d|\n", n2 ); printf("avg interarrival |%d|\n", n3 ); printf("avg io |%d|\n", n4 ); } printf("before closing\n"); fclose(fp); return(0); } and pg.txt file: 2 interactive 20 10 80 5 batch 500 250 1000 10 this output

Can't get my PHP to show error when form field is blank -

i making php journal through form, no matter do, comes posted. i've tried using empty() , null i'm not sure i'm doing wrong. here html form: <form action="journal_post.php" method="post"> <p>give entry title.</p> <input class="input" type="text" name="title" /> <p>what mood today?</p> <input class="input" type="text" name="mood" /> <p>now please tell me day.</p> <textarea class="input" name="entry" rows="12" cols="75" type="text"> </textarea> <br> <br> <input class="submit" type="image" src="submit.png" name="submit" value="submit" /> <form> here php: <?php $servername = "localhost"; $username = "root"; $password = "blahblah"; d

Sampling and Reconstructing Signals In Matlab -

i have continuous signal : x(t) = cos(100*pi*t)+cos(200*pi*t)+sin(500*pi*t) i must apply standard reconstruction of sampling theorem f=500hz then have repeat it, f1>f any guys? i'm confused signals , matlab!! sampling @ f=500hz means taking samples every t = 1/f = 1/500 = 2ms . i don't know units of t vector , length not specified. let's assume length 1 second , units in us . you can create sampling vector tsample every 2ms (which corresponds f=500hz) , value of signal @ points. freq = 500; period = 1/freq * 1000000; % convert tsample = 0:period:1000000; % samples 0 1 second every 2000us sampled_signal = x(tsample); pd: school exercise have see happens if don't satisfy nyquist criteria. try different sampling frequencies , see happens if don't sample fast enough.

SpecFlow StepArgumentTransformation -

i have gherkin steps defined like: when select '<currentuser>' in stepdefinitions, capture parameter , replace 1 session. use stepargumenttransformation here what regex expression can use capture between < , > thanks if understand requirement correctly don't think can want. reason there no transformation 1 type another, string in string out, won't able step argument transformation. think have couple of options. 1 use lookup the value session in each step. other create class can used in transform. this: public class sessionvariable { ...stuff } [stepargumenttransformation] public sessionvaraible transformtosessionvariable(string input) { ..create session variable input } then make step methods accept variable of type sessionvaraible [when("i select '(.*)'")] public void wheniselect(sessionvaraible sessionvariable) { ...whatever }

html - making a box-shadow stay above a ul element on hover -

in project of mine i'm perfecting navbar, can see ordering menu item has test drop down menus, have hover , active class of blue box-shadow, box-shadow doesn't render on new menu list, z-index's of 9999 first li , 999 second, still renders on box shadow. here's js fiddle. https://jsfiddle.net/ybarpz3x/25/ thank you! nav css nav { position: fixed; background-color: #fff; width: 100vw; z-index: 999; } nav ul { float: right; font-size: 0px; padding: 0; margin: 0; color: #337ab7; position: relative; z-index: 9999; } nav ul .current-top-menu-item { box-shadow: 0px 4px 0px #36b8c8; } nav ul .current-top-menu-item { color: #204e76; } nav ul .top-menu-collapsed { padding: 20px 19px; } nav ul * { -webkit-transition: 170ms ease-out; -moz-transition: 170ms ease-out; -ms-transition: 170ms ease-out; transition: 170ms ease-out; } nav ul li { display: inline-block;

algorithm - Point in polygon on Earth globe -

i have list of coordinates (latitude, longitude) define polygon. edges created connecting 2 points arc shortest path between points. my problem determine whether point (let's call u ) lays in or out of polygon. i've been searching web hours looking algorithm complete , won't have flaws. here's want algorithm support , accept (in terms of possible weaknesses): the earth may treated perfect sphere (from i've read results in 0.3% precision loss i'm fine with). it must correctly handle polygons cross international date line. it must correctly handle polygons span on north pole , south pole. i've decided implement following approach (as modification of ray casting algorithm works 2d scenario). i want pick point s (latitude, longitude) outside of polygon. for each pair of vertices define single edge, want calculate great circle (let's call g ). i want calculate great circle pair of points s , u . for each great circle defined in point 2,

networking - Can't access to local server with Android -

my problem linked post : https://stackoverflow.com/questions/28982225/android-local-server-access-over-wifi/ i have website hosted mamp on mac mini, connected d-link router. i've got wifi-antenna (ubiquiti) connected router too, creates wifi ( offline ) lan. when try connect mac mini's ip, displays website other devices (iphone, windows pc) android doesn't work. i'd know how developper in link refered did " use dns redirecting domains custom domain ". or if there way work around this... client devices connects wifi network shoudn't (i wish) have configure manually android network parameters... edit: ngrok.io not solution : clients may not have 3g/lte connection on phones the adress / ip should same every time mac reboot thanks in advance

ruby on rails - Elasticsearch: reached maximum index count for current plan - status:500 -

is there heroku cli command allow purge elasticsearch indices? this error that's returned causing our application non-functional: reached maximum index count current plan - status:500 upgrading our current plan not feasible option due being in stages @ time. please advise on how cure this. you should able delete indices want via direct curl call. first need retrieve url of es cluster using heroku config:get command , retrieving appropriate variable: if you've installed searchbox addon : sb_url=$(heroku config:get searchbox_url) curl -xdelete http://<sb_url>/your_index if you've installed found addon : found_url=$(heroku config:get foundelasticsearch_url) curl -xdelete http://<found_url>/your_index last not least if you've installed bonsai addon : bonsai_url=$(heroku config:get bonsai) curl -xdelete http://<bonsai_url>/your_index to test out: # create 1 index => ok > curl -xpost http://<***_url>/your_ind

reducers - How to update the state in redux without using mapDispatchToProps() method -

i trying update reducer state using : store.dispatch(nameofthereducer(data)). it calls action creator not update reducer state. dont want create react component want dispatch state change. there way so..thanks in advance i think misunderstood how component , redux state relates. redux state change done through actions regardless of component 'using' state. as long have action creator defined somewhere, , reducer handle corresponding action.type , can use action creator in whichever component. there no benefit of using store directly. store stored in context , , considered bad practice using context . nice thing redux takes care of giving provider , connect . except when initializing app, should use mapdispatchtoprops when want use action creators in component.

java - Add BM25 scoring in Lucene -

i new-comer lucene. using lucene in java using lucene-3.6.0.jar. followed tutorial http://www.tutorialspoint.com/lucene/ . base code follows: public class lucenetester { string indexdir = "data/indexdir"; string datadir = "data/datadir"; indexer indexer; searcher searcher; public static void test() { lucenetester tester; try { tester = new lucenetester(); tester.createindex(); tester.search("malformed"); } catch (ioexception e) { e.printstacktrace(); } catch (parseexception e) { e.printstacktrace(); } } private void createindex() throws ioexception { indexer = new indexer(indexdir); int numindexed; long starttime = system.currenttimemillis(); numindexed = indexer.createindex(datadir, new textfilefilter()); long endtime = system.currenttimemillis(); indexer.close(); system.out.println(numindexed + " file indexed, time taken: " + (endtime - s

python - Stripping multiple characters from the start of a string -

i'm trying trim sub-string beginning of string based on condition: for instance, if input domain name prefixed http , https and/or www , needs strip these , return domain. here's have far: if my_domain.startswith("http://"): my_domain = my_domain[7:] elif my_domain.startswith("https://"): my_domain = my_domain[8:] if my_domain.startswith("www."): my_domain = my_domain[4:] print my_domain i've tried use these inbuilt functions ( .startswith ) instead of trying use regex. while code above works, i'm wondering if there more efficient way combine conditions make code shorter or have multiple checks in same conditional statement? i know regex computationally slower lot of built in methods lot easier write code wise :) import re re.sub("http[s]*://|www\." , "", my_domain) edit: mentioned @dunes more correct way of answering problem is. re.sub(r"^https?://(www\.)?&quo

how to get opposite side of a foreign key relation in django -

i have following relationships: class team(models.model): name = models.charfield(max_length=255) def players(self): ???? class player(models.model): user = models.onetoonefield(user, related_name="player") team = models.foreignkey(team) from team object, players belong it. how can values in opposite relationship? this covered in detail in documentation on following relationships backward . given team object team , players with: team.player_set.all() you can override player_set name setting related_name parameter in foreignkey definition.

pointers - How do I store hex values in char* variables in c -

i have following variables char *key; char*text; i want store hex value 0xaaaaaaaaaaaaaa in key , want store hex value 0xdddddddddddddddddddddddddddddddddddddddddddddddd in text. correct way of doing this?

ruby on rails 3 - current_user method with devise from the console -

rails 3.2.18 devise pry-rails gem (which installs pry) pry-doc gem i started rails console: rails c then logged in: then logged in: [13] pry(main)> applicationcontroller.allow_forgery_protection = false => false [14] pry(main)> app.post('/sign_in', {"user"=>{"login"=>"p3.rails.production@gmail.com", "password"=>"vw#98052"}}) => 302 302 means logged in, means can call: [15] pry(main)> app.controller.current_user but getting following response: nomethoderror: undefined method `current_user' #<devise::failureapp:0x000000094e33c0> (pry):13:in `__pry__' [16] pry(main)> app.session gives me: => {"flash"=> #<actiondispatch::flash::flashhash:0x00000009509598 @closed=false, @flashes={:alert=>"you need sign in or sign before continuing."}, @now=nil, @used=#<set: {}>>}

Database instead SQLITE - C# Server -

i have system basicly poker server made c# + pubnub api. old source , improving code. don't know if system big system or home games purpose, don't sqlite poker server, reason is: make signup system, website read database data , things new , past tournaments, new , past cash games, new , past freerolls. thinking: free/opensource/creative commons or "freedom" database system can use? i asking choose , fast database system can implement , use long time. thank you if work microsoft's stack why not use ms sql server express? suppose, feet needs, , it's free. if going deploy server on hosting, migration ms sql server express ms sql server easy.

ios - Setting CAEmitterLayer properties with KVC -

i attempting to change properties on caemitterlayer instance dynamically. making call setvalue:forkey: this: [self.mainviewcontroller.mainview.spaceview.emitterlayer setvalue:[nsnumber numberwithfloat:0] forkey:@"emittercells.particle.velocityrange"]; not seeing change in particle emitter. if set property 0 hard coding no particles emitted. here link gist file containing uiview implements particle system. know kvc can tricky miss typing maybe i'm over-looking obvious? so maybe i'm over-looking obvious indeed. problem line: setvalue:[nsnumber numberwithfloat:0] forkey:@"emittercells.particle.velocityrange" the string "emittercells.particle.velocityrange" not key. it key path . need call setvalue:forkeypath: .

java - Calling a remove() on every element to empty an ArrayList -

i'm trying write code removes movies arraylist , blanking can stuff more movies later. i'll start code: for(int index = 0; index < movies.size(); index++){ removemovie(movies, movies.get(index)); } everytime loop runs, increment index , movies.size() should decrease. need keep movies.size() consistent while still representing original arraylist size. so, want "index < arraylistsoriginalsizehereeventhoughmyforloopisdecreasingitssizebyremovingmovies" here's tried now: int tempmoviesize = movies.size(); for(int index = 0; index < tempmoviesize; index++){ removemovie(movies, movies.get(index)); tempmoviesize += 1; } this doesn't work though because getting outofbounds exception. should maintain size of tempmoviesize . (it goes down 1 because movie object removed, , incremented one, canceling out , keeping @ original value (in case 8).) int size = movies.siz

Choose image from photo album in Cordova windows phone 8.1 -

can please let me know how choose image photo album , file-uri or base-64 delivered thru call back. i able take picture camera facing problem while picking image photoalbum. using below code choose image right after choosing image app navigates home screen(index.html) giving warning on console "the code on page disabled , forward caching. more information, see: http://go.microsoft.com/fwlink/?linkid=291337 ". navigator.camera.getpicture(onsuccess, onfail, { quality: 50, destinationtype: camera.destinationtype.file_uri, mediatype: camera.mediatype.picture, sourcetype: camera.picturesourcetype = { photolibrary: 1, camera: 0, savedphotoalbum

swift ios use image or UIView to display dummy placeholder until data has loaded -

Image
if click on item in tableview new vc open. but want display dummy placeholder , loading indicator disappears once data has been fetched server. but should use , image placeholder or should style uiview? dont know whats best memorywise i want show this: then make fade away once data has been fetched api. it choice. know viewcontroller lifecycle includes methods jobs these. wievwillappear, viewdisappeared, viewshouldappear... if want add animation, may style view show animation facebook.

c++ - Custom read producing garbage -

i'm implementing own read function reads content file buffer. reads information in file when print out information has garbage null bytes '\00\' attached output. output read "hi\00\00\00th\00\00\00er\00e" when reading "hi there" have no idea causing , appreciated. i'm not sure if it's important or not '\00\' appear after 2 chars every time. bool fileread(int ptrbuffer, int buffersize, int fid) { if (buffersize == 0) { debug('p', "cannot read 0 bytes.\n"); machine->writeregister(2, -2); return false; } char *buffer = (char *)malloc(sizeof(char *) * (buffersize +1)); debug('p', "attempting read %d bytes file %d\n", buffersize, fid); // read bytes file. openfile* file = openfiletable[fid - fid_offset]; if (file == null) { debug('p', "file not exist!\n"); machine->writeregister(2, -4); return false; } file->read(buff

cuda - Can many threads set bit on the same word simultaneously? -

i need each thread of warp deciding on setting or not respective bit in 32 bits word. multiple setting take 1 memory access, or 1 memory access each bit set? there no independent bit-setting capability in cuda. (there bit-field-insert instruction in ptx, nevertheless operates on 32-bit quantity.) each thread set bit doing full 32-bit write. such write need atomic rmw operation in order preserve other bits. therefore accesses serialized, @ whatever throughput of atomics are. if memory space not concern, breaking bits out separate integers allow avoid atomics. a 32-bit packed quantity assembled using __ballot() warp vote function . example given in answer here . (in fact, warp vote function may allow avoid memory transactions altogether; can handled in registers, if result need 32-bit packed quantity.)

javascript - Can someone explain working of this js code with reference to 'this' keyword? -

Image
js code is: this.sound1 ="global"; function cat(){ this.sound = 'meawo!!!!'; this.sound1 = 'meawooooo!!!!'; meawo1 = function(){ console.log(this.sound1); console.log(this); }; function meawo2(){ console.log(this.sound1); console.log(this); }; this.meawo = function(){ console.log(this.sound); console.log(this); meawo1(); meawo2(); }; }; var c = new cat(); c.meawo(); output is: question: how come this inside of meawo1 (function expression) & meawo2 (function expression declaration) referring "global" , not object c ? why that? always remember simple tip while wanting know object this refer to. obj.method(); in above, method 's called on obj , , hence this in method it's called on, i.e obj = this . in case, though meowo called on c , meowo1 , meowo2 aren't on object want refer to. functions don'

javascript - Getting pagination to work with React Komposer -

i'm using meteor 1.3.4.1, kurounin:pagination 1.0.9, , react-komposer 1.8.0 (npm package). so here's code instantiating pagination within composer function: function composer(props, ondata) { console.log('loading pages'); const pagination = new meteor.pagination(ufcfighters); if( pagination.ready() ) { console.log('ready'); const fighters = { columns: [ { width: '5%', label: '', classname: '' }, { width: '20%', label: 'name', classname: 'text-center' }, { width: '20%', label: 'wins/losses/draws', classname: 'text-center' }, { width: '20%', label: 'weight class', classname: 'text-center' }, { width: '10%', label: 'status', classname: 'text-center' }, { width: '10%', label: 'rank', classname: 'text-center' }, ], data: pagination.getpag

php - Creating new attribute field in Catalog->Manage Categories->Display Settings -

im trying add attribute field in display settings in manage categories. found tutorial on web http://www.marketingadept.com/blog/magento-developers-add-a-custom-field-to-the-category-admin-page/ config.xml <?xml version="1.0" encoding="utf-8"?> <config> <modules> <cmsblock> <version>0.0.1</version> </cmsblock> </modules> <global> <resources> <cmsblock_setup> <setup> <module>cmsblock</module> <class>mage_catalog_model_resource_eav_mysql4_setup</class> <connection> <use>core_setup</use> </connection> </setup> </cmsblock_setup> <cms_block_setup_write> <connection> <use>core_write</use> </connection> </cms_block_setup_write> <cms_block_setup_read> <connection> <use>core_read</use> </connection> </cms_block_setup_read> </resources> </global> </con

javascript - Show loading animation with delay -

in web application i'm using jsf , primefaces. on buttons have time consuming functions. during time want show loading animation until complete site built. i'm doing calling functions showloading() , hideloading() this: <p:commandlink oncomplete="hideloading();" onstart="showloading()" process="@form" update="@form" actionlistener="#{dummycontroller.dummymethod}" content </p:commandlink> inside functions i'm showing/hidings div-objects specified id: function showloading() { $("#loader").show(); } this works fine. want show loading animation if pages needs more second build. that's why modified functions this: function showloading() { $(#loader").delay(1000).show(0); } function hideloading() { $("#loader").clearqueue(); $("#loader").hide(); } my problem @ point: loader works fine, in case doesn't appear. suggestion: showloading called @ diffe

jquery - Static files are missing -

in app there /static folder contains static resources needed app. here handlers static resources: - url: /static static_dir: static this works files directly in /static , let's have folder containing jquery: static |- jquery | \- jquery.js | \- images \- ... when try reach [myapp].appspot.com/static/jquery/jquery.js return 404 , have no idea why. also of files including .css , .ttf etc. giving me could not guess mimtype error. have no idea how solve that. edit added (new) app.yaml. don't have dispatch.yaml. version: 1 runtime: python27 api_version: 1 threadsafe: true handlers: - url: /static/pages_style mime_type: text/css static_dir: /static/pages_style - url: /static/images/(.*\.(gif|png|jpg))$ static_files: static/images/\1 upload: static/images/.*\.(gif|png|jpg)$ - url: /static/bootstrap 3.3.5 static_dir: /static/bootstrap 3.3.5 - url: /static/jquery 2.1.4 static_dir: /static/jquery 2.1.4 - url: /.* script: mya

javascript - Highcharts solid gauge dynamic update -

my idea display cpu , memory load highcharts solid gauge update every few seconds, ever do, wont run wanted, it's this: i have php code giving me integer cpu , memory usage $cpu = exec("mpstat 1 1 | grep 'all' | awk '{print 100 - $12}' | head -n 1"); $mem = exec("free -m | grep mem | awk '{print $3 / $2 * 100}'"); this highcharts js script: $(function () { var gaugeoptions = { chart: { type: 'solidgauge' }, title: null, pane: { center: ['50%', '85%'], size: '105%', startangle: -90, endangle: 90, background: { backgroundcolor: (highcharts.theme && highcharts.theme.background3) || '#eee', innerradius: '60%', outerradius: '100%', shape: 'arc' } }, tooltip: { enabled: false }, // value axis yaxis: { s