Posts

Showing posts from May, 2013

How to implement a maintenance mode for Heroku API -

How to implement a maintenance mode for Heroku API - i want utilize maintenance mode on heroku. but api, maintenance mode not seem work. api calls stopped in tracks because there no header 'access-control-allow-origin' present. there no way know if api in maintenance mode—or if it's not responding. is there way utilize heroku maintenance mode when app api? currently, unfortunately not. when set custom maintenance page gets embedded iframe within heroku-served html page. you've identified, cors headers not set api client won't fetch page. see is there way have heroku error/maintenance url served straight without iframe api heroku maintenance maintenance-mode

javascript - Emberjs filtered select collection update -

javascript - Emberjs filtered select collection update - i made jsbin demonstrate problem: http://jsbin.com/pexolude/69/edit explonation: in first select have customers. select's value (customer_value) filters 2nd select's (contactpersons) collection. if select customer, "new contact person" button enabled. on click adds new contact person "dale" double r diner. (in app form , new contact person add together selected customer) the test select "double r diner" add new contact person (dale added, not on double r diner's contact persons list ) change "great northen hotel" go "double r diner" -> dale on list it nice have contact_persons property auto-updated when new element added. shouldnt default behaviour? or have trigger somehow? totally, rule of thumb, @ of properties required in computed property, , if of them create difference in value of computed property (which i'd assume do), should def

jquery ui - enable scrolling on parent while dragging child element -

jquery ui - enable scrolling on parent while dragging child element - here have parent div table consists of 3 sites a,b , c.each site consists of info can dragged other sites.i have done draggable part jquery ui.any way dragging part went well.the height of parent div static 1 scroll property set true.so due this, when drag element parent divs scroll doesnt work , wont allow place dragged element @ right position.i googled , got codes enable scrolling part while dragging dragged element not visible,it goes along scroll.pls seek fiddle u clear thought of meant , pls help me....fiddle drag: function (e) { var ismoving = false; if ((e.pagey - offset.top) <= distance) { ismoving = true; clearinetervals(); inttophandler = setinterval(function () { parentdiv.scrolltop(parentdiv.scrolltop() - step) }, timer); } if (e.pagey >= (offsetheight - distance)) { ismoving = true; clearinetervals(); intbottomhandler = s

javascript - Bind one attribute of an array of ng-options -

javascript - Bind one attribute of an array of ng-options - i have next array: [{code: "af", name: "afghanistan"}, {code: "za", name: "south africa"}, {code: "al", name: "albania"}] i have select , bind ng-model on code attribute of selected object , not whole object. on other hand, select display name (and not code). in addition, if set ng-model code, pre-select name in selection. i tried next (jade) select(ng-model='mycountry', ng-options='country.name country in countries track country.name') here ng-model gets whole object (mycountry = {code: "af", name: "afghanistan"}) , not code (mycountry = "af") is possible that? you can use: <div> <select ng-model="country" ng-options="country.code country.name country in countries"></select> selected country (ng-model): {{country}} </div> country.c

java - JPasswordField not working properly -

java - JPasswordField not working properly - i don't know what's wrong code password not turn dots. please help me. >.< here ui code: private final jpanel contentpanel = new jpanel(); public jpasswordfield password_id; public jformattedtextfield user_id; public jbutton btnaccept; private jformattedtextfield previouslyfocusedtextbox = user_id; public login(final jframe parent, boolean modal) { super(parent, modal); setbounds(100, 100, 469, 428); getcontentpane().setlayout(new borderlayout()); final toolkit toolkit = toolkit.getdefaulttoolkit(); final dimension screensize = toolkit.getscreensize(); final int x = (screensize.width - getwidth()) / 2; final int y = (screensize.height - getheight()) / 2; setlocation(x, y); setresizable(false); flowlayout flow_2 = new flowlayout(0,0,0); final jpanel panel_1 = new jpanel(); panel_1.setbackground(new color(128, 0, 128)); panel_1.setpreferredsize(new dimension(10, 90)

php - How to display more than one result from search -

php - How to display more than one result from search - i trying display results search whatever still shows me 1 , want create link each result product. suggestions? thanks my search_engine.php code include("storescripts/init.php"); //connect db $button = $_get ['submit']; $search = $_get ['search']; if ($search === 'search products'){ echo "please come in value!"; } else { if(strlen($search)<=1) echo "search term short"; else { echo "<br />you searched <b>$search</b> <hr size='1'></br>"; $search_exploded = explode (" ", $search); foreach($search_exploded $search_each) { if($search_each) $construct .="product_name '%$search_each%' or brand '%$search_each%' or category '%$search_each%'"; } $constructs ="select * products $construct limit 100 "; $run = mysql_

javascript - Encrypting with CryptoJS, decrypt with Ruby / AES -

javascript - Encrypting with CryptoJS, decrypt with Ruby / AES - this problem has me knees! i'm trying encrypt info that's going sent ror-application via ajax. i've managed encrypt string in ruby , decrypt in javascript, can't manage reverse. here's js: function decrypt(data, key) { var index = data.indexof('!$'); var iv = data.substr(0, index); var crypttext = data.substr(index + 2); encrypted = {} encrypted.ciphertext = cryptojs.enc.base64.parse(crypttext); var decrypted = cryptojs.aes.decrypt(encrypted, key, { iv: cryptojs.enc.base64.parse(iv) }); homecoming decrypted.tostring(cryptojs.enc.utf8); } function encrypt( data, key ) { enc = cryptojs.aes.encrypt( data, key ); enc_str = cryptojs.enc.base64.stringify(enc.iv) + "!$" + cryptojs.enc.base64.stringify(enc.ciphertext); homecoming enc_str; } // ... var key = 'abcdef123abcdef123abcdef123abcdef123abcdef123';//cryptojs.sha256

ios - tabBarController sending delegate methods to tabs that don't respond to them -

ios - tabBarController sending delegate methods to tabs that don't respond to them - using storyboard have setup application 3 tab bars. when click on 1 of tabs , have singleton datasource class perform action, , switch tab, when singleton finishes fetching info externally tries send current tab causes crash because current tab on not respond specific delegate method have implemented in singleton delegate, , should not implement since there no reason specific tab perform action. here how delegate setup. @class dataholder; @protocol dataholdercontrollerdelegate <nsobject> @required -(void)logout; @optional -(void)friendsquarrydidfinishwithdata; -(void)pendingfriendsquarrydidfinishwithdata; -(void)allusersquarrydidfinishwithdata; -(void)additionalfriendsfoundandadded; -(void)messagequarryfinishedwithdata; -(void)thumbnailquarydidfinishwithdata; -(void)sentrequestusersfoundwithdata; @end @interface dataholder : nsobject; @property (nonatomic,weak) id <dataholderc

Cannot create a Google Compute VM instance -

Cannot create a Google Compute VM instance - i thought relatively straight forward, cannot start google compute engine instance @ all. creating instance through web interface, error after clicking "create" button. the error appears in activity log is: invalid value field 'resource.type': 'https://www.googleapis.com/compute/v1/projects//zones/asia-east1-b/disktypes/pd-standard'. must url valid compute resource of right type. here screen shot of instance settings: any ideas going wrong? have tried different zones , vm sizes. not sure why you're unable create instance, can create straight terminal gcutil. this command should trick: gcutil addinstance --zone=asia-east1-b --image=debian-7-wheezy-v20140606 --machine_type=g1-small bigquery-bi-instance google-compute-engine

javascript - Add to element as divs -

javascript - Add to element as divs - okay, here's code: html: <h2>header</h2> <div id="results1" class="results"> <h1>results 1</h1> </div> js: (function() { var results = document.getelementbyid('results1'); var drink = [ 'rum', 'vodka', 'whiskey', 'beer' ]; })(); i need add together drinks results element divs. just simple for loop iterate on array , , append each item results div . (var = 0 ; < fruit.length; i++) { results.innerhtml += "<div>" + fruit[i] + "</div>"; }; jsfiddle demo javascript jquery html

javascript - How do you manually add a space to an input field in angular -

javascript - How do you manually add a space to an input field in angular - so i've been having hell of time datepicker angular bootstrap. essentially, functions should, new chosen date displayed in input field, doesn't update date directive unless there manual alter field (i.e. add together space end of text). i've tried everything, , thing can think of simulate space character beingness added when form submitted. so question is: when submit button clicked, how add together space @ end? note: cannot utilize jquery. javascript angularjs twitter-bootstrap

collections - Java Lambda re-use Stream -

collections - Java Lambda re-use Stream - i wanted seek out of functionality of lambdas , wanted write filter arraylist , utilize methods of intstream calculate average , maximum of arraylist of numbers my first thought filter arraylist, save stream , utilize methods calculate: arraylist<integer> arr = new arraylist<>(); arr.add(5); arr.add(7); arr.add(11); intstream s = arr.stream().filter(i -> < 10).maptoint(i -> (int)i); int maxbelowten = s.max().getasint(); double avgbelowten = s.average().getasdouble(); system.out.println("maximum below ten: " + maxbelowten); system.out.println("average below ten: " + avgbelowten); however, throws java.lang.illegalstateexception: stream has been operated upon or closed with information, brought work of course, opening 2 streams , filtering twice int maxbelowten = arr.stream().filter(i -> < 10).maptoint(i -> (int) i).max().getasint(); double avgbelowten = arr.stream().filter(i

javascript - Can I have an Angular directive replaced with two elements? -

javascript - Can I have an Angular directive replaced with two elements? - i writing <password> directive contain <input> followed <span> (an icon allowing user show/hide password). possible have angular replace directive element in html these 2 elements , apply attributes exist on directive element <input> element? so: <password ng-model="myvar" ng-change="mytrigger" ng-whatever="mywhatever"></password> would become: <span> <input type="password" ng-model="myvar" ng-change="mytrigger" ng-whatever="mywhatever"/> <span ng-click="togglepasswordvisibility()">show/hide</span> </span> and if user adds other attributes <password> have them applied on <input> . you have manually on element compile: .directive('password', function($compile) { homecoming { restrict: 'e'

scala - Spray/Akka missing implicit -

scala - Spray/Akka missing implicit - myservice.scala:33: not find implicit value parameter eh: spray.routing.exceptionhandler i have run "missing implicit" compilation error using akka, in spray.io code makes http phone call separate back-end server, part of responding http get. code needs import quite lot of spray , akka libraries, it's bit hard figuring whether there may library conflicts causing this, , i'd rather figure how logically trace sort of problem , other cases. the missing implicit encountered on calling runroute(myroute) here's code: import spray.routing._ import akka.actor.actor import akka.actor.actorsystem import spray.http._ import mediatypes._ import akka.io.io import spray.httpx.requestbuilding._ import scala.concurrent.future import spray.can.http import spray.http._ import akka.util.timeout import httpmethods._ import akka.pattern.ask import akka.event.logging import scala.concurrent.duration._ // don't implement our rou

Rename a Role in the Lightswitch -

Rename a Role in the Lightswitch - how rename name of role in securitydata dataworkspace in lightswitch? //lookup role, , rename it, or create 1 if none exist. var rolesquery = this.dataworkspace.securitydata.roles.where(r => r.name.startswith(oldrolenamestring)).execute(); role role = rolesquery.any() ? rolesquery.single() : this.dataworkspace.securitydata.roles.addnew(); role.name = "othername"; an invalidoperationexception thrown states "cannot set value of property 'name' because read-only." so right way then? renaming roles not possible. there's couple reasons this: 1. lightswitch bases role implementation on asp.net's membership/role scheme doesn't provide api rename roles. 2. name property cannot updated because primary key , lightswitch doesn't allow changing values of primary keys. instead, you'd need delete role , add together new 1 replace it. visual-studio-lightswitch

java - Hibernate custom type access result set -

java - Hibernate custom type access result set - my class implements hibernate custom user type. implements usertype, parameterizedtype. public object nullsafeget(resultset resultset, string[] params, object owner) throws sqlexception { i need access status fields via resultset parameter. have 2 ways of access. by giving coloumn number resultset.getstring(17); specifing colounm name. hiberbate returns resultset.getstring("status13_51_0_"); //status13_51_0_ hibernate generates query own alias , can access alias not column name. the problem , class called different places need access each time status column. as incoming query different receiving column number , generated field alias different. what approach, solution can suggest me overcome situation ? you should phone call resultset.getstring method on appropriate element param array. there no need utilize hardcoded aliases. e.g. resultset.getstring(params[0]); simple illustration m

c# - Why is the regular expression trying to make submatch? -

c# - Why is the regular expression trying to make submatch? - i newbie regex please bear me if trivial question. next this. want see if input has next pattern: <any number of spaces><one or more of alphanumeric character>;<any number of possible spaces> if input has above look homecoming matches. the regular look have follows: \s*\w+\s*?;\s* when regex.ismatch(input, pattern, regexoptions.ignorecase) even if have valid input "a;" or " a;" end getting false. when examine using regex tool, seems matches whole thing , tries find submatch sec \s* 1 time again @ point says no sub match. can explain why getting false? the next work according needs. \s*\w+;\s* example: console.writeline(regex.ismatch("a;", @"\s*\w+;\s*")); // true console.writeline(regex.ismatch(" a;", @"\s*\w+;\s*")); // true console.writeline(regex.ismatch("a; ", @"\s*

python - convert xml format into a formatted text file for metadata of Quickbird -

python - convert xml format into a formatted text file for metadata of Quickbird - i have metadata of quickbird in format xml: <?xml version="1.0" encoding="utf-8" standalone="yes"?> <isd> <imd> <version>aa</version> <generationtime>2008-01-04t18:36:17.000000z</generationtime> <productorderid>005708443040_01_p001</productorderid> <productcatalogid>901001001e9ed900</productcatalogid> </imd> </isd> i convert xml text format following: version = "aa"; generationtime = 2008-01-04t18:36:17.000000z; productorderid = "005708443040_01_p001"; productcatalogid = "901001001e9ed900"; childcatalogid = "202001001e9ed800"; i wrote python code following, didn't provide result expected from xml.dom import minidom xmldoc = minidom.parse("image.xml") isd = xmldoc.getelementsbytagnam

javascript - JQuery UI Sortable - Nested Sortable Divs connectWith -

javascript - JQuery UI Sortable - Nested Sortable Divs connectWith - i'm using jquery ui sortable seek have grouping of sortable divs, potentially divs have sortable applied them. , these sortables should able move items between each other. i'm able items in parent sortable div children sortable divs, can't items children parents. is possible? <div id="block-container"> <div class="block">block1</div> <div class="sub-wrapper"> <div class="block-sub-container"> <div class="block"></div> <div class="block"></div> </div> </div> </div> $('#block-container').sortable({connectwith: ".block-sub-container"}); $('.block-sub-container').sortable({connectwith: "#block-container"}); here i'm working with: http://jsfiddle.net/5pm24/ you can see outside items can drag

javascript - Using PsExec with spawning a child process results in truncated stdout -

javascript - Using PsExec with spawning a child process results in truncated stdout - my goal able execute command on remote machine , total stdout response command run. getting truncated result. when run same command through command prompt, total output command run. here code: var process = spawn('psexec.exe', ['\\\\servername', 'ipconfig']); var doonce = true; process.stdout.on('data', function (data) { log.info('stdout: ' + data.tostring()); if(doonce){ doonce = false; process.stdin.write('ipconfig');} }); process.stderr.on('data', function (data) { log.info('stderr: ' + data.tostring()); }); process.on('exit', function (code) { log.info('child process exited code ' + code); }); when executed next console output. can tell, of ipconfig has been truncated. if command such netstat, of results before tr

python - Crawl URL file to get final destination URL after redirects? -

python - Crawl URL file to get final destination URL after redirects? - i have text file follows http://url.com/r/gfdgdfg http://url.com/r/a32512f http://url.com/r/awdre25 http://url.com/r/agbfd35 http://url.com/r/nfg4622 is there way utilize python (trying simple script on linux box) crawl each url (load it) , final url? each url/link redirect , want url after redirects. import requests urls = '''http://url.com/r/gfdgdfg http://url.com/r/a32512f http://url.com/r/awdre25 http://url.com/r/agbfd35 http://url.com/r/nfg4622''' x in urls.splitlines(): r = requests.get(x) print x, '=>', r.url result: http://url.com/r/gfdgdfg => http://lyrics.url.com http://url.com/r/a32512f => http://lyrics.url.com http://url.com/r/awdre25 => http://lyrics.url.com http://url.com/r/agbfd35 => http://lyrics.url.com http://url.com/r/nfg4622 => http://lyrics.url.com python

semaphore - In Producer/Consumer, why does switching the order of up(mutex) and up(fill) result in deadlock? -

semaphore - In Producer/Consumer, why does switching the order of up(mutex) and up(fill) result in deadlock? - let's utilize code on wikipedia page example. semaphore mutex = 1; semaphore fillcount = 0; semaphore emptycount = buffer_size; procedure producer() { while (true) { item = produceitem(); down(emptycount); down(mutex); putitemintobuffer(item); up(mutex); up(fillcount); } } procedure consumer() { while (true) { down(fillcount); down(mutex); item = removeitemfrombuffer(); up(mutex); up(emptycount); consumeitem(item); } } why swapping position of up(mutex) , up(fillcount) in producer function guarantee deadlock? i'm trying come instance, can't seem find any. deadlock semaphore producer-consumer

model view controller - Why do we need an Spring MVC or Struts framework if we intend to proceed with single page apps -

model view controller - Why do we need an Spring MVC or Struts framework if we intend to proceed with single page apps - i have design problem @ hand. traditionally had been developing spring mvc/struts/jsf applications either rest/soap service serving data. now have html5 , other javascript frameworks. in light, still need create spring mvc applications such (assume info served restful service) if go ahead pure html5, css ui (with ajax calls restful services), possible issues may into? approach have security holes beingness prone cross site scripting? is approach start off with? approach called single page app? you still need serve single page app somewhere, along w images , css files. spring mvc servlet, or whatever. i'd spring info rest servlet creates restful hateoas endpoints you. it's easier if spa , rest service on same domain, don't have worry cross-domain restrictions. they still vulnerable xss, scheme unless take counter-measures. sp

linux - how to print just filename without using __FILE__ in C -

linux - how to print just filename without using __FILE__ in C - this question has reply here: __file__ macro manipulation handling @ compile time 6 answers i want print filename beingness used in project. if utilize __file__ , prints entire path along file name long in case , disturbs log indents. can please help how can print file name using mutual parameter across project. in c code, might utilize instead of __file__ look basename(__file__) ; however, has disadvantage of calling basename @ every occurrence. alternatively, compile path/foo.c command like gcc -wall -c -g -dbase_file=\"foo\" path/foo.c (you have generic make rule giving that) then utilize base_file instead of __file__ in code. with gcc, utilize __base_file__ instead of __file__ c linux

html - CSS-only nav menu - need root element to stay darkened when open -

html - CSS-only nav menu - need root element to stay darkened when open - i have css-only navigation menu i'm trying finish up. finish except 1 thing: when user hovers on element submenu navigates downwards submenu root element goes white. root navigation element remain darkened when submenu open. below codepen implementation far: http://codepen.io/anon/pen/ijjyb can help me finish this? change selector (line 51): #navmenu > ul li.has-sub > a.active, #navmenu > ul li.has-sub > a:hover to this: #navmenu > ul li.has-sub > a.active, #navmenu > ul li.has-sub:hover > this results in :hover action still beingness active when user in submenu not children of <a> - <li> -tag html css navbar

html5 - Javascript setInterval works but not infinite loop -

html5 - Javascript setInterval works but not infinite loop - i don't understand why infinite loop not work uncommenting function phone call works. <body> <canvas id="mycanvas"style="border:2px solid black;" width="1600" height="900"> browser not back upwards html5 canvas tag. </canvas> <script> var c = document.getelementbyid ("mycanvas").getcontext ("2d"); var boxsize = 25; var numboxes = 1; var x = 1000; var dx = 1; var y = 100; var dy = 1; var = 0.01; var da = 0.1; var size = 20; var w = c.canvas.width; var h = c.canvas.height; //function testing () { while (true) { c.clearrect (0, 0, w, h); x = x + 1; y = y + 1; = + 0.1; x = x + dx; y = y + dy; if (x < size / 2 || x + (size / 2) > w) { dx = -dx; da = -da; } if (y < size /

ruby on rails - Can't find DOM element in jQuery -

ruby on rails - Can't find DOM element in jQuery - i'm going insane. take @ fiddle: http://jsfiddle.net/ndh9g/4/ it's relevant code rails site i'm working on (for fantasy football). every time "type" select changed, want reset "direction" select "select" cutting downwards on wonkiness happens if type changed after fields filled in. except can't. no matter do, cannot access stupid "direction" select. if look, you'll see these 2 lines: $('div', location).next('.player-trade-fields').hide(); $('div', location).next('.terms-field').show(); and coming shock no one: work should without issue. when seek access "direction" select @ same dom level 2 fields: $('div', location).next('.trade-direction') i nothing. have alert in there show me if value beingness returned , absolutely nil returns value. don't it. don't how jquery not find it. i&

php - PostgreSQL for Windows -

php - PostgreSQL for Windows - basically used create web systems php , mysql, wanted larn new database system, chose postgresql. uninstalled xampp , installed postgresql-9.3.4-2-windows-x64 pgadmin iii. question 1: how can run php files using postgre assuming im creating new scheme scratch. set php file? still need install xampp again? or set files within folder in postgresql installation folders? question 2: how can manage databases using pgadmin instead of phppgadmin or browser based postgresql database manager. postgresql database, set php files in directory apache can serve, , configure apache accordingly. can start here as how utilize pgadmin, rtm. php postgresql psql

node.js - openstreet map using node-geocoder sending garbage value -

node.js - openstreet map using node-geocoder sending garbage value - geocoder module nail open street map seems returning garbage value below url , request , response headers url parameters {"host":"nominatim.openstreetmap.org","path":"/search?format=json&addressdetails=1&q=adyar"} response headers {"date":"fri, 20 jun 2014 06:48:57 gmt","server":"apache/2.2.22 (ubuntu)","content-location":"reverse.php","vary":"negotiate,accept","tcn":"choice","x-powered-by":"php/5.3.10-1ubuntu3.11","access-control-allow-methods":"options,get","access-control-max-age":"8640000","access-control-allow-origin":"*","connection":"close","transfer-encoding":"chunked","content-type":"application/json; ch

Error using Vim substitute method -

Error using Vim substitute method - i using substitute() method script vim code folds different. code in ~/.vimrc follows: function! foldtext() allow width = winwidth(0) - &foldcolumn - (&number ? 4 : 0) allow first_line = getline(v:foldstart) . " ..." allow edited_line = subsitute(first_line, "{ \.\.\.", "{ ... }", "") allow expansion_string = repeat(" ", width) homecoming edited_line . expansion_string endfunction set foldtext=foldtext() the problem doesn’t work, each fold: 0------------------------------------------------------------------------------- if take out edited_line , homecoming first_line . expansion_text first part works: class whatever { ... but purely aesthetic reasons i’d folds start brace show brace so: class whatever { ... } i’ve not used vimscript much, , pinched this site, expect i’m missing basic. thanks! the 0 comes typo in function name. when vim

django - South Data Migration Fails with ValueError when Function Tries to Access a Table Through a Foreign Key -

django - South Data Migration Fails with ValueError when Function Tries to Access a Table Through a Foreign Key - my info migration references function takes object of current model parameter, , tries create object table (in same app) through foreign key. creation of object fails value error stating object passed argument not instance of expected class (although is). seems there no link between 2 tables. here info migration. ranking in orm.ranking.objects.all(): find_matching_domains(ranking) find_matching_domains declared in app , imported in info migration. fails when trying create dictionary object. dico = categorydict(category=ranking.category, key="url_dict", value=url_dict) with next error: file "...", line 175, in save_url_dict value=url_dict) file ".../lib/python2.6/site-packages/django/db/models/base.py", line 355, in __init__ setattr(self, field.name, rel_obj) f

compiler errors - compiling code for 'iWave' Surface simulation by Jerry Tessendorf -

compiler errors - compiling code for 'iWave' Surface simulation by Jerry Tessendorf - i found code in paper written simulation of fluid surfaces http://www-evasion.imag.fr/people/fabrice.neyret/images/fluids-nuages/waves/jonathan/articlescg/simulating-ocean-water-01.pdf but when seek run code in dev c++ bunch of compiler errors "stray '\146' in program" the compiler errors fixed, due wrong formatted ' pdf. the code compiles without error, when runs nil happens @ all. could help me? code shown below #include <cmath> #ifdef __apple__ #include <glut/glut.h> #else #include <gl/gl.h> // opengl itself. #include <gl/glu.h> // glu back upwards library. #include <gl/glut.h> // glut back upwards library. #endif #include <iostream> using namespace std; int iwidth, iheight, size; float *display_map; float *obstruction; float *source; float *height; float *previous_height; float *vertical_derivative; float sc

image - Java display base 64 byte array in jsp -

image - Java display base 64 byte array in jsp - i have class called graphic creates new bufferedimage, draws new graphics2d , returns image base64 encoded string: bufferedimage image = new bufferedimage(width, height, bufferedimage.type_int_argb); graphics2d g2 = image.creategraphics(); g2.setrenderinghint(renderinghints.key_antialiasing, renderinghints.value_antialias_on); // draw background g2.setcolor(color.decode("#ffffff")); g2.fillrect(0, 0, grafikbreite, grafikhoehe); g2.setcolor(color.decode("#000000")); // draw rectangles , other stuff... drawstuff(g2); bytearrayoutputstream baos = new bytearrayoutputstream(); byte[] imageinbyte = {}; seek { jpegimageencoder j = new jpegimageencoderimpl(baos); j.encode(image); imageinbyte = baos.tobytearray(); baos.close(); } grab (ioexception e) { e.printstacktrace(); } homecoming javax.xml.bind.datatypeconverter.printbase64binary(imageinbyte); in jsp-file want display image using, graphic crea

c# - Binding a collection not working -

c# - Binding a collection not working - i'm working on windows phone app has listbox itemtemplate. i'm trying bind observablecollection of viewmodel listbox nil beingness shown. the xaml of page looks this: ... <phone:phoneapplicationpage.resources> <datatemplate x:key="myitemtemplate"> <grid height="auto" verticalalignment="top" width="auto"> <grid.rowdefinitions> <rowdefinition height="auto" /> <rowdefinition height="*" /> </grid.rowdefinitions> <textblock text="{binding path=name}" style="{staticresource phonetextlargestyle}" grid.row="0"/> <textblock text="{binding path=description}" style="{staticresource phonetextsubtlestyle}"

c# - try{} catch(Exception e){} VS try{} catch(Exception e){ throw;} - What the difference? -

c# - try{} catch(Exception e){} VS try{} catch(Exception e){ throw;} - What the difference? - this question has reply here: the difference between try/catch/throw , try/catch(e)/throw e 4 answers i got here next code anti-pattern. right? try { //something } catch(exception e) { //something } and why improve use try { //something } catch(exception e) { //something throw; } ? i got sec variant using re-throwing exception (logging example), if need re-throw same exception why not utilize next code? try { //something } catch(exception e) { //something throw e; } this re-throw same exception , maintain stack trace. create debugging easier. catch(exception e) { //something throw; } this rethrow exception, you'll lose stack trace. catch(exception e) { //something throw e; } this silently swallow exception. want when yo

Visual Studio 2010 insert copy of resource with condition disappears after save -

Visual Studio 2010 insert copy of resource with condition disappears after save - in visual studio 2010 trying create re-create of dialog template resource status in order have 2 different versions of dialog in 2 different build configurations. i have header file .rc file includes contains this: #ifdef build_config1 #define res_define_1 #else #define res_define_2 #endif so, go resource view in visual studio, right-click on dialog template , take "insert copy..." insert resource re-create dialog pops , set condition: res_define_2 , click ok. at point, looks good. see both original dialog , re-create status in brackets [res_define_2]. save , i'm go. here problem seems be. our version command scheme ancient, , based on locking single files. in previous versions of visual studio, we've archived *.rc files, , made sure resources up-to-date deleting *.aps files resource editor creates. whenever needed edit resource, visual studio regenerate

.net - Can I create a route which redirects "/" to another folder with static HTML files in it? -

.net - Can I create a route which redirects "/" to another folder with static HTML files in it? - i'm using webapi, , have route setup "api/{controller}/{id}". have next folder construction in project: \static\index.html \static\pagey.html i want web site's users able go to: http://localhost/index.html http://localhost/pagey.html is should avoid doing in first place? if no, there way create such route definition? if you're running on owin, can without touching web api routing. should able utilize microsoft.owin.staticfiles middleware this. illustration setup class: public class startup { public void configuration(iappbuilder app) { var webapiconfig = new httpconfiguration(); // web api routing setup here... app.usewebapi(config); var assemblypath = assembly.getexecutingassembly().location; var assemblyfolder = path.getdirectoryname(assemblypath); var staticfolder

javascript - Regex converting & to & -

javascript - Regex converting & to &amp; - i developing little character encoder generator user input text , on click of button, outputs encoded version. i've defined object of characters need encoded so: map = { '©' : '&copy;', '&' : '&amp;' }, and here loop gets values map , replaces them: object.keys(map).foreach(function (ico) { var icoe = ico.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); raw = raw.replace( new regexp(icoe, 'g'), map[ico] ); }); i them outputting result textarea. works fine, problem i'm facing this. © replaced &copy; & symbol @ origin of converted &amp; ends beingness &amp;copy; . i see why happening i'm not sure how go ensuring & not replaced within character encoded strings. here jsfiddle live preview of mean: http://jsfiddle.net/4m3nw/1/ any help much appreciated prelude: apart regex, thought worth cons

javascript - How to search in rad file explorer for current folder including sub folders -

javascript - How to search in rad file explorer for current folder including sub folders - i want utilize filter in rad file explorer needs search current directory including sub folders items.currently can search in main folder not sub folders items using built in filter box.some body help me please that not available oob because cause performance issues. nevertheless, can create such functionality yourself: implement custom filesystemcontentprovider, overriding resolvedirectoryastree() , resolvedirectory() methods in way, described in help article: http://www.telerik.com/help/aspnet-ajax/fileexplorer-custom-filebrowsercontentprovider.html call recursively resolvedirectoryastree() , resolvedirectory() methods content provider in order take references listed files , folders (e.g. base.resolvedirectoryastree()). 1 time gather needed info 1 place can create search through items in it. despite of accuracy of such implementation, note information-gathering slow proces

php - Fatal Error - 'Mongo' class not found -

php - Fatal Error - 'Mongo' class not found - i'm trying execute this: <?php // connect $m = new mongo(); ?> but next error: fatal error: class 'mongo' not found in c:\wamp\www..... info: php: 5.38 mongodb: mongodb-win32-i386-2.0.2 mongodb php driver: mongo-1.1.4-php5.3vc6ts wampserver: 2.2 os: windows 7 enterprise sp1 i've followed mongodb installation fine (incl. adding dll ext & php.ini), i've started mongod.exe , wamp running. what imply missing/incorrect? edit: i have got running on windows 7 machine (windows 7 profressional). got me curious. windows 7 enterprise sp1 machine has same http.conf , php.ini , c:\wamp\bin\mongodb contents (therefore dbs exact same) , exact same batch file start mongod.exe win7 professional machine. but still, can on win7 enterprise sp1 machine connect via command line. win7 professional machine's phpinfo() contains: win7 enterprise sp1 machine doesn't contain

java - Remove string between characters -

java - Remove string between characters - i remove everything(for chars {}$* \w+ "" ) between ; , # : for illustration remove string: input: or(and(ca18*cb18);m10#;abzz/kld // remove ;m10# output: or(and(ca18*cb18);abzz/kld i tried regular expression: ^[;]\w+([a-za-z0-9])[#] however, not seem work recommendations? solution updated question be: // actual regex ;[{}$*\w"']+?#, escaping needed java: input.replaceall(";[{}$*\\w\"']+?#", ""); where can update character set between [] match actual requirements find more border cases.. if decided need black-list of characters instead, utilize look negated character set ( ^ within [], not confuse ^ @ start of regex, denotes origin of string): ;[^;#]+?# java regex

sql - Query with multiple INNER JOINS, difficulties in avoiding duplicates -

sql - Query with multiple INNER JOINS, difficulties in avoiding duplicates - i have access bd main table ('principale') having many-to-many connection ('tabregisti'), bring together table between them ('tabregisti_unione'). i've form 'principale' there's search button that, after user click, creates query listbox in form. query i'm using following: select principale.id, principale.codicedvd, principale.cofanetto, principale.titolodvd, tabregisti.nomeregista, tabregisti.cognomeregista, tabcategoria.categoria, principale.durata, principale.attoriprincipali, principale.produzione, principale.annodvd, principale.annofilm, principale.dataacq, principale.ubicazione tabregisti inner bring together (tabcategoria inner bring together ((principale inner bring together tabubicazione on principale.ubicazione = tabubicazione.ubicazione) inner bri

javascript - Binding real number values to Grails domain attributes (values sent by Dojo widgets) -

javascript - Binding real number values to Grails domain attributes (values sent by Dojo widgets) - i using dojo 1.9 grails 2.3.9. the dojo numbertextbox widget - utilize in forms - sets real number values (e.g.: 12.56) in fixed format (the javascript base of operations format) html form input fields (but displays/edits them according browser locale, user sees formatted numbers). grails on other hand expects input fields formatted according browser locale. this results in conversion mismatch , effect grails loses decimal places when browser locale not english language , saves record incorrectly database. i trying override value conversion in grails implementing custom valueconverter , registering in application context. the request sent browser contains real value correctly ("12.45") the main problem converter doesn't seem used @ all. how register override defaut double info conversion? the converter: package gefc.dojo.binding import org.gr

machine learning - simple perceptron model and XOR -

machine learning - simple perceptron model and XOR - sorry maintain asking here. study hard ready reply questions too! many papers , articles claim there no restriction on choosing activation functions mlp. it seems matter 1 fits given condition. and articles mathematically proven simple perceptron can not solve xor problem. i know simple perceptron model used utilize step function activation function. but if doesn't matter activation function use, using f(x)=1 if |x-a|<b f(x)=0 if |x-a|>b as activation function works on xor problem. (for 2input 1output no hidden layer perceptron model) i know using artificial functions not learning model. if works anyway, why articles proven doesn't work? does article means simple perceptron model 1 using step function? or activation function simple perceptron has step function unlike mlp? or wrong? in general, problem non-differentiable activation functions (like 1 proposed) cannot used back-propaga

How to convert a big csv file into json array quickly in java -

How to convert a big csv file into json array quickly in java - i want convert big csv file 20000 50000 record file json array takes 1 min convert in there way accomplish in less 5 sec. resourcebundle rb = resourcebundle.getbundle("settings"); string path = rb.getstring("fileandfolder.path"); system.out.println(path + "ssdd"); string csvpath = request.getparameter("dp") != null ? request .getparameter("dp").tostring() : ""; string orname = path + csvpath; file file = new file(orname); filereader fin = new filereader(file); //read file 1 1 bufferedreader bi = new bufferedreader(fin); int res; string csv = ""; while ((res = fin.read()) != -1) { csv = csv + ((char) res); //converted int char , stored in csv } long start3 = system.nanotime(); jsonarray array = cdl.tojsonarray

Dimen attributes not working in deutsch language android -

Dimen attributes not working in deutsch language android - i using checkbox , add together padding dimen value <dimen name="padding_checkbox">25dp</dimen> i have created v-17 folder big device , set <dimen name="padding_checkbox">5dp</dimen> now i'm testing app on nexus in english, it's returning expected result, when alter language of device , set deutsch(german), checkbox padding gets big, tried checking padding value with int px = getresources().getdimensionpixelsize(r.dimen.padding_checkbox); and 7 in english language , 33 in deutsch(german), cannot understand why happening. i think have mentioned <dimen name="padding_checkbox">25dp</dimen> in values-de why happening(may be).try remove it, if exists. android

cordova - Adding plugins to Phonegap doesn't work -

cordova - Adding plugins to Phonegap doesn't work - simple problem - when add together plugin fresh phonegap project, says adds list shows none installed. i've reinstalled phonegap, no joy. plugin folder gets created , has plugin files. started on project before had worked. installed plugman , had same problem. try cordova command: cordova plugin add together https://git-wip_us.apache.org/repos/asf/cordova-plugin-device.git cordova plugin ls cordova phonegap-plugins

ruby on rails 4 - Creating a mutual friends list -

ruby on rails 4 - Creating a mutual friends list - i've been through treebook tutorial on treehouse , i've been trying enhance it. i want add together list of mutual friends on profile_page shows friends have in mutual user. i can write if statement show profile_name of mutual users. e.g. <% if current_user.friends.include?(friend) , @user.friends.include?(friend) %> <%= friend.profile_name %> <% end %> but i'd write block go through , show other information. how create query in profiles controller can utilize in block? so want like: def common_friends friends.where(friends: [friend1, friend2]) end this way querying friends friend list includes both friend1 , friend2. ruby-on-rails-4

regex - Named Entity Recognition with Regular Expression: NLTK -

regex - Named Entity Recognition with Regular Expression: NLTK - i have been playing nltk toolkit. come across problem lot , searched solution online got satisfying answer. putting query here. many times ner doesn't tag consecutive nnps 1 ne. think editing ner utilize regexptagger can improve ner. example: input: barack obama great person. output: tree('s', [tree('person', [('barack', 'nnp')]), tree('organization', [('obama', 'nnp')]), ('is', 'vbz'), ('a', 'dt'), ('great', 'jj'), ('person', 'nn'), ('.', '.')]) where input: former vice president dick cheney told conservative radio host laura ingraham "was honored" compared darth vader while in office. output: tree('s', [('former', 'jj'), ('vice', 'nnp'), ('president', 'nnp'), tree('ne

php - wordpress permalink getting the previous clicked link -

php - wordpress permalink getting the previous clicked link - i have displayed title selected category. , it's anchor tag, permalink not working. problem here? it's old link might somewhere clicked . not working exact category. <a class="heading-link" href="<?php the_permalink(); ?>"> <?php query_posts('cat=4&showposts=1'); if (have_posts()) : while (have_posts()) : the_post(); the_title(); endwhile; endif; wp_reset_query(); ?> </a> place <a> tag within loop <?php query_posts('cat=4&showposts=1'); if (have_posts()) : while (have_posts()) : the_post(); ?> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <?php endwhile; endif; wp_reset_query(); ?> ph

python - Pandas dataframe with multiindex column - merge levels -

python - Pandas dataframe with multiindex column - merge levels - i have dataframe, grouped , multiindex columns below: import pandas pd codes = ["one","two","three"]; colours = ["black", "white"]; textures = ["soft", "hard"]; n= 100 # length of dataframe df = pd.dataframe({ 'id' : range(1,n+1), 'weeks_elapsed' : [random.choice(range(1,25)) in range(1,n+1)], 'code' : [random.choice(codes) in range(1,n+1)], 'colour': [random.choice(colours) in range(1,n+1)], 'texture': [random.choice(textures) in range(1,n+1)], 'size': [random.randint(1,100) in range(1,n+1)], 'scaled_size': [random.randint(100,1000) in range(1,n+1)] }, columns= ['id', 'weeks_elapsed', 'code','colour', 'texture',

C++ about generic initialization in templates -

C++ about generic initialization in templates - i writing generic function below. template<class iterator, class t> void foo(iterator first, iterator last) { t a; cout << << endl; // iterators } typedef vector<double>::iterator dblptr; vector<double> values; foo< dblptr, int>(); this functions prints out undefined value variable a , while if alter initialization into /// t = t() cout << << endl; // iterators i can see initialized value 0 expecting. if phone call t a variable initialized default value, if phone call t = t() believe due optimization re-create constructor should called value of t() still default one. i cannot understand difference behind these 2 lines , reason why happens? first of all, default initiaization of built-in types such int leaves them uninitialized. value initialization leaves them zero-initialized. example this default initialization: t a;

sql - Oracle Procedure: Creating dynamic WHERE clause -

sql - Oracle Procedure: Creating dynamic WHERE clause - i creating dynamic clause, its' reporting error(40,51): pl/sql: ora-00905: missing keyword @ column_2 in ('x','y','z') , error remains other operators well. select * test_table column_1 = <some_value> , (case column_2 when 'a' column_2 in ('x','y','z') column_3 in (1, 2) when 'b' column_2 in ('p', 'q', 'r') column_3 in (2, 3) else column_2 = 'x' column_3 = 1 end case); also need add together status passed in parameters in not null, this where column_1 = <some_value> if (param_value <> null) column_2 = param_value end if please suggest how can accomplish desire. you can't dynamically "attach" in clauses that, there few different ways this: where column_1

compatibility - android best practice for supporting multiple screens -

compatibility - android best practice for supporting multiple screens - given: starting api level 13 (android 3.2), screen sizes (small,normal,large,xlarge) deprecated in favor of using swdp qualifier. recommended applications meant run on android 3.2 or higher should using these newer qualifiers. http://developer.android.com/guide/practices/screens_support.html then: what best practice maintaining compatability api 7+ without making problem more complicated using both techniques @ same time? to clarify: when creating resource folders alternate layouts, dimensions,values, etc, requirement of supporting api 7+, should utilize deprecated qualifiers (small, normal, large, xlarge) or new qualifiers (sw600dp, sw800dp etc) or both @ same time? update: found similar question accepted reply suggested using older abstract size bin qualifiers: http://stackoverflow.com/a/15113877 use layout aliases. quotation official documentation: "the smallest-width qualifier