Posts

Showing posts from August, 2015

c# - ASP.NET Web APi - Passing an object as parameter -

makeuser method in user controller creating username , password. [httpget] public string makeuser(userparameters p) { const string chars = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789"; string pass = ""; random r = new random(); (int = 0; < p.number; i++) { pass += chars[r.next(0, 62)]; } string firsttwoo = p.name.substring(0, 2); string firstthree = p.surname.substring(0, 3); return "your username is: " + firsttwoo + firstthree + "\nyour password is: " + pass; } userparameter class sending parameters object. public class userparameters { public int number { get; set; } public string name { get; set; } public string surname { get; set; } } runasync method in console client. can pass object method? if yes mistake here? thank you!

TypeScript: Declare a variable with type of object literal -

i trying find proper signature (current version of typescript 1.7) function should accept reference types, not primitives: function onlyobject(x: ???) { if (typeof x !== 'object') { throw "bad arg!"; } } so function above should work: onlyobject({ }); onlyobject(new date()); onlyobject(new number(1)); onlyobject(null); onlyobject(function () { }); but fail in compile time: onlyobject("awd"); onlyobject(1); onlyobject(false); there isn't way express in language. if you're feeling industrious, can add it , project accepting pull requests feature.

java - Android: Download file from password protected website -

i need download pdf files site users have login before can download files. if user not logged site, links pdf files redirect login page. i managed post user credentials login page , save cookie response , tried providing cookie urlconnection when attempting download, still getting login page instead of pdf file. update: code added. posting user credentials: httpurlconnection conn = (httpurlconnection) url.openconnection(); conn.setrequestmethod("post"); outputstream os = conn.getoutputstream(); bufferedwriter writer = new bufferedwriter(new outputstreamwriter(os, "utf-8")); writer.write("username=" + username + "&password=" + password); writer.flush(); writer.close(); os.close(); string result = httputils.getresponsestring(conn); if (result.indexof("invalid") == -1) { string cookie = conn.getheaderfield("set-cookie"); return cookie; } cookie stored , used in following code segment attempting

python- reading JSON in ascending order -

i'm trying parse json file looks this: { "my_test":[ { "group_name":"group-a", "results": [ { "test_name": "test1", "time": "8.556", "status": "pass" }, { "test_name": "test2", "time": "45.909", "status": "pass" }, { "test_name": "test3", "time": "9.383", "status": "fail" }, ... } } how can print out test results in ascending order? (by name or time) edit: output in ascending order of time: test1 8.556 test3 9.383 test2 45.909 you try this, using builtin sorted function. from json import loads json_data = """{ "my_test": [{ "group_name": "group-a", "results": [{ "test_name": "test1", &

swift - Is there a way to use a Template, and In-Out Parameter and Optional together? -

i ran interesting behaviour other day. wrote helper function prevent errors while automatically typecasting json property. looked this: func readdata<t>(inout output:t, _ input:anyobject?, _ throwerror:bool = true) throws { if (input == nil) { if (throwerror) { throw converterror.missingparameter } } else { if let inputobject:t = input as? t { output = inputobject } else if (throwerror) { throw converterror.wrongtype } } } var myproperty:string try readdata(&myproperty, myjson["data"], true) this checks property exists, , it's right type. if goes well, value inside myproperty changes. a little while later, needed make changes. made class called properties , has list of properties inside of it. there 2 variables of type of class: originalproperties , modifiedproperties each of properties inside these classes optional variables now, keep track of prop

bash - share variable (data from file) among multiple python scripts with not loaded duplicates -

i load big matrix contained in matrix_file.mtx . load must made once. once variable matrix loaded memory, many python scripts share not duplicates in order have memory efficient multiscript program in bash (or python itself). can imagine pseudocode this: # loading , sharing script: import share matrix = open("matrix_file.mtx","r") share.send_to_shared_ram(matrix, as_variable('matrix')) # shared matrix variable processing script_1 import share pointer_to_matrix = share.share_variable_from_ram('matrix') type(pointer_to_matrix) # output: <type 'numpy.ndarray'> # shared matrix variable processing script_2 import share pointer_to_matrix = share.share_variable_from_ram('matrix') type(pointer_to_matrix) # output: <type 'numpy.ndarray'> ... the idea pointer_to_matrix point matrix in ram, once loaded n scripts (not n times). separately called bash script (or if possible form python main): $ python load_and_sh

javascript - Unable to locate json module required in code (program runs fine and module is used) -

one of packages using happen require separate module want into: var crypto = require('crypto'); however when try in /node_modules/ modules are, cannot find crypto module... searched accross project , module not show up... it looks crypto part of main modules - how inside core code? look? the crypto module part of standard library -- https://nodejs.org/dist/latest-v4.x/docs/api/crypto.html

php - if mysql any field is empty then show a word like null -

i need know that, if there empty field display null in retrieve form. mean, name----------age----------country xyz----------" "---------usa so, form show name: xyz age: show null country: usa <?php $dbhost = ''; $dbuser = ''; $dbpass = ''; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('could not connect: ' . mysql_error()); } $no=$_get['no']; $sql = "select * tablename name='$name'"; mysql_select_db('dbname'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('could not data: ' . mysql_error()); } while($row = mysql_fetch_array($retval, mysql_assoc)) { ?> <table width="100%"><tr><td> <table> <tr> <tr><td class="a" style="width:20%">name</td><td style="width:20%" class="a"><a class="res" ><?php echo $

javascript - Detecting type of line breaks -

what efficient (fast , reliable enough) way in javascript determine type of line breaks used in text - unix vs windows. in node app have read in large utf-8 text files , process them based on whether use unix or windows line breaks. when type of line breaks comes uncertain, want conclude based on 1 then. you want first lf. source.indexof('\n') , see if character behind cr source[source.indexof('\n')-1] === '\r' . way, find first example of newline , match it. in summary, function whichlineending(source) { var temp = source.indexof('\n'); if (source[temp - 1] === '\r') return 'crlf' return 'lf' } there 2 popularish examples of libraries doing in npm modules: https://github.com/danielchatfield/node-newline/blob/master/lib/detect.js , https://github.com/neoklosch/crlf-helper/blob/master/lib/crlfhelper.js first split on entire string inefficient in case. second uses regex in case not qui

mongodb - Get all records with specified properties between a certain date range -

i passing in 2 dates formatted mm-dd-yyyy date range. need query records within range , include specified fields. i've had no luck. part of record in mongo: { "_id": "some id", "date": { "$date": "2015-06-26t13:02:12.121z" }, query: var start = '09-07-2015' var end = '09-14-2015' if do: var query = order.find({ date : { $lt : end, $gt : start } }); i full document within week ranges expected. however, want specify fields return rather full document. i've tried using grouping , project specify fields: var query = order.aggregate( { $match : { date: { $gte: start, $lt: end } }, $group: { cust_id: '$request.headers.customer_id', wholesaler_id: &#

c# - Running Method on Client ASP MVC -

i know how call method. client. have custom printer runs on iis asp.net. ex: method call printer.print(); inside api of printer referenced on project , published iis. using printerdll; public actionresult index(){ printerdll.printer freenter = new printerdll.printer(); freenter.open(); return view(); } now works if access site network. but runs on server driver installed. if driver installed in clients computer possible call method in clients computer instead of server? if so, possible call without using activex call needs internet explorer access? you asked not-so-easy way. other's may have ideas how improve on this. if have idea improvement go ahead , leave comment or edit answer. the broad strokes are: make new protocol scheme, like: myawesomeness:// write application registered protocol handler newly created scheme. in web page issue ajax call myawesomeness://url/data this invoke aforementioned app , can take there. some light

matplotlib - Plot sphere with Julia and PyPlot -

Image
recently tried plot sphere using pyplot/julia , unfortunately harder thought. there's wrong points generation, can't figure out why implementation didn't work. although fine original python code. i've tried adapt demo2 matplotlib surface plot doc mwe: using pyplot u = linspace(0,2*Ï€,100); v = linspace(0,Ï€,100); x = cos(u).*sin(v); y = sin(u).*sin(v); z = cos(v); surf(x,y,z) and i'm getting instead of so, what's wrong in julia implementation? x , y , z should matrices, not vectors -- otherwise have curve drawn on sphere, instead of surface itself. using pyplot n = 100 u = linspace(0,2*Ï€,n); v = linspace(0,Ï€,n); x = cos(u) * sin(v)'; y = sin(u) * sin(v)'; z = ones(n) * cos(v)'; # rstride , cstride arguments default 10 surf(x,y,z, rstride=4, cstride=4) the curve drawn corresponds diagonal of matrices. plot( diag(x), diag(y), diag(z), color="yellow", linewidth=3 )

regex - JavaScript negative lookahead regular expression producing wrong result -

assume following url: http://a2.mzstatic.com/us/ryoyo0/078/purple100x100/v4/38/e3/b4/38e3b4a2-b422-8d1e-69f2-593fc035c9d4/mzl.vqhwzhhc.100x100-75.jpg we want replace last occurrence of 100x100 256x256. url should read: http://a2.mzstatic.com/us/ryoyo0/078/purple100x100/v4/38/e3/b4/38e3b4a2-b422-8d1e-69f2-593fc035c9d4/mzl.vqhwzhhc.256x256-75.jpg here's our javascript replace method: replace( /100x100(?!100x100)/, '256x256' ) unfortunately, consistently replace first, not last, occurrence. what doing wrong? thanks! another way it... replace( /(.*)100x100/, '$1256x256' ) works by... capturing 100x100 greedily possible, (.*) , group 1 matching 100x100 replacing captured group 1, using $1 , adding 256x256 in place of non-captured match n.b. method can work last match (or first if make initial capture un-greedy adding ? after .* ) it avoid using look-around assertions, performance reasons, compatibility various regex implemen

html - Nested flexbox groups -

i 2 groups of 3 inputs. on wider screens, 2 groups should side-by-side, , on narrower screens, 2 groups should stacked. 3 input items inside groups should side-by-side. in cases, input items should evenly sized across width of window. in other words, on larger screens, should see 6 inputs equally sized side-by-side, taking width of window. on smaller screens, should see 3 inputs equally sized taking width of window, stacked on top of 3 similar inputs. as grow or shrink window, inputs should change size proportionally. when window small 6 inputs fit side-by-side, should go 2 groups of 3, 3 inputs in each group expanding group takes width of window. i want flexbox. realize media queries can this, embedding in growable div, media queries not work. this code sample comes close, in wrapping, not grow inputs (or div wrappers around inputs matter) take width of window. <!doctype html> <html lang="en"> <head> <meta charset="utf-8">

css - Quick media query glitch -

just quick question colleague of mine, have made website responsive , @ 800px navigation gets hidden , mobile menu appears using standard css media query. viewing website on ipad, displaying mobile menu colleague thinks ipad should display website on desktop has screen resolution wider 800px. is correct , if not, why not? thanks. an ipad's width in portrait 768px. check out viewport sizes . things bit more difficult understand higher resolution displays. there's question posted here @ stack overflow .

javascript - Automatically add a certain class, whenever <Form> code contains a certain value? -

i want add special class each form contains word special part of action url. but have many forms, , can't think of automated way this. the way came create following code, have create such code each , every form, using different index number: <?php $case1 = "special"; $case2 = "none"; if($case1 == "none") { $class1 = ""; // don't add class } else { $class1 = "effect"; // add `effect` class } if($case2 == "none") { $class2 = ""; // same goes here } else { $class2 = "effect"; // , here } ?> html: <form action="/go/<?= $case1 ?>" method="post" target="_blank"> <input type="submit" class="<?= $class1 ?> general-class" value="submit"> </form> <form action="/go/<?= $case2 ?>" method="post" target="_blank"> <input type="

ios - "Potential leak of an object" when using Core Graphics -

my app drawing shadow using following code: -(void)drawshadow:(cgcontextref)context rect:(cgrect)rect{ cgcontextsavegstate(context); //set color of current context [[uicolor blackcolor] set]; //set shadow , color of shadow cgcontextsetshadowwithcolor(context, cgsizemake(0, 2), 3, [[uicolor colorwithwhite:0 alpha:0.5] cgcolor]); cgcontextfillellipseinrect(context, rect); cgcontextcliptomask(context, rect, cgbitmapcontextcreateimage(context)); cgcontextrestoregstate(context); // warning shows in line } when run product > analyze, marks last instruction of block message: "potential leak of object". when remove line, shows same message in closing bracket. any idea of i'm doing wrong? thanks i think it's cgbitmapcontextcreateimage leaking. try assigning local variable , calling cgimagerelease once you've clipped mask. another iphone - cgbitmapcontextcreateimage leak

How Does Python Swap Elements inside a List? -

Image
i new python, , learned mutable , immutable objects. appears when swapping elements inside list, python creates copies of individual elements , copy them list. in above example, begin n = [[1, 2], [3, 4]] . first sublist, [1, 2] occupies id# 24 , , second sublist [3, 4] occupies id# 96 . @ first, thought since lists mutable, after swapping, id# 24 holds [3, 4] , id# 96 holds [1, 2] . can see in test above, not case. rather, python pointing objects in manner determined our swap; first slot of list points 96 , second slot points 24 . certainly, id# of n did not change, n did not violate definition of mutable object. way sublists got swapped seems caveat. can kindly confirm or explain in more precise language? you mistaken ids. id#24 id of list [1,2] . not memory address or id of index 0 in n . you might want try example confirm: >>> x = [1, 2] >>> id(x) 4332120256 >>> l = [x, 3] >>> id(l[0]) 4332120256 >>&g

excel - Auto-filling a column with data once one cell has been updated -

Image
how can auto-fill column 0's once 1 cell in column has been filled? example: original table once enter number cell in april column... i want column auto-fill rest of cells 0's, this... my first idea use worksheet_change event so... private sub worksheet_change(byval target range) dim keycells range set keycells = range("h6:h16") 'h6 h16 range of april column, repeat each column in loop if not application.intersect(keycells, range(target.address)) nothing range("h6:h16").value = 0 end if end sub but overwrites entire column, while want keep original value. is there way excel return cell changed can change value of cells in column except one? or there easier way this? with apr in h6:h16, data range seem in e6:p16. private sub worksheet_change(byval target range) if not intersect(target, range("e6:p16")) nothing on error goto bm_safe_exit application.enableevents = false dim tgt ra

application android contact sync -

**hi, looking application (apk) or php api can sync android contact database mysql ,i want sync every custmer in site (database) phone contact thinks, you should try take @ rest api: https://developers.google.com/google-apps/contacts/v3/#creating_contacts

delphi - How to change hint text while hint is shown in TBalloonHint? -

before used thint, , working code: procedure tmainform.formcreate(sender: tobject); begin application.onshowhint := appshowhint; end; procedure tmainform.appshowhint(var hintstr: string; var canshow: boolean; var hintinfo: controls.thintinfo); begin hintinfo.reshowtimeout := 1; end; now use tballoonhint , want change hint text when hint shown. above procedure not triggered. i changing hint text each second, when user enters control, hint shown , want update hint text each second, when user not moving mouse. how achieve tballoonhint? tballoonhint not support functionality. following code (delphi xe3) adds it. cons: cpu load - every call tballoonhint.showhint creates new tcustomhintwindow flickering when redrawing type tmyhintwindow = class(thintwindow) public function calchintrect(maxwidth: integer; const ahint: string; adata: tcustomdata): trect; override; function shouldhidehint: boolean; override; end; var balloonhint: tball

r - dplyr summarise_each() using multiple functions for different column subsets accross the same groups -

i'd use summarise_each() apply multiple functions grouped dataset. however, rather apply each function all columns, i'd apply each function particular subsets. realize specifying each column summarise() , have many variables. is there alternate solution either 1) using summarise_each() , deleting unneeded columns or 2) saving group_by() result, performing multiple separate summarise_each() operations , combining results? if not clear, let me know , can try illustrate example code. i suggest following: here apply min function 1 variable , max function other. merge grouping variable. > by_species <- iris %>% group_by(species) start variable want apply min function: min_var <- by_species %>% summarise_each(funs(min), petal.width) min_var source: local data frame [3 x 2] species petal.width (fctr) (dbl) 1 setosa 0.1 2 versicolor 1.0 3 virginica 1.4 then variable want ap

swift - How do you use a switch statement with a nested enum? -

i'm getting error on switch statement below path . enum case search not member of type instagram enum instagram { enum media { case popular case shortcode(id: string) case search(lat: float, lng: float, distance: int) } enum users { case user(id: string) case feed case recent(id: string) } } extension instagram: targettype { var path: string { switch self { case .media.search(let _, let _, let _): return "/media/search" } } } i want use switch statement return path, cases giving me errors. there way work? this using advanced enums: https://github.com/terhechte/appventure-blog/blob/master/resources/posts/2015-10-17-advanced-practical-enum-examples.org#api-endpoints i'm adding more general answer few reasons. this open question regarding nested enums , switch statements. the other 1 sadly closed . the legit answer not show how assign

javascript - What does the ++ sign mean in programming code? -

this question has answer here: behaviour of increment , decrement operators in python 6 answers incrementing in c++ - when use x++ or ++x? 10 answers what ++ sign mean in code: for (var i=0; < mystring.length; i++) { alert(mystring[i]); } while (x>y) { alert ("xrules!"); y++; } ++ increment operator saying y++ is same thing saying y = y + 1

javascript - Parse with data gathered from popup -

i working on facebook app , have little bit of trouble: have index.php , mypopup.php file. hosted on heroku, if matters in way. need when button pressed on index.php page, popup window should appear, content of mypopup.php file, has html form couple of checkboxes , button. now, question how can data popup window (checked items) passed index.php , work data in index.php file? for example: checkbox1 data1 [checked] checkbox2 data2[unchecked] the data related checkbox1 should passed function in index.php you can use javascript this. content show in lightbox. when lightbox done loading, attach event handlers of items want watch in lightbox ( onchange events example). can pass data index.php on back-end using ajax request. also, realized (silly me), if have html form, can change action of form send data index.php instead of mypopup.php. either way work. depends on specifics of data , need it.

Stripping time (in the format hh:mm) from a string in Python 2 -

i have been trying strip out occurrences of sequences of text in format '%d:%d' (for example, 05:45) string. have tried following code: def remove_times(s): in range(len(s)): if s[i] == ':': s = s.replace(s[i-2:i]+':'+s[i:i+3], '') return s this not solution problem few reasons , doesn't work in form given above either. my problem don't know how replace patterns take form above. seems there neat way of doing can't find it. for example sample input be: 'the time currently: 05:52' and corresponding output be: 'the time currently: ' so whole time gets deleted input , returned. i think you're looking re.sub . import re def remove_times(s): return re.sub(r'[012]?[0-9]:[0-5][0-9]', '', s) result: >>> remove_times('hi name 4:30 bob') 'hi name bob'

perl - RegEx - File upload filtering in Cyberduck -

i have local folder (mac os) 437 subfolders containing files , subfolders. these want upload *.jpg files top level in 359 of subfolders. filters in cyberduck using standard perl regular expressions. how write regex string in preferences? local path local main folder: /danacord/webshops/covers/ sub folders - example: alpha sub 1 sub 2 beta sub 1 sub 2 delta sub 1 sub 2 i don't want beta folder uploaded. fyi: of folder- , filenames start capitalized letters , contains blanks.

c++ - Filling a list with Window objects using EnumWindows -

i'm trying fill list 'window" objects of active windows can't figure out way save window information in windowlist. windowlist passed callback function through lparam parameter. here current code: std::list <window> windowlist; //in center.h //in center.cpp: void center :: detectwindows() { enumwindows(detectwindowsproc, (lparam)&windowlist); } bool callback detectwindowsproc(hwnd hwnd, lparam inputlist) { if (iswindow(hwnd) && iswindowenabled(hwnd) && iswindowvisible(hwnd)) { tchar tchartitle[100]; getwindowtext(hwnd, tchartitle, 100); std::string title = converttchartostr(tchartitle); window * windowptr; windowptr = (window*)inputlist; window newwindow((int)hwnd, title, true); *windowptr = newwindow; std::cout << (int)hwnd << " - " << title << std::endl; } return true; } when try print out every element in

file - python menu Game menu game... etc -

i'm making game in python using pygame , other libraries. have main menu 1 python file, , when player selected, starts game file. if choose go menu while playing game, starts menu again. new menu can't start/open game file anymore doesn't @ all. (after each time open file close previous one) eg: menu-->playerselect-->gamestartup-->menu-->playerselect-->break/crash. so actual code first file menu name "flappybirdmain, "happybrid" name of second game file. if startgui == 2: screen.blit(background, [0, 0]) import happybird done=true pygame.quit() for second file "happybird" have open menu connected pressing down "m" key: if event.key == k_m: pygame.mixer.fadeout(1) import flappybirdmain done=true so import flappybirdmain done=true closes "happybird" file i have figured out making copies of same files("flappybirdma

Android permission doesn't work even if I have declared it -

i'm trying write code send sms android app, when try send sms sends me error: 09-17 18:37:29.974 12847-12847/**.**.****e/androidruntime﹕ fatal exception: main process: **.**.****, pid: 12847 java.lang.securityexception: sending sms message: uid 10092 not have android.permission.send_sms. @ android.os.parcel.readexception(parcel.java:1599) @ android.os.parcel.readexception(parcel.java:1552) @ com.android.internal.telephony.isms$stub$proxy.sendtextforsubscriber(isms.java:768) @ android.telephony.smsmanager.sendtextmessageinternal(smsmanager.java:310) @ android.telephony.smsmanager.sendtextmessage(smsmanager.java:293) @ **.**.****.mainactivity$3.onclick(mainactivity.java:70) @ android.view.view.performclick(view.java:5198) @ android.view.view$performclick.run(view.java:21147) @ android.os.handler.handlecallback(handler.java:739) @ android.os.handler.dispatchmessage(handler.java:95) @ android

swift - NSCollectionView error: Parameter indexPath out of bounds or nil -

i've been playing around osx programming (usually ios guy) i've hit strange issue nscollectionview can't seem debug. when change data data source uses populate collection items, call reloaddata() on collection view usual , hits assertion. error parameter indexpath out of bounds or nil . if don't change data app crashes @ same point(s) though sometimes, first time, works fine , crashes subsequently. now, i've debugged numerous times. data correct , @ no point in my code ever see nil index path. assertion occurs on makeitemwithidentifier call, , on last item in collection. if continue, either see expect or else of cells previous collection still there behind new cells. at 1 point refactored code , found error occurring in nscollectionview s itematindexpath: function instead. has else seen error and, if so, caused it? update 2: know causing issue, have no idea how prevent it. happens this: user clicks item in collection view. item changes data object

Emacs Dired - C-x C-f to create a new file gives me suggestions of existing files -

i'm trying create file in dired mode in emacs. in right directory , when press c-x c-f suggested elsewhere on , type 'img' (that's name of file want create), tries find existing files other directories including pattern 'img'. i'm stuck if press enter, it'll open first suggested file containing pattern 'img' other directories, tab go on suggestions. please advise. you using ido-find-file can interactively select file typing substring of file name. if want temporarily disable feature (i.e. current search only) press c-f before typing name of new file (i.e. immediatly after c-x c-f ).

html - jQuery fadeIn Doesn't seem to run? -

very simple jquery project practice. have set button ( #btn ) , wanted see if possible fade in div when click button. set fiddle, wrong code itself? link jsfiddle . --code-- -jquery- > jquery(function() { > $('#btn').click(function(){ > $('#text2').fadein(1000); > }); }) --html-- <div id="btn"> <button>click me!</button> </div> <div id="text"> <h1> hello </h1> </div> <div id="text2"> <h2 style> hi there! <h2> </div> fadein() works display:none; css property, not opacity. use .css('opacity', '1') or animate that... jsfiddle

c# - Read and edit XML value -

i want read , edit value string (value="j:\demo\demo_data_3.xml") next parameter name="database". when use xpathdocument xpathdoc = new xpathdocument(dashboardpath); xpathnavigator navigator = xpathdoc.createnavigator(); while (navigator.movetofollowing("parameters", "")) i can move to <parameter> not read or edit values. have advice? xml source <?xml version="1.0" encoding="utf-8"?> <dashboard currencyculture="en-us"> <title text="dashboard" /> <datasources> <sqldatasource componentname="dashboardsqldatasource1"> <name>demo_data_excel</name> <connection name="testdata" providerkey="inmemorysetfull"> <parameters> <parameter name="database" value="j:\demo\demo_data_3.xml" /> <parameter name="read only" value="1&q

python - Plotting pandas groupby -

Image
i have dataframe car data - structure pretty simple. have id, year of production, kilometers, price , fuel type (petrol/diesel). in [106]: stack.head() out[106]: year km price fuel 0 2003 165.286 2.350 petrol 1 2005 195.678 3.350 diesel 2 2002 125.262 2.450 petrol 3 2002 161.000 1.999 petrol 4 2002 164.851 2.599 diesel i trying produce chart pylab/matplotlib x-axis year , then, using groupby, have 2 plots (one each fuel type) averages year (mean function) price , km. any appreciated. maybe there's more straight way it, following. first groupby , take means price: meanprice = df.groupby(['year','fuel'])['price'].mean().reset_index() and km: meankm = df.groupby(['year','fuel'])['km'].mean().reset_index() then merge 2 resulting dataframes data in one: d = pd.merge(meanprice,meankm,on=['year','fuel']).set_index('year') setting index ye

PHP Laravel: Update one -to- many relationship -

i have 1 many relationship in eloquent model , know best approach go updating model, belongsto model part. i have come across other answers suggest save each belongsto model singly, brings problem making n amount of calls database server instead of single insert or few. so know best approach ensure query , database resourse optimized , efficient. hasone / hasmany (1-1, 1-m) 1. save(new or existing) 2. savemany(array of models new or existing) use of these 2 methods..

java - Sort a list by frequency of strings in it -

this question has answer here: sorting words in order of frequency? (least greatest) 4 answers list is list<string> list = new arraylist<string>(); list.add("apple"); list.add("ball"); list.add("apple"); list.add("cat"); list.add("ball"); now have sort list frequency of apple, ball, cat i have output as: apple ball cat first, count occurrence of string , sort using map list<string> list = new arraylist<string>(); list.add("apple"); list.add("ball"); list.add("apple"); list.add("cat"); list.add("ball"); map<string, integer> map = new hashmap<string, integer>(); (string s : list) { if (map.containskey(s)) { map.put(s, map.get(s) + 1); } else { map.put(s, 1); } } valuecomparator<string,

javascript - How to make image selection area bigger in titanium App? -

how increase selection area of label/image/button everywhere in titanium app? because of android device creates problem while click on label/image/button. takes time or sometime requires double click redirect page in app. think because requires more touch area near outside of label/image/button. please suggest ideas.thanks in advance thanks if goal globally increase tapeable area of every component in app, don't think that's possible make in global way. if it's hard user tap items, you'll have identify items , give them proper width , length. if use ti.ui.size frequently, need following: wrap item in view , assign ti.ui.size width or height move callback wrapping view assign size bottom, top, left, , right of item make wrapping view big enough catch user taps.

android - Checking whether a list item is there in ssharedpreference -

in app use ssharedpreference save list items when clicked on button , retrieving these items activity. in other activity want check if list item present in ssharedpreference or not ,so created method check. if run app, crashes showing nullpointerexception in logcat. method check ssharedpreference codelist codes = (codelist) getrritem(position); private boolean checkarchiveditem(codelist checkcodes) { boolean check = false; list<codelist> archives = archvprefrnces.getarchives(interactivity.this); if (archives != null) { (codelist codes : archives) { if (codes.equals(checkcodes)) { check = true; break; } } } return check; } this line being mentioned in logcat list<codelist> arc

group by - select the most recent answer for each entry MySQL -

i feel should easy making small mistake somewhere. should add teacher , not coder, i'm not versed in sql. in addition, did @ bunch of questions here , none of them quite worked. i have table student_answers(id, student_id, question_id, answer, result, date_time) want question_id , answer , result , date_time last answer student entered each question. if answered 3 times question 7, want see last answer , result entered. for teaching purposes can not update each row re-enter answers. i tried following queries select id, question_id, answer, result, date student_answers student_id = 505 , question_id in (select id test_questions q q.test_id = 37) group question_id having date = max(date) order student_answers`.`question_id` asc but didn't include questions multiple answers @ all, , have me questions student 505 answered once. student 505 answered questions 3 , 4 twice , rest once, , saw results 1, 2 , 5. i tried query select b.* ( select q

javascript - SetInterval not repeating the function execution -

i have js structure this: var intervalid; function counterupdater(){ intervalid = setinterval(ajax_counter_upload(),10000); } function ajax_counter_upload(){ $.ajax({ type: "post", url: "plan/counter.php", data: {tipo:'bp'}, success: function(data){ $("#spinner_msg").fadeto(200,0.1, function(){ $(this).html(data); $(this).fadeto(900,1); }); } }); } function ajax_submit(){ var submit_val=$("#stato").serialize(); dest="plan/new_bp1.php"; $.ajax({ type: "post", url: dest, data: submit_val, success: function(data){ data1=data.split("|"); if(data1[0]=="successo"){ $("#spnmsg").fadeto(200,0.1, function(){$(this).removeclass().addclass("spn_succ

MongoDB, MapReduce and sorting -

i might bit in on head on i'm still learning ins , outs of mongodb, here goes. right i'm working on tool search/filter through dataset, sort arbitrary datapoint (eg. popularity) , group id. way see can through mongo's mapreduce functionality. i can't use .group() because i'm working more 10,000 keys , need able sort dataset. my mapreduce code working fine, except 1 thing: sorting. sorting doesn't want work @ all. db.runcommand({ 'mapreduce': 'products', 'map': function() { emit({ product_id: this.product_id, popularity: this.popularity }, 1); }, 'reduce': function(key, values) { var sum = 0; values.foreach(function(v) { sum += v; }); return sum; }, 'query': {category_id: 20}, 'out': {inline: 1}, 'sort': {popularity: -1} }); i have descending index on popularity datapoint, it's not working because of lack of that: { "v"

ios - Keeping state of UISwitch in TableViewCell: Swift -

i have issue, have tableview setup, users can add , delete new items can check them in , out. mean that, every cell added there comes uiswitch in cell user can turn on , off. "on" being checked in , "off" being checked out. so, that, new programming , know how save state(whether off or on) of uiswitch every time user leaves application switch stays same. thank help. current code: current cell code if new ios development,nsuserdefaults easier use.just save data this: [[nsuserdefaults standarduserdefaults] saveobject:data forkey:@""]; and read data this: [[nsuserdefaults standarduserdefaults] objectforkey:@""]

difference between Firebase and Auth0 authentication -

how auth0.com authentication feature compared firebase authentication? does auth0.com -free or silver plan- provide authentication feature firebase not provide? thanks there few providers auth0 has aren't available on firebase yet-- namely providers use other oauth. also, rules system available in auth0 can powerful-- writing custom login/user rules using js. you can setup two-factor auth , passwordless login systems auth0, doesn't seem available firebase yet. you can integrate firebase auth0 add-on, allows use both pretty seamlessly. all in all, depends on how far want go user system-- i'd recommend checking out auth0's firebase tutorial , documentation learn more.

Cassandra distinct counting -

i need count bunch of "things" in cassandra. need increase ~100-200 counters every few seconds or so. however need count distinct "things". in order not count twice, setting key in cf, program reads before increase counter, e.g. like: result = cf[key]; if (result == null){ set cf[key][x] = 1; incr counter_cf[key][x]; } however read operation slows down cluster lot. tried decrease reads, using several columns, e.g. like: result = cf[key]; if (result[key1]){ set cf[key1][x] = 1; incr counter_cf[key1][x]; } if (result[key2]){ set cf[key2][x] = 1; incr counter_cf[key2][x]; } //etc.... then reduced reads 200+ 5-6, still slows down cluster. i not need exact counting, can not use bit-masks, nor bloom-filters, because there 1m+++ counters , go more 4 000 000 000. i aware of hyper_log_log counting, not see easy way use many counters (1m+++) either. at moment thinking of using tokyo cabinet external k

javascript - Make google map blurry -

i trying make google map (javascript api v3) blurry while focus on other element. what doing right adding: blur(5px); to map-container, work! unfortunately, map gets distorted sometimes. lead me conclusion there gotta better solution, rather adding css rules. maybe using options or styles of api itself?

android - Using pagination with CursorLoader and MergeCursor closes old cursors -

as title says, when trying paginate listview backed simplecursoradapter , cursorloader , old cursors getting closed, below exception being thrown. first 2 pages load fine (the first isn't using mergecursor , second page first 1 use mergecursor ). don't call close() on cursor whatsoever. what interesting while debugging, cannot see closed flags on cursor being set true, it's worth. might issue mergecursor then. let me know if guys have solutions, i'm out of ideas. stack trace: android.database.staledataexception: attempting access closed cursorwindow.most probable cause: cursor deactivated prior calling method. @ android.database.abstractwindowedcursor.checkposition(abstractwindowedcursor.java:139) @ android.database.abstractwindowedcursor.getlong(abstractwindowedcursor.java:74) code: private list<cursor> mcursorslist = new arraylist<>(); @override public void onscroll(abslistview view, int firstvisibleitem, in