Posts

Showing posts from August, 2015

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

PHP cURL POST gives me error 403 while trying to contact STEAM Server -

i'm trying automate accepting trades on steam account, i've been able login , fine gives me hope can contact server remotely, kept login cookies on using curl cookie jar. here's curl code: $useragent = $_server['http_user_agent']; $url = "https://steamcommunity.com/tradeoffer/957#######/accept/"; $params = [ 'sessionid' => "71824xxxxxxxxxxxx" , 'tradeofferid' => ########, 'serverid' => #, 'partner' => ############## ]; $cookie_jar = 'c:\windows\temp\cooc0b3.tmp'; $session = curl_init($url); curl_setopt($session, curlopt_cookiejar, $cookie_jar); curl_setopt($session, curlopt_cookiefile, $cookie_jar); curl_setopt($session, curlopt_header, 1); curl_setopt($session, curlinfo_header_out, true); curl_setopt($session, curlopt_verbose, 1); curl_setopt($session, curlopt_post, true); curl_setopt($session, curlopt_postfields, $params); curl_setopt($session, curlopt_followlocation, true); curl_setopt

r - Processing a variable space delimited file limited into 2 columns -

for whatever reason data being provided in following format: 0001 text 0001 0002 has spaces in between 0003 yet supposed 2 columns 0009 why didn't comma delimit may ask? 0010 or use quotations? 001 knows 0012 i'm here file 0013 , hoping has elegant solution? so above supposed 2 columns. have column first entries, ie 0001,0002,0003,0009,0010,001,0012,0013 , column else. i recommend input.file function "iotools" package. usage like: library(iotools) input.file("yourfile.txt", formatter = dstrsplit, nsep = " ", col_types = "character") here's example. (i've created dummy temporary file in workspace purpose of illustration). x <- tempfile() writelines(c("0001 text 0001", "0002 has spaces in between", "0003 yet supposed 2 columns", "0009 why didn't comma delimit may ask?", "0010 or use quotations?"

Error using Vim Command-T in Ubuntu -

i trying learn vim job. new vim please go easy on me :). installed command-t plugin using vundle . when press leader + t following errors: command-t.vim not load c extension please see installation , trouble-shooting in vim ruby version: 1.9.3-p484 expected version: 2.2.2-p95 below details system: os: unbuntu 14 running on vagrant installed ruby 2.2.2 , ruby-1.9.3-p484 using rvm. gcc version 4.8.4 (ubuntu 4.8.4-2ubuntu1~14.04) ruby 2.2.2 default version project. need upgrade vim ruby 2.2.2. if yes how can upgrade vim ruby in ubuntu. i read couple of solution on stackoverflow , run rake make plugin folder. still getting same error. thanks update below result rake make command ➜ command-t git:(master) rake make /home/vagrant/.rvm/rubies/ruby-2.2.2/bin/ruby extconf.rb checking float.h... yes checking ruby.h... yes checking stdlib.h... yes checking string.h... yes checking fcntl.h... yes checking stdint.h... yes checking sys/errno.h... yes checking sys/socket

Why does Chef throw SSL error when using knife Command on Chef-Workstation? -

ssl error occurs when use knife command verify successful setup of chef-workstation or when try upload chef-cookbook. using following commands : knife client list knife node list knife cookbook upload cookbookname we following error on chef-workstation: openssl::ssl::sslerror: ssl_connect returned=1 errno=0 state=sslv2/v3 read server hello a: unknown protocol to resolve error tried using rackfile software create following 3 files: hostname.key hostname.pem hostname.crt on chef-server. we placed hostname.pem inside chef folder on server , inside certs folder on workstation. tried run commands once again did not succeed. resolve ssl error sincerely appreciated. you need register certificate on each workstation . also, make sure certificate matches correct url (i.e. api endpoint, not web interface)

excel - record how long a variable was above a level in r -

i working on converting project have programmed in excel r. reason doing code includes lots of logic , data means thats excel's performance poor. far have coded around 50% of project in r , extremely impressed performance. the code have following: loads 5min time-series data of stock , adds day of year column labeled doy in example below. the ohlc data looks this: date open high low close doy 1 2015-09-21 09:30:00 164.6700 164.7100 164.3700 164.5300 264 2 2015-09-21 09:35:00 164.5300 164.9000 164.5300 164.6400 264 3 2015-09-21 09:40:00 164.6600 164.8900 164.6000 164.8900 264 4 2015-09-21 09:45:00 164.9100 165.0900 164.9100 164.9736 264 5 2015-09-21 09:50:00 164.9399 165.0980 164.8200 164.8200 264 converts data table called df df <- tbl_df(dia_5) using plyr hint of ttr filters through data creating set of 10 new variables in new data frame cal

php - mysql custom global defined variable -

in database design, tend store variable meant acting role or type smallint . example : create table `house` ( `id` int(11) not null auto_increment, `type` smallint(11) not null, and in php, define('house_small_type', '0'); define('house_medium_type', '1'); so in php, in select queries : $this->db->query("select * house type=?;", house_small_type); my questions : in php part, there better way ? in mysql itself, mysql has global define functionality (like define in php) ? i want kind of select * house type = house_small_type in mysql query. purpose when select in mysql, no way i'm going keep mapping value 0,1,2 real meaning. convineance viewing tables values, without changing structure table , fields. i suggest using mysql variables: set house_small_type = 0; set house_medium_type = 1; then, in queries may use these variables: select * house type = @house_small_typ

r - Cycle for and mvtnorm? -

i need combine cycle function mvtnorm. pmvnorm can done:for example here create vector different value of cumulative probability according different value of mean: a <- c(0, 0, 0) y <- c(0, 0, 0) for(i in 1:3) a[i] <- i*0.5 for(i in 1:3) y[i] <- pnorm(2, a[i], 1) y # [1] 0.9331928 0.8413447 0.6914625 but if use mvtnorm ? have vector of probabilities of bivariate mean of 1 of 2 distribution takes different value. how write command mu? example library(mvtnorm) <- c(0, 0, 0) for(i in 1:3) a[i] <- i*0.5 mu <- c(0, 0) for(i in 1:2) mu[i] <- (1, a) ...and on. i'm blocked command mu. can me? thank you

java - I want to set the text of a button using the words from a txt file -

Image
my buddy , writing simple app in android studio. when push button, new activity opens name of button pushed , displays text in file. i have code generates first set of buttons (these hard coded), , can name of buttons pushed. trouble reading text file , displaying contents. each line in text file word needs text value of button. can't hard code words because can change often. example; on main activity push button labeled "round", sends page has words in text file named "round" listed buttons. i hope more clear. thanks in advance. assuming file in sdcard , youll name same button should work. also, in first activity can make public variable(or extras hi i'm frogatto mentioned. sound better idea mine ) stores name of button clicked , add +".txt". ps: took time make because of curiosity c: public class test extends activity { linearlayout layout; button btnarr [] = new button[50]; int counter = 0,check=0; pro

c# - Mix two or more mp3 files into one, keeping high performance -

i have problem mixing 2 mp3 files one. actually, i've found test code using naudio library, slow me. new "audio programming" need help, advice how make algorithm solving problem faster code below. the code mixes 2 files 1 in 8+seconds much slow. actually, checked , convertwavtomp3() lasts 8 seconds. files 1.mp3 , 2.mp3 3+ minutes long. static void main(string[] args) { var watch = stopwatch.startnew(); watch.start(); var path = @"c:\users\gutek\desktop\"; // read mp3 files disk mp3filereader mpbacground = new mp3filereader(path + "1.mp3"); mp3filereader mpmessage = new mp3filereader(path + "2.mp3"); //convert them wave stream or decode mp3 file wavestream background = waveformatconversionstream.createpcmstream(mpbacground); wavestream message = waveformatconversionstream.createpcmstream(mpmessage); var mixer = new wavemixerstream32(); mix

bash - output of shell script in json form -

i want output of following small shell script in json form. #!/bin/bash top -b -d1 -n1 | grep cpu output: cpu(s): 6.2%us, 1.6%sy, 0.2%ni, 90.9%id, 1.1%wa, 0.0%hi, 0.0%si, 0.0%st required output: {"cpu": "6.3" } how can convert output of such every shell scripts in json form ? you try this echo "{\"cpu\":\"`top -b -d1 -n1 | grep cpu | cut -f3 -d " " | cut -f1 -d %`\"}" a brief description: first, take @ man cut , -f , -d arguments. \" s double quotations, should preceded backslash avoid misunderstanding shell interpreter. , @ last, enclosed in quotation marks `` executed, described here .

while loop - Cannot use (!=) to check char values -

im trying make while loop checks see if user inputted character correct. if character incorrect, loop supposed run until is. however, when enter loop cannot exit, if input correct value. appreciated! if (userinputcheck == 'u' || userinputcheck == 'd' || userinputcheck == 'r' || userinputcheck == 'l'){ return userinputcheck; } else while(userinputcheck != 'u' || userinputcheck != 'd' || userinputcheck != 'r' || userinputcheck != 'l'){ system.out.println("error. please enter u up, d down, r right, or l left"); string temp = keyboard.next(); userinputcheck = temp.charat(0); } return userinputcheck; a test x != 'u' || x != 'd' always true -- think it. if chracter entered u first test false, second true, whole thing true. want use && instead of || : while(userinputcheck != 'u' && userinputcheck != &#

javascript - How to get inner id/class from div? -

this question has answer here: event binding on dynamically created elements? 19 answers i have this: <div id="container"></div> this html. inside of container, add other div elements using jquery. $(document).ready(function () { $.get("/ask", {}, function (response, status) { $.each(response.cars, function (index, val) { $("#container").append("<div class = 'q' id=" + val.id + "\">" + val.carname + "<br>" + val.date + "</div>"); }); }); $("div").click(function (e) { e.stoppropagation(); alert($(this).attr("id")); }); }); on click, want retrieve id inner divs (they 1, 2, 3) whenever click on of divs added using jquery, shows container or nothing @ all. how can id add

xml - IllegalAccessError in Java SE app with Weld implementation -

i trying run standalone app has weld implementation of cdi, , in app need entitymanager work oracle database. when run app (via weld main method), following shown in cmd line: exception in thread "main" java.lang.illegalaccesserror: tried access class javax.xml.parsers.factoryfinder class javax.xml.parsers.factoryfinder$configurationerror @ java.lang.class.getdeclaringclass0(native method) @ java.lang.class.getdeclaringclass(unknown source) @ java.lang.class.getenclosingclass(unknown source) @ java.lang.class.getsimplebinaryname(unknown source) @ java.lang.class.ismemberclass(unknown source) @ org.jboss.weld.util.reflection.reflections.isnonstaticinnerclass(reflections.java:139) @ org.jboss.weld.bootstrap.beandeployer.isbeancandidate(beandeployer.java:98) @ org.jboss.weld.bootstrap.beandeployer.addclass(beandeployer.java:78) @ org.jboss.weld.bootstrap.beandeployer.addclasses(beandeployer.java:135) @ org.jboss.weld.bootstrap.bean

regex - How to parse <a name and <image src= inside <li tag using php? -

i got html string lots of <li> .. </li> sets. want parse following data each set of <li> ...</li> : 1: call.php?category=fruits&amp;fruitid=123456 2: mango season 3: http://imagehosting.com/images/fru_123456.png i used preg_match_all first value how second , third value ? happy if show me second , third item .thanks in advance. php: preg_match_all('/getit(.*?)detailfruit/', $code2, $match); var_dump($match); // iterate new array for($i = 0; $i < count($match[0]); $i++) { $code3=str_replace('getit(\'', '', $match[0]); $code4=str_replace('&amp;\',detailfruit', '', $code3); echo "<br>".$code4[$i]; } sample <li> ..</li> data: <li><a id="fr123456" onclick="setfood(false);setseasonfruitid('123456');getit('call.php?category=fruits&amp;fruitid=123456&amp;',detailfruit,false);">mango season</a&

javascript - Error "InvalidCastException: Cannot cast from source type to destination type." While using Instantiate in Unity -

okay, i'm making 2d game in unity, , when run code, error: invalidcastexception: cannot cast source type destination type. toastspawn.spawntoast () (at assets/scripts/toastspawn.js:11) the code in file toastspawn.js follows: #pragma strict var toast : rigidbody; var toastspawner : gameobject; function start() { invokerepeating("spawntoast", 3, 1); } function spawntoast() { var toastclone = instantiate(toast, gameobject.find("toastspawner").transform.position, quaternion.identity); toastclone.addforce(vector2 (0,1) * 1000); } i started using unity yesterday, why getting error. :) well, it'd better if take start c# :p although not javascript guy still can see glitches. you instantiating rigidbody instead of gameobject. take gameobject instead of rigidbody, getcomponent of rigidbody object in order apply force. you have toastspawner gameobject why or using gameobject.find? same gameobject. something like, var toast

php - Finding and replacing keywords with link using DOMDocument -

i've been researching way find keywords if inside of 'p', 'span' or 'blockquote' , replace them link, using domdocument. i've written piece of regex achieves this, rather use domdocument should result in better solution. the code below has 2 main issues, if place &amp; in $html .. crashes because &amp; isn't escaped , can't find way correctly escape &amp; . a smaller issue, not important .. if html invalid domdocument tries correct html , seem unable prevent this. the preg_replace uses array, because dynamically loaded using multiple keywords. $html = ' <blockquote>random random text</blockquote> <p>we match text</p> <p>this sample text</p>'; libxml_use_internal_errors(true); $dom = new domdocument(); $dom->stricterrorchecking = false; $dom->loadhtml(mb_convert_encoding($html, 'html-entities', "utf-8")); $xpath = new domxpath($dom); foreach($xpath-&g

angularjs - Angular UI Bootstrap Modal doesn't work with ng-include -

live example: http://plnkr.co/edit/wws3ufb3iz0cai4u2x04?p=preview when "open modal 1" clicked, following error thrown: error: dialog.open expected template or templateurl, neither found. use options or open method specify them. however, modal 2, doesn't use ng-include , works fine. also, if ui-bootstrap-tpls-0.1.0.js included instead of ui-bootstrap-tpls-0.2.0.js , works fine. any ideas? i believe issue result of changing modal directive terminal. means other directives (e.g. ng-include) not processed along modal. here's commit made change: https://github.com/angular-ui/bootstrap/commit/ec796ec2299d03ddfb821e97047c0329f11ab962#src/modal/modal.js i don't know enough know why directive should terminal, 1 easy solution use ng-include child of modal, rather second directive acting on same element. here's mean: <div modal="opened1"> <ng-include src="'modal1.html'"></ng-include> <

scikit-learn fit function classification -

i using fit function classification training in scikit-learn. example, while using random forests, 1 typically uses following type of code: import sklearn sklearn.ensemble import randomforestclassifier rf forest=rf(n_estimators=10) forest=forest.fit(trainingx,trainingy) unfortunately, following error when using python 3: c:\anaconda3\lib\site-packages\sklearn\base.py:175: deprecationwarning: inspect.getargspec() deprecated, use inspect.signature() instead forest=forest.fit( args, varargs, kw, default = inspect.getargspec(init) c:\anaconda3\lib\site-packages\sklearn\base.py:175: deprecationwarning: inspect.getargspec() deprecated, use inspect.signature() instead args, varargs, kw, default = inspect.getargspec(init) does know error means? it looks getargspec deprecated since python 3.0(see getargspec doc ), getting warnings (not errors) when gets called. used lot in sklearn. there discussion of on scikit-learn issue tracker. raised here , f

sorting - How do I sort a perl hash by multiple keys? -

hi have data structure of following form: $data = { 'a' => { key1 => 2, key2 => 1 }, 'b' => { key1 => 1, key2 => 2 }, 'c' => { key1 => 1, key2 => 1 }, 'd' => { key1 => 3, key2 => 2 }, 'e' => { key1 => 3, key2 => 1 }, 'f' => { key1 => 1, key2 => 2 }, }; what want able loop through data structure in ascending order of key2 , descending order of key1 , , ascending order of