Posts

Showing posts from May, 2014

java.lang.reflect.InvocationTargetException in xamarin.android -

i exception when click button in fragment. below code fragment public override java.lang.object instantiateitem(viewgroup container, int position) { int pos = position + 1; if (pos == 1) { view view = layoutinflater.from (container.context).inflate (resource.layout.pager_item, container, false); container.addview (view); return view; } else if (pos == 2) { view view = layoutinflater.from (container.context).inflate (resource.layout.bookaservice, container, false); spinner spinner = view.findviewbyid<spinner> (resource.id.spinner); var adapter = arrayadapter.createfromresource ( container.context, resource.array.planets_array, android.resource.layout.simpledropdownitem1line); adapter.setdropdownviewresource (android.resource.layout.simpledropdownitem1line); spinner.a...

pandoc - Convert markdown to reStructuredtest? -

how can convert file named index.md restructuredtext file index.rst without manual editing or anything? how vice-verse? what general syntax of such changes? pandoc --from=markdown --to=rst --output=index.rst index.md for reverse can try pretty same thing pandoc --from=rst --to=markdown --output=readme.md readme.rst the general syntax is pandoc --from={type} --to={type} --output={filename} {input-filename}

javascript - Convert an Array of Images png to Base64 -

i'm trying convert png images, lot of them base64 , send them on post request server-side application. i have looked , found function author has done http://jsfiddle.net/handtrix/yvq5y/ here, want: function convertimgtobase64url(url, callback, outputformat){ var img = new image(); img.crossorigin = 'anonymous'; img.onload = function(){ var canvas = document.createelement('canvas'), ctx = canvas.getcontext('2d'), dataurl; canvas.height = this.height; canvas.width = this.width; ctx.drawimage(this, 0, 0); dataurl = canvas.todataurl(outputformat); callback(dataurl); canvas = null; }; img.src = url;} i'm using way: convertimgtobase64url(model.cells[i].attrs.image["xlink:href"], function(base64img){ // base64dataurl console.log(base64img) }); as can see each cells contains image, need convert base64 before sending on post request, question how can convert array of png ima...

How to run shell-commands in IPython? (Python Profiling GUI tools) -

i trying file profiling in ipython, generate profiling stats output , pass python profiling gui tools kcachegrind. here code trying that. codes executed in ipython. # example function profiling def factorial(n): if n == 0: return 1.0 else: return float(n) * factorial(n-1) def taylor_sin(n): res = [] in range(n): if % 2 == 1: res.append((-1)**((i-1)/2)/float(factorial(i))) else: res.append(0.0) return res # generate cprofile output (the stats, not text) %prun -d prof.out x = taylor_sin(500) # conversion using pyprof2calltree # in ipython, add prefix '!' code make shell-command code !pyprof2calltree -i prof.out -o prof.calltree and ipython prints error message: !pyprof2calltree -i prof.out -o prof.calltree /bin/sh: 1: pyprof2calltree: not found is saying haven't add pyprof2calltree environment path or that? how solve it? i can run in pure shell command. don't switch between ipython...

Neo4j 2.2.2 server does not start after db is generated via java code -

i new neo4j. trying application in java using neo4j 2.2.2 along spring data. using spring-data-neo4j (2.2.2.release) connect neo4j db. have done crud opertaions using repositories in spring data. unable open & view db in neo4j ui tool. when trying start neo4j server console, getting bellow error message. emuser1@em02-desktop:~/installations/neo4j-community-2.2.2/bin$ ./neo4j start warning: max 1024 open files allowed, minimum of 40 000 recommended. see neo4j manual. starting neo4j server...warning: not changing user process [14509]... waiting server ready.. failed start within 120 seconds. neo4j server may have failed start, please check logs. i have checked message.log file in db store. showing below exceptions. java.lang.runtimeexception: error starting org.neo4j.kernel.embeddedgraphdatabase, /home/emuser1/installations/neo4j-community-2.2.2/data/graph.db @ org.neo4j.kernel.internalabstractgraphdatabase.run(internalabstractgraphdatabase.java:334) ~[neo4j-kernel-2.2.2.ja...

machine learning - Too small RMSE. Recommender systems -

sorry, i'am newbie @ recommender systems, wrote few lines of code using apache mahout lib. well, dataset pretty small, 500x100 8102 cells known. so, dataset subset of yelp dataset "yelp business rating prediction" competition. take top 100 commented restaurants, , take 500 active customers. i created svdrecommender , evaluated rmse. , result 0.4... why small? maybe don't understand , dataset not sparse, tried larger , more sparse dataset , rmse become smaller (about 0.18)! explain me such behaviour? datamodel model = new filedatamodel(new file("datamf.csv")); final ratingsgdfactorizer factorizer = new ratingsgdfactorizer(model, 20, 200); final factorization f = factorizer.factorize(); recommenderbuilder builder = new recommenderbuilder() { public recommender buildrecommender(datamodel model) throws tasteexception { //build here whatever existing or customized recommendation algorithm return new svdrecom...

ruby - rails block a record for change for another places in the code -

i have ruby on rails application lot of sidekiq workers. of workers can work while (at least few minutes). how can block record changes places (ie controllers), avoid data conflict when save record in worker? you need lock model: account = account.first account.with_lock # block called within transaction, # account locked. account.balance -= 100 account.save! end you can read more here .

python - a simple command -- "np.save", maybe i misunderstood -

just working through example numpy.save -- http://docs.scipy.org/doc/numpy/reference/generated/numpy.save.html examples from tempfile import temporaryfile outfile = temporaryfile() x = np.arange(10) np.save(outfile, x) after command (highlighted), why not find output file called "outfile" in current directory? sorry may sound stupid outfile.seek(0) # needed here simulate closing & reopening file np.load(outfile) array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) it because using - temporaryfile , temporary file not stored outfile in directory. if want save outfile , can give name , save file. np.save('outfile',x) when saving load, need use , again filename string - np.load('outfile')

Filter Anagram in Array in Python -

i'm trying go through array , delete elements aren't anagrams in python. here code wrote. logic seems fine can't seem it. b = ['cat', 'dog', 'god', 'star', 'lap', 'act'] array=[] t=0 in b: while t<len(b): if ''.join(sorted(i))==''.join(sorted(b[t])): array.append(i) t+=1 print array just minor tweaks existing code should work. b = ['cat', 'dog', 'god', 'star', 'lap', 'act'] array = [] t = 0 i, value in enumerate(b): t = i+1 while t<len(b): if ''.join(sorted(value))==''.join(sorted(b[t])): array.extend([value, b[t]]) t+=1 print array ['cat', 'act', 'dog', 'god']

How to import neo4j dump into the current database -

i can dump of current database following: neo4j-shell -c dump > dump.sql now how import dump file database (using shell) neo4j-shell -file dump.sql the shell exit after executing file. see http://neo4j.com/docs/2.2.2/re02.html

sass - CodeIgniter 3.0 with Foundation 5 -

i'm using codeigniter 3.0 , foundation 5. installed sass/scss , compass make working foundation easier. i'm wondering possible use them together? foundation cli builds new directory of content, have existing ci project i'd integrate with. i resolved adding empty compass project codeigniter, copied foundation scss , bower_components directories source directory. adding add_import_path src/bower_components/foundation/scss config.rb allow importing of foundation scss. # require additional compass plugins here. add_import_path "src/bower_components/foundation/scss" # set root of project when deployed: http_path = "/" css_dir = "src/css" sass_dir = "src/sass" images_dir = "images" javascripts_dir = "src/js"

ios - How to locate Xcode after installation (Xcode beta)? -

i'm new world of ios , have started learning technologies used create ios apps. i’ve downloaded xcode 7 (beta) on mac (which has os 10.10.2). i’ve used downloaded file (xcode_7_beta.dmg) complete installation using terminal command (xcode-select —install). installation seems have completed i’m struggling locate installation anywhere intention launch it. appreciate around it. thanks. the application named xcode-beta , exist in applications folder. this located off root of drive at: /applications

android - How to adjust the code to download full size content? -

how download full size content. followed android connecting network tutorial , mentioning int len = 500; it's downloading 500 character api returns more character. how adjust code download full content ? below code having ... private string downloadurl(string myurl) throws ioexception { inputstream = null; // display first 500 characters of retrieved // web page content. int len = 500; try { url url = new url(myurl); httpurlconnection conn = (httpurlconnection) url.openconnection(); conn.setreadtimeout(10000 /* milliseconds */); conn.setconnecttimeout(15000 /* milliseconds */); conn.setrequestmethod("get"); conn.setdoinput(true); // starts query conn.connect(); int response = conn.getresponsecode(); = conn.getinputstream(); // convert inputstream string string contentasstring = readit(is, len); return contentasstring; // makes su...

web - Directory mapping and merging in git -

i have online store running oscommerce , use git manage development, official release uses git. i go through changelog , read each change each file, type said change, , commit. can imagine takes forever , increases chance of me typing , commiting wrong. i'd easier way manage updates/merging official git repo without having hand edit each file , commit. know git has merge command run 2 obstacles when thinking problem. the file structure isn't same. all files located in shop/ , default catalog/ i want merge changed files official "catalog/" directory files in "shop/" directory. i rather not download/redownload every readme, changelog, , other removed files every time updates official repo how can update/merge files without retyping every change in manually taking account above 2 problems? what's proper workflow situation?

algorithm - Flatten out a list in java -

i asked question in interview given hypothetical list in java that, along holding integer content, may hold list of similar type example: [1,3,5,[6,7],8,9,10,[11,13,15,[16,17,[18,19]]],20] output should be: [1,3,5,6,7,8,9,10,11,13,15,16,17,18,19,20] easy thought! came recursive solution solved problem! or not? the interviewer said sublists go down depths , hence may result in stackoverflow error! i tried coming non recursive solution, couldn't. tell non recursive solution might be? you can use linkedlist stack. public static list<object> flattennonrecursive(list<object> list) { list<object> result = new arraylist<>(); linkedlist<object> stack = new linkedlist<>(list); while (!stack.isempty()) { object e = stack.pop(); if (e instanceof list<?>) stack.addall(0, (list<?>)e); else result.add(e); } return result; } public static list...

c# - How to assign Control + . as a shortcut key? -

i want catch keys in winform keydown event , set control + . shortcut key. but can't find . (dot) key in keys list. private void frmmain_keydown(object sender, keyeventargs e) { if (e.control && e.keycode == keys.dotkey) //what dot key //do somthing } keys.decimal on layout , keys.oemperiod on german layout you're looking for.

javascript - How to call POST method in node.js service? -

i trying validate json jsonschema. server.js code: // set ====================================================================== var express = require('express'); var app = express(); // create our app w/ express var port = process.env.port || 8080; // set port var bodyparser = require('body-parser'); var methodoverride = require('method-override') app.use(function(req, res, next) { //the code hits point! var data = ''; req.on('data', function(chunk) { data += chunk; }); req.on('end', function() { req.rawbody = data; }); console.log(data); next(); }); app.use(bodyparser.json()); app.use(methodoverride()); // routes ====================================================================== require('./routes.js')(app); // listen (start app node server.js) ====================================== app.listen(port); console.log(...

arrays - odd results from nested for loops javascript -

i'm trying check submitted string against letterset. if word_string = "gar" , should return "gar" because these letters appear in letterset. for reason, words appear correctly, , appear missing letters. example, word_string = "rag" , returns "r" . "fig" returns "fg" . letterset = {0: "r", 1: "a", 2: "g", 3: "a", 4: "o", 5: "e", 6: "f", 7: "i"} var ls = []; (prop in letterset) { ls.push(letterset[prop]); }; console.log(ls) var word_string = ''; var word = document .getelementbyid('word_container') .childnodes; (var in word) { var w = word[i].innerhtml; (var prop=0; prop<ls.length; prop++) { if (ls[prop] == w) { console.log(w); word_string += w; ls.splice(prop); ...

angularjs - Class directive not working when using ng-class with condition -

i tried load directive below not working. <div ng-class="{'nav-dropdown' : dt.url == null }"> </div> it works fine if assigned class this: <div class="nav-dropdown"> </div> edit: when using method: <div ng-class="{'nav-dropdown' : dt.url == null }"> </div> the class added inside html as <div class="nav-dropdown"> </div> the main problem : directive doesn't show <div class="nav-dropdown"><div>this directive template</div></div> what want load directive condition : dt.url null. can help? you can use ternary expression <ng-class="condition ? 'true' : 'false'"></div> so, instead use this: <div ng-class="{'nav-dropdown' : dt.url == null }"> </div> you use this: (this works me) <div ng-class="dt.url == null ? 'nav-dropdown...

python - how can i get newBalance to == outstandingBalance when loop iterates through range and newBalance > 0 -

outstandingbalance = 1800 #declaring variables apr = .18 interest = apr / 12 #annual interest rate minpay = 0 #minpayment needed payoff balance in year newbalance = outstandingbalance month = 0 #month counter while newbalance>0: month = month+1 minpay = minpay + 10 in range(1, 13): newbalance = newbalance * (1+interest) - minpay if newbalance < 0: break so trying newbalance go outstandingbalance value when loop iterates through range , newbalance still >0 can increase minpay each iteration 10 until @ 12 months newbalance <0 as understand it, you're trying determine minimum monthly payment needed ensure outstanding balance paid off within year, , you're approaching incrementing minimum payment 10 until balance paid within year. can code , running moving newbalance = outstandingbalance line loop ensure you're restarting calculation original balance each time: outst...

perl Encode::_utf8_off in python -

what python's equivalent function of perl's encode::_utf8_off ? you should never ever use encode::_utf8_off . you trying encode string using utf-8. in perl, you'd use of following: utf8::encode($s); utf8::encode( $utf8 = $uni ); use encode qw( encode_utf8 ); $utf8 = encode_utf8($uni); use encode qw( encode ); $utf8 = encode('utf-8', $uni); i don't know python, quick search finds utf8 = uni.encode('utf-8', 'strict')

ios - tableView dataSource and delegate restrictions -

why tableview on ios needs "numberofrowsinsection" , "cellforrowatindexpath" functions run when it's datasource connected view controller? there 2 ways how can put rows uitableviewcontroller: variable or static care, static can used when using uitableviewcontroller , not uitableview static means specify when write app exact rows in table, special case , used settings etc. the more common case don't know exact rows displayed since load data internet , display data depending on loaded. from question sounds looking static approach, in case don't need these methods, but in general avoid using static tableview since if ever changes have work transfer it.

node.js - How to get data back from Mongoose without using a callback? -

ultimately knowledge bad started few hours ago. in head should work: getall: function(callback){ user.find({}, function (err, data) { if (err) return console.error(err); return data; }); } var users = api.getall(); console.log(users); //undefined but reason have pass callback data working so: getall: function(callback){ user.find({}, function (err, kittens) { if (err) return console.error(err); callback(kittens); }); } var users = api.getall(function (data) { console.info(data); //does output data }); how can option one, easier read of 2 work? unfortunately can't. when execute function, whatever return it. if return nothing undefined default. instead of having readability based on getting user , should have based on you're going once you've gotten it. presumably you'll have action(s) you'll want perform on user, right? promises can make code better callbacks. here's code re-written ...

php - Call a Controller in every 10 Seconds on CodeIgniter -

i made research on site couldn't find answer, decided yo ask this. i'm getting data via xml , xml renews every 10 seconds. so, have re-run controller in every 10 seconds. can not make via cron know not allowing cron jobs under 1 minute. thanks in advance. use sleep , run script once. while(true) { sleep(10); // parse xml } or if wanna limit time, change true limit , increment in end of block. problem within solution if xml parsing takes 5 seconds, called in each 15 seconds, make arrangement according this.

ecmascript 6 - Obj-C category/extension Swift in Javascript ES6 -

i'm looking add methods class in javascript es6 without creating subclass of it, in same way categories in objective-c or extensions in swift. i didn't find information it. any suggestion? es6 class syntax syntax sugar on javascript's prototypal inheritance model. add methods class, can add more properties onto prototype. class { } something.prototype.newmethod = function(){ };

Kotlin-JS interop - using language constructs -

i have js interop function using for in construct iterate on input elements, it's throwing error @ runtime. native("document") val ndoc: dynamic = noimpl fun jsinterop() { js("console.log('js inling kotlin')") val ies = ndoc.getelementsbytagname("input") (e in ies) { console.log("input element id: ${e.id}") } } getting following js error uncaught typeerror: r.iterator not functionkotlin.definerootpackage.kotlin.kotlin.definepackage.js.kotlin.definepackage.iterator_s8jyvl$ @ kotlin.js:2538 any suggestions on how fix one? kotlin : m12 the generated js code function is, jsinterop: function () { var tmp$0; console.log('js inling kotlin'); var ies = document.getelementsbytagname('input'); tmp$0 = kotlin.modules['stdlib'].kotlin.js.iterator_s8jyvl$(ies); while (tmp$0.hasnext()) { var e = tmp$0.next(); console.log('input ...

ios - UINavigationController nested Inside UINavigationController (UITabbarController more tab) -

Image
i'm having issue have uinavigationcontroller tab on uitabbarcontroller. works when it's normal tab on tab bar, when placed inside more tab , selected app crashes message "nsinvalidargumentexception', reason: '*** -[__nsplaceholderarray initwithobjects:count:]: attempt insert nil object objects[0]" is because there nested uinavigationcontrollers? here image of call stack.

node.js - Tibco EMS connectivity using nodejs /Javascript -

how can connect tibco nodejs environment. have tried connect tibco ems queue using nodejs package stompjs or javascript component. one of tibco approach use tibco web messaging product. separate module offer bridge ems, callable javascript , flash programs. meant of extreme scaling of mobile devices. if stay tibco solutions, ftl option. low latency next generation messaging bus can interfaced javascript. if either of these solutions not acceptable, can create web service responsible of creating messages on bus. of course more difficult reading out of queue or subscribing topic... can done. and last not least... other (sometimes free) messaging buses have rest api interfaces. 1 example activemq .

Java servlet sessions within multiple iframes -

i have site, call www.main.com 4 iframes loads www.iframe.com/foo each of iframes. upon initial load of www.iframe.com/foo make call config.bar() servlet (foo) load user data session. before make call config.bar() i'm checking see if config loaded session , if so, skip fetch config.bar() , load session. my problem is, since session not yet established in foo, getting 4 unique session id's, making 4 calls config.bar(). when refresh www.main.com page, 4 iframes load again assigned sessionid of first iframe load (from previous request). i tried moving logic filter hoping right things had no effect. possible load servlet multiple times within iframes different url , have 1 session id @ time of initial load? here's snippets demonstrate i'm trying do: www.iframe.com/foo: //--foocontroller.java @controller class foocontroller { @requestmapping(value = "/foo", method = requestmethod.get) public string foo(model model, httpservletrequest request) ...

php - Am I safe?? [trying to prevent sql injection] -

this question has answer here: how can prevent sql injection in php? 28 answers i wondering if i'm safe sql injection if have in script: < script> //some stuff var item = <?php echo json_oncode($phpvar) ?> item.replace(/"/,'&quot').replace(/'/,'&#39'); //do more script stuff item < /script> currently using laravel (php), pdo there else should aware of/look out for? (i didn't whitelist/blacklist before submitting database b/c pdo me understand) also i'm asking b/c item taken user input , dynamically creates html using value of item the question unanswerable (atleast not in way not give false sense of security) amount of resource provided. since using pdo i'll go right ahead , ought using prepared statements . injection on whole lies on how web application handles ...

documentation - Netbeans 8 auto add author to method comment -

when type methods , generate comments via /** enter. generates comment this. /** * @param int $weight * @return \kt_forbes_theme_model */ is possibility auto add @author ? /** * @author guy * @param int $weight * @return \kt_forbes_theme_model */ i have add @autor manualy method, anoing. it seems not possible in current netbeans versions reported in https://netbeans.org/bugzilla/show_bug.cgi?id=251426 . there related posts issue modify command / template function commenting in netbeans. triggering "/** + enter key" or edit comment template in netbeans php 6.8 (this last 1 not solve issue - @ least in netbeans 8.1). i'm fighting ide include auto comments data cause comment added looks like: /** * */ whitout info included.

sql - How to remove duplicate ID rows. While removing, use the rows that has NULL value in another column -

while removing duplicate rows same id value, how remove rows has null value in 1 particular column. note: there other non-duplicate rows (below e.g., 12) has null value , should still selected in result set. input table: id | sale_date | price ----------------------------- 11 20051020 22.1 11 null 20.1 12 null 20.1 13 20051020 20.1 expected result: id | sale_date | price ----------------------------- 11 20051020 22.1 12 null 20.1 13 20051020 20.1 assuming have sql server 2008 or above, work you. use row_number , assign values id starting @ max date. value higher 1 lower max date particular id delete row_num greater 1. check out: declare @yourtable table (id int,sale_date date, price float); insert @yourtable values (11,'20051020',22.1), (11,null,20.1), (12,null,20.1), (13,'20051020',20.1); cte ( select *, row_number() on (partitio...

ios - Sender: AnyObject crashes when UIBarButtonItem is pressed -

i having trouble understanding how create barbuttonitem , set sender anyobject. created barbuttonitem programmatically , tried set sender object app crashes when button pressed. import uikit class viewcontroller: uiviewcontroller { override func viewdidload() { super.viewdidload() // additional setup after loading view. var toggle = uibarbuttonitem(title: "settings", style: uibarbuttonitemstyle.plain, target: self, action: "togglesidemenu") self.navigationitem.leftbarbuttonitem = toggle } func togglesidemenu(sender: anyobject) { togglesidemenuview() } that "selector" has parameter, should be: action: "togglesidemenu:" ^ plus method need @objc annotation , i'm pretty sure sender optional, so: @objc func togglesidemenu(sender: anyobject?) { togglesidemenuview() }

Use Java as “scripting” language in C++ -

this question has answer here: how call java functions c++? 6 answers let’s i’m designing cross-platform application in c++ can user-extended through add-ons. application offer c++ api , load dynamic objects ( .so , .dll , etc.). but, cumbersome users have compile 6 target platforms (windows x86 / x86-64 , macos x x86 / x86-64 , gnu/linux x86 / x86-64 ). in order keep portability, thought of providing ruby api using libruby . little work came proof of concept. problem i’m worried performances . these add-ons may big , cruby isn't fast. then thought, why not java ? java bytecode has better runtime performances, jit; it portable; distribution simple, users have provide jar ; users can provide closed-source add-ons (even if decompiling java bytecode not hard); more people know java ruby. the question now, how achieve this? made research , found out ...

php - Symfony 2: "No route found for "GET /" - error on fresh installation -

i'm trying begin education of symfony 2 , started tutorial. 1 of first things tried install symfony 2 , configure it. when i'm trying access http://127.0.0.1:8000/ i'm getting incomplete site error: error - uncaught php exception symfony\component\httpkernel\exception\notfoundhttpexception: "no route found "get /"" @ /home/spectator/webprojects/cls/app/cache/dev/classes.php line 2059 things i've tried far: clearing cache (php app/console cache:clear --env=prod --no-debug), recursively changing permissions folder cls (symfony 2 folder) 775 , 777 (for diagnostics purposes), adding "/" route routing.yml , routing_dev.yml, reinstalling , re-chmod symfony 2. try http://localhost:8000/app/example fresh installation has no routes root path "/"

swift - Most common dictionary in array of dictionaries -

i need find common dictionary in array of swift dictionaries. tried using following : func frequencies <s: sequencetype s.generator.element: hashable> (source: s) -> [(s.generator.element,int)] { var frequency: [s.generator.element:int] = [:] x in source { frequency[x] = (frequency[x] ?? 0) + 1 } return sorted(frequency) { $0.1 > $1.1 } } but can't invoke 'frequencies' argument list of type [[string:string]]() . how can edit above function take array of dictionaries, or use method entirely? you use nscountedset provides kind of functionality: let arr = [ [ "foo": "bar" ], [ "foo": "bar" ], [ "foo": "baz" ], ] let countedset = nscountedset(array: arr) dict in countedset { println(coun...

amazon web services - AWS EC2 response not received on the client side -

i using t2.micro instance serve requests front-end hosted on s3. interestingly enough, 90% of users can response. however, there 10% can't response back. of these users in enterprise environment. i had chance check 1 of friend's chrome dev tool (using on our front-end) , saw weird behaviour no response sent back. then, sent json request endpoint directly. there onwards, started work. recently, potential adopter enterprise tried our prototype , same thing happened again. time, wasn't lucky , got lecturing user. :( i tried searching online tons of possibility. can come 2: ( ) firewall blocks response sending ec2 addresses (i not using route 51 yet attach our domain name yet) ( ii ) there sort of routing issues going on if think these reasons what's happening, please let me know can fix them. otherwise, debugging steps can take? you can find our site here: http://resohub.s3-website-us-east-1.amazonaws.com/ , test if have same problem. updates: (a) typo in ...

swing - Making a chess game in Java, I want to move the pieces -

so have images stored imageicon's on jbuttons. want user click on jbutton of piece want use , click on jbutton move there, how this? i've tried using actionlistener imageicon proving complicated because have 2d array of jbutton images. actionlistener actionlistener = new actionlistener() { public void actionperformed(actionevent actionevent) { system.out.println(actionevent.getactioncommand()); } }; jbutton[][] squares = new jbutton[8][8]; border emptyborder = borderfactory.createemptyborder(); (int row = 0; row < squares.length; row++) { (int col = 0; col < squares[row].length; col++) { jbutton tempbutton = new jbutton(); tempbutton.setborder(emptyborder); tempbutton.setsize(64, 64); squares[row][col] = tempbutton; squares[row][col].addactionlistener(actionlistener); panel.add(s...

Will write spaces but not the last character (VBA Excel) -

Image
data: desired output: current output: my current code: private sub generateflatfile_click() dim myfile string, rng range, cellvalue variant, integer, j integer, spacingcode string dim ipar integer dim sblank long dim cont boolean dim mystring string myfile = "c:\reformatted.txt" set rng = selection open myfile output #1 dim strarr(1 63) string, intbeg integer, intend integer, intcount integer, schar string = 2 rng.rows.count j = 1 rng.columns.count if instr(1, cstr(cells(1, j).value), "63") = 1 strarr(val(cells(1, j).value)) = cells(i, j).value elseif instr(1, cstr(cells(1, j).value), "code") ipar = instr(1, cstr(cells(i, j).value), "(") if mid(cells(i, j).value, ipar - 1, 1) = "" if mid(cells(i, j).value, ipar - 2, 1) = "" schar = mid(cells(i, j).value, ipar - 3, 1) else: schar = ...

.htaccess - What does "!" do in a rewrite Rule? -

i looking @ htaccess file. contains content rewriteengine on rewriterule !\.(css|jpg|png|xml)$ index.php what "!" , valid redirection css , other critical files? ! means not . in other words, long following doesn't match, apply rule. # not end in .css, .jpg, .png, or .xml # send index.php rewriterule !\.(css|jpg|png|xml)$ index.php

r - gpclibPermit() is FALSE, cannot install gpclib -

i have similar problem user, how turn gpclibpermit() true solution install gpclib, error > install.packages("gpclib") package available in source form, , may need compilation of c/c++/fortran: ‘gpclib’ these not installed then download gpclib_1.5-5.tar.gz http://cran.r-project.org/web/packages/gpclib/index.html , extract library folder, i.e d:\r\r-3.2.0\library. when execute following, still errors: > install.packages("gpclib") package available in source form, , may need compilation of c/c++/fortran: ‘gpclib’ these not installed > gpclibpermitstatus() [1] false thanks update i tried > install.packages("d:/r/gpclib_1.5-5.tar.gz", repos = null, type = "source") and got error * installing *source* package 'gpclib' ... ** package 'gpclib' unpacked , md5 sums checked ** libs *** arch - i386 warning: running command 'make -f "d:/r/r-3.2.0/etc/i386/makeconf" -f "d:/r/r-3...

R summing row one with all rows -

i trying analyse website data ab testing. reference point based on experimentname = experiment 1 (control version) experimentname uniquepageview uniquefrequency nonuniquefrequency 1 experiment 1 459 294 359 2 experiment 2 440 286 338 3 experiment 3 428 273 348 what need sum every uniquepageview, uniquefrequency , nonuniquefrequency row when experimentname = experiment 1 e.g. uniquepageview experimentname = 'experiment 1 ' + uniquepageview experimentname = 'experiment 2 ', uniquepageview experimentname = 'experiment 1 ' + uniquepageview experimentname = 'experiment 3 ' so on forth (i have unlimted number of experiment #) same uniquefrequency , nonuniquefrequency (i have unlimited number of column well) result expected: experimentname uniquepageview uniquefrequency nonuniquefrequency conversion rate pooled uniq...

ruby on rails - Rspec can't stub where or find_by_, only find -

i'm going share several pairs of run code , test code. basically, test code working when use find on object class, problem find 1 method don't want use because i'm not looking primary key! approach 1 : stubbing :where plan.all first can called on it #run code @current_plan = plan.where(stripe_subscription_id: event.data.object.lines.data.first.id).first #test code @plan = plan.new #so first plan i'd find plan.stub(:where).and_return(plan.all) #result of @current_plan (expecting @plan) => nil approach 2 : chain stubbing :where , :first #run code @current_plan = plan.where(stripe_subscription_id: event.data.object.lines.data.first.id).first #test code @plan = plan.new #so first plan i'd find plan.stub_chain(:where, :first).and_return(@plan) #result of @current_plan (expecting @plan) => nil approach 3 : stubbing custom :find_by #run code @current_plan = plan.find_by_stripe_subscription_id(event.data.object.lines.data.first.id) #test code...

How to set back key action on Android -

i'm working on android application starts activity serves menu screen (i'll call activity menu activity). there button moves app activity user can enter name (i'll call activity name activity), , app returns menu activity. after entering name, (i have gone this: menu - name - menu) when press button, goes name activity, name still present in edittext field. i'd know if there's way change key's functionality avoid going name activity, , instead return main activity (the hierarchy - main - menu - name). also, there way can prevent name being retained in edittext? thanks in advance. i'm bit confused hierarchy either way you're looking if want clear previous activities: clearing activity backstack otherwise call finish() on activity want close before changing. clear edittext

java - Updating JPA Entity Model -

i have application running on google app engine uses jpa. imagine @ point, application evolves, new attributes added java classes, requiring update jpa model. how changes handled once application in production? for example, lets add new field (foo) class (bar), , foo isn't nullable. during course of transaction, entitymanager reads in old bar object(before foo added), updates field, , tries commit change, , exception happens. want guard against. in general, there best practice updating jpa model after it's been put production avoid constraint conflicts older objects have been persisted? unfortunately updating model not trivial in gae. you'll have either update existing entities or create "update on demand" entities don't fail new conditions. adding not nullable field example forces update entities beforehand jpa not allow afterwards.

matlab - How to associate the 'MarkerSize' to a value that means the radius of a plotted circle? -

Image
i have 3 vectors of same length. 2 of them contain x , y coordinates of want plot. third 1 contains values want associate radius of plotted circle. i have read 'markersize' in plot corresponds number of points in circumference, , if want use scatter , third vector corresponds area of plotted circle. nonetheless, want third vector associated radius as such, how associate size of circles radius? i have using plot : hold on; nd = 1 : 24 plot(xl(nd), -yl(nd), 'o', 'markerfacecolor', 'g', 'markeredgecolor', 'k', 'markersize', attribute(nd)) end and using scatter : hold on; nd = 1 : 24 scatter(xl(nd), -yl(nd), attribute(nd), 'o', 'markerfacecolor', 'k', 'markeredgecolor', 'k') end thanks in advance help. assuming want use markersize attribute plot , said, number reports circumference of plotted marker in pixels. well, know there's relationship be...

mysql syntax error 1064 (42000) -

i have standard lamp configuration (apache2, mysql, php5), running on ubuntu, , i'm typing mysql commands terminal. i'm logged mysql command line root. far i've created new database, trouble started. i'm trying create simple table getting mysql syntax error , can't figure out i'm doing wrong. this error: error 1064 (42000): have error in sql syntax; check manual corresponds mysql server version right syntax use near ')' @ line 10 and query: create table if not exists `customers` ( `uid` int(11) not null auto_increment primary key, `name` varchar(50) not null, `email` varchar(50) not null, `phone` varchar(100) not null, `password` varchar(200) not null, `address` varchar(50) not null, `city` varchar(50) not null, `created` datetime not null default timestamp ); no idea what's wrong honestly. you can assign default value current_timestamp not timestamp create table if not exists `customers` ( `uid` int(11) ...

jquery - Navigation hover not working -

hi i'm trying out new style navigation. can't seem hover effect working. thought had targeted can't seem working. i'm using 1 li @ moment cause i'm trying out. appreciated. my code <body> <header class="page-header"> <nav class="main-nav" role="navigation" style="position: fixed; top: 0px; width: 100%; border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: rgb(241, 241, 239);"> <div class="wrap"> <div class="menu-category-menu-container"><ul id="menu-category-menu" class="category-nav"><li id="menu-item-13003" class="menu-item menu-item-type-taxonomy menu-item-object-category current-post-ancestor current-menu-parent current-post-parent menu-item-has-children menu-item-13003"><a href="http://thefreshexchangeblog.com/category/lifestyle/">lifestyle</a> <ul class...

build - Gulp task runs much faster without 'return' statement - why is that? -

gulp task formed (without return ) runs faster: gulp.task('less', function () { gulp.src('./less/**/*.less') .pipe(less()) .pipe(gulp.dest('./destination')); }); than same 1 return : gulp.task('less', function () { return gulp.src('./less/**/*.less') .pipe(less()) .pipe(gulp.dest('./destination')); }); so, question gulp task supposed return ? why faster without return , while still generates expected files? after investigation found when return used on gulp task it's not slower @ all, returns correct time took finish task. it felt faster since without return statement returned result completed instantly, task time looked few ms, actual process continued on background , completed silently. so, it's safe it's prefferable use return on tasks have gulp.src() .

r - cbind factor vector with level names -

i create 3 vectors , try combine them 1 table using cbind. third vector factor 3 levels. output: v1 <- c(1,2,3) v2 <- c(4,5,6) v3 <- factor(c('lorem','ipsum','dolor')) cbind(v1,v2,v3) v1 v2 v3 [1,] 1 4 3 [2,] 2 5 2 [3,] 3 6 1 preferred output be: cbind(v1,v2,v3) v1 v2 v3 [1,] 1 4 lorem [2,] 2 5 ipsum [3,] 3 6 dolor is possible level names instead of id display above? not sure why need way. better use data.frame can hold multiple classes. using cbind , matrix , matrix can hold single class. so, if there single non-numeric value, columns transformed 'character' class. cbind(v1, v2, v3=levels(v3)[v3]) # v1 v2 v3 #[1,] "1" "4" "lorem" #[2,] "2" "5" "ipsum" #[3,] "3" "6" "dolor" or cbind(v1, v2, v3=as.character(v3))

openedge - What's the right sintax to search for a X(6) format var in Progress 4gl? -

on statement below have error telling me attribute type not compatible with. consult database properties , attribute format x(6). know right sintax ? p.s. tried = '1', eq 1, eq '1', = "1" , eq "1" for each bd.tablename bd.tablename.attribute = "1" when property/attribute, mean field? if you're talking buffer/table attributes, such type, example, separator should colon, -> : not period (.), unlike other oo languages. if you're talking field, themaddba correct, , should check data type, it's way safer field format. if still have issue, maybe provide more information , can try further.

Python String to hex -

so, i've been banging head against wall long on seems should easy data conversion. writing in python , passing module hex value converted wrapper c type uint_64t. problem getting hex value via python library argparse. when takes in value, example lets use value 0x3f, saves string. if try cast int throws error: "valueerror: invalid literal int() base 10: '0x3f'" if create variable hex = 0x3f however, when print out, gives me appropriate integer value. (which great since i'm creating uint) confused how make conversion string int if cast doesn't work. have seen plenty of examples on turning string hex value letter (in other words take each individual character of ascii string '0x3f' , give hex value) haven't been able find example of situation looking for. apologies if i'm bringing has been answered time , again. try specifying int in base 16: >>> int("0x3f", 16) 63 you use ast.literal_eval , should able...