Posts

Showing posts from March, 2010

javascript - function prototype inheritance with new keyword -

i making sure understood javascript's new , prototype keywords correctly simple code put not behaving expect. var classa = function() { return { shout: function() { alert("i can shout"); } }; }; classa.prototype.shoutlouder = function() { alert("i can shout"); }; var instance = new classa(); instance.shout(); // why not available? instance.shoutlouder(); when instance variable attempts invoke shoutlouder it's failing "uncaught typeerror: instance.shoutlouder not function" . but, in mozilla docs , says when using new create object: a new object created, inheriting foo.prototype. where wrong in understanding? here jsbin above code-snippit. you're losing access function's (class') prototype object because you're returning new object out of function: var classa = function() { return { shout: function() { alert("i can shout"...

javascript - Countdown and bootstrap progress bar "bump" -

i'm working on little "web app" quiz. each slide has got amount of time answered (or 0 infinite time). i find js here countdown: function countdown(options) { var timer, instance = this, seconds = options.seconds || 10, updatestatus = options.onupdatestatus || function () {}, counterend = options.oncounterend || function () {}; function decrementcounter() { updatestatus(seconds); if (seconds === 0) { counterend(); instance.stop(); } seconds--; } this.start = function () { clearinterval(timer); timer = 0; seconds = options.seconds; timer = setinterval(decrementcounter, 1000); }; this.stop = function () { clearinterval(timer)...

javascript - how to keep resolving Q promises when polling -

i'm trying poll endpoint , use q resolve request. understand can't q, once promise resolved it's done. is there way can approach using q along polling? my setup like: class poller { poll() { const deferred = q.defer(); const promise = $.ajax({ //stuff }); promise.done((resp) => { // resolves once, how can keep resolving // on future xhr calls? deferred.resolve(resp); }); promise.always(() => { settimeout(() => { this.poll.call(this); }, 5000) }) return deferred.promise; } } const poller = new poller(); poller.poll().then((resp) => { // keep trigging updates polling }) the whole point of promise can resolved once. structure looking event .

Move Camera in UnityScript 2d in C# -

i have started programming unity 2d, , have faced 1 large problem: how move camera? script attached object "player". want move player. thanks! /* */ using unityengine; using system.collections; public class playercontroller : monobehaviour { public float speed = 10; //float speed public string haxis = "horizontal"; void start () { //empty } void fixedupdate () { if (input.getaxis (haxis) < 0) //left { vector3 newscale = transform.localscale; newscale.y = 1.0f; newscale.x = 1.0f; transform.localscale = newscale; } else if (input.getaxis (haxis) > 0) //right { vector3 newscale =transform.localscale; newscale.x = 1.0f; transform.localscale = newscale; } //position transformation transform.position = transform.position + transform.right * input.geta...

JWT and server side token storage -

every article i've read vouching advantages of jwt state 1 of these advantages ability auth system distributed across multiple servers. i.e . aren't relying on central repository of user auth details lookup on every request. however when comes implementation, i've read in many places added security shouldn't rely on jwt signature verification itself, , should maintain list of black or white list tokens generated server. doesn't defeat advantage i've listed above, list of tokens need stored centrally servers can access , require lookup on each request? how have people implemented on end? you making points in question. make sense store oauth token @ central location in order make easier implement signout/revoke functionality. if relied on token signature couldn't have possibly implemented such feature. suppose user wanted revoke access token. in case if didn't have central location/datastore tokens have invalidated , relied on token sig...

spring - SpringSecurity - Concurrent Session does not work -

i implementing control of concurrent session spring security. but when login in system chrome user , after on firefox same user, not display error message. no exception in console. my web.xml : <!-- ... --> <listener> <listener-class> org.springframework.security.web.session.httpsessioneventpublisher </listener-class> </listener> <!-- .... --> my security.xml : <-- .... --> <security:http auto-config="true" use-expressions="true"> <security:intercept-url pattern="/**" access="isauthenticated()" /> <security:form-login login-page="/login" default-target-url="/home" authentication-failure-url="/login?logout=true" authentication-success-handler-ref="authenticationsuccesshandler" authentication-failure-handler-ref="authenticationfail...

linux - wkhtmltopdf doesn't show desktop size page in pdf -

i have been trying set wkthmltopdf convert html pdf documents on-the-fly on linux web server. i've looked around solutions around default 800x600 issue , found this: /usr/bin/xvfb-run --server-args="-screen 0, 1024x768x24" wkhtmltopdf --use-xserver http://domain.com /home/location/apps/test1.pdf however, still gives resulting pdf width of 800. missing? i've tried run xvfb-run ssh command line , works flawlessly. creates pdf normal output.. it's width not being recognized... just guess, might need set of quotes around "0, 1024x768x24' it's considered single argument after being passed on. this: /usr/bin/xvfb-run --server-args="-screen \"0, 1024x768x24\"" wkhtmltopdf --use-xserver http://domain.com /home/location/apps/test1.pdf they escaped \ xvfb-run command not consider them argument delimiters, rather passes them on wkhtmltopdf. (i don't know xvfb-run, assume in turn building wkhtmltopdf command line....

sql - Updating table with child table values -

i have 2 table: crm_inquiries , ics_subscribers . crm_inquiries has primary key inquiryid , foreign key, subid associate table ics_subscribers fname , lname . ics_subscribers has primary key subid , columns subfirstname , sublastname . need run query retrieve crm_inquiry rows , update fname , lname values subfirstname , sublastname in ics_subscriber table. hope makes sense.. i wrote script accomplish wondering if there better way it. create table #inq( inquiryid int, subid int ) insert #inq select distinct inquiryid, subid crm_inquiries lname = 'poe' , subid not null declare @totalcount int select @totalcount = count(*) #inq print @totalcount while(@totalcount > 0) begin declare @subid varchar(250) declare @inquiryid int select top 1 @subid = subid, @inquiryid = inquiryid #inq print 'subid = ' + @subid print 'inquiryid= ' + cast(@inquiryid varchar(max)) update crm_inquiries set fname = (select subfirstname ics_subscribers subid =...

asp.net - registerclientscriptblock on javascript callback -

i have javascript function checks lat long , runs on page load. calls page method lat long. in page method, use registerclientscriptblock set bunch of variables, , return string of javascript display map uses variables. map loads, error variables expecting undefined. <script type="text/javascript"> function check() { if (navigator.geolocation) { var panelprog = $get('progress'); panelprog.style.display = ''; var panelprog = $get('map'); panelprog.style.display = 'none'; navigator.geolocation.getcurrentposition(function (position) { // access them accordingly pagemethods.setsession(position.coords.latitude, position.coords.longitude, callback); }); } } function callback(result) { eval(result); } </script> [webmethod] public stati...

wpf - Label with static text and binding -

i trying label show specific text while being bound variable in vb.net code. can make binding cant add static text. what have far: <label x:name="testlabel" content="{binding path=row, stringformat='row #{0}'}" horizontalalignment="left" height="35" margin="203,21,0,0" verticalalignment="top" width="83" fontsize="18"> with public class row implements inotifypropertychanged private _row byte public property row() byte return _row end set(byval value byte) _row = value onpropertychanged(new propertychangedeventargs("row")) end set end property public event propertychanged propertychangedeventhandler implements inotifyproperty...

wcf - Documentation on how to use REST WebAPI like a boss -

i've exposed few methods and, while crystal clear on how they're supposed used, i'm sure time, memory fade , i'll standing there idiot wonder why on earth haven't provided help. when use wcf, there's wsdl file. i'm not aware of corresponding functionality webapi. add ping can type in url window of browser .../service.svc/ping , see date back. what intuitive , (hopefully fairly) canonical approach? i'm thinking .../help . there better way? just pushing out produce huge string (xml or json formatted), isn't like-a-boss'y. anonymous types can't handled without serialization. pushing out object typed entity breaks connection. i wish have built-in documentation on how use calls. names themselves, of course, values treated (i had case .../donkey?scope={scope} pattern null or all , though any , took while figure out.) you might checkout swashbuckle allow generate swagger documentation asp.net web api controllers. ano...

vbscript - How to integrate icon modification script with script to toggle proxy? -

i refer this post . in original post have proxy on/off script. where need inclusion of "icon change script" (see referral post) existing script, i.e. would set sh = createobject("wscript.shell") lnkfile = sh.specialfolders("desktop") & "\your.lnk" set lnk = sh.createshortcut(lnkfile) if lnk.iconlocation = "c:\path\to\some.ico" sh.iconlocation = "c:\path\to\.ico" else sh.iconlocation = "c:\path\to\some.ico" end if lnk.save fit into option explicit dim wshshell, strsetting set wshshell = createobject("wscript.shell") 'determine current proxy setting , toggle oppisite setting strsetting = wshshell.regread("hkcu\software\microsoft\windows\currentversion\internet settings\proxyenable") if strsetting = 1 noproxy else proxy end if 'subroutine toggle proxy setting on sub proxy wshshell.regwrite "hkcu\software\microsoft\windows\currentversion\internet settings\p...

Windows Azure Web sites python -

after whole load of hard work i've got hello world flask app running on windows azure, app built locally , runs fine, deploying azure nightmare though. i've sort of got 2 questions here. i can't seem stack trace @ all, i've tried setting things in web.config, documentation on how use stuff apawling, can find literally badly written blog posts dotted around 1 of microsoft's millions of blogs. doesn't me fix problem. the second question relates first one, due horrible debugging methods (taking application apart , commenting things out) feel pymongo causing this, i've built without c extensions , it's in site-packages , works on local machine. without stack trace i've no idea how fix without wanting pull hair out. can shed light on this? disappointing because rest of azure isn't bad, theres far better website hosting alternatives out there heroku literally 10 command setups. i've been working on day far.. solved for interest...

android - Shouldn't I be using a RecyclerView? -

Image
i want implement schedule-like overview list , grid view. works using recyclerview , swapping out layoutmanager @ runtime. works fine in general, tuned grid cells have fixed height, realised recyclerview not respect wrap_content layout property , instead introduces whitespace between grid items. i stumbled on more or less same question linear layoutmanager , third-party provided specialisations of layoutmanager. quick searched revealed nothing similar gridlayoutmanager , beginning suspect going down wrong road: apart easy switching between layouts, there seems no reason me work recycler view: i dont't require special animation stuff. my adapter returns fixed list without loading more items on demand. actual recycling of items doesn't take place. so evaluating switch separate fragments using ordinary listview , gridview . feel little working against intentions of android ... after all, introduced single view (in theory) should need. am missing obvious ...

deleteNode for singly linked list java -

public void deletenode(student targetnode) { node position = head; node nextposition1; node nextposition2; while (position.getlink() != null) { if (position.getlink().getdata().equals(targetnode)) { nextposition1 = position.getlink(); nextposition2 = nextposition1.getlink(); position.setlink(nextposition2); } else { position = position.getlink(); } } } i can delete specific nodes can't delete first node. your loop checking next link in position equality target node. thus, it'll never @ first value (the head). easiest way fix add clause check equality explicitly against head, , if exists, advance head it's link otherwise enter while loop checks against future links. believe want add break; if clause remove link unless you're looking potentially remove several nodes , not 1 (as function name suggest). public void deletenode(student targetnode) { node po...

javascript - AngularJS Routed Page Not Showing -

so quick question i've been looking @ code awhile cannot find why, gives me output on page partials/view1.html i'm not trying post here whenever run small issue has been baffling me awhile now, , no errors on console. run code http://plnkr.co/edit/sn9tagvbodx3mkrxatiu?p=preview , mentioned on post , works fine, don't right output this. following index.html (the main page) <!doctype html> <html ng-app="demoapp"> <head> </head> <body> <div ng-view></div> <script src="angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script> <script src="scripts.js"></script> </body> my script likes: var demoapp = angular.module('demoapp', ['ngroute']); demoapp.config(function($routeprovider) { $routeprovider .wh...

c# - I cant seem to use dependency injection in WinRT BackgroundTask -

i implementing ibackgroundtask in windows runtime component , i'd inject logger dependency application exits when calls background task. won't enter constructor. i'm using ninject di container , have no problems using anywhere else in app. i'd this: private readonly ilog _logger; public backroundtask(ilog logger) { _logger = logger; } public async void run(ibackgroundtaskinstance taskinstance) { var deferral = taskinstance.getdeferral(); try { // here } catch (exception ex) { // log error injected logger... logger.errorformat("{0}error in queuetimer {1}{0}", environment.newline, ex.tostring()); } deferral.complete(); } i've had no success i've tried , log on oncomplete method in calling .cs file. in limited experience creating windows store applications, must supply default constructor background tas...

c++ - Correct behavior for std::setprecision(0) in GCC vs VS2013 -

depending on compiler use, different out put function @ n=0. std::string tostrwprec(double a_value, const int n) { std::ostringstream out; out << std::setprecision(n) << a_value; return out.str(); } (gcc) 4.8.3 20140911 (red hat 4.8.3-9) returns 1 tostrwprec(1.2345678,0). vs2013 returns 1.2346 same code. my question are: what correct/standard behavior setprecision? what alternative using setprecision? here updated code based on comment below std::string tostrwprec(double a_value, const int n) { std::ostringstream out; out << std::setprecision(n) << std::fixed<< a_value; return out.str(); } according 22.4.2.2.2 [facet.num.put.virtuals] paragraph 5, stage 1, said precision: for conversion floating-point type, if floatfield != (ios_base::fixed | ios_base::scientific), str.precision() specified precision in conversion specification. otherwise, no precision specified. the same paragraph specifie...

angularjs - Angular: Using ng-disabled if forms in partials in child controllers have ng-invalid attribute -

i've been struggling few hours, , i'm coming blank. wouldn't build this way, else's code , refactoring way beyond scope of part of project. need works within way it's built. here rough approximation of html looks like: <div ng-controller=outercontroller outercontroller> <button ng-click="save()" ng-disabled="?????">save</button> <div ng-controller="partialcontroller partialcontroller> <div partial can replicated bunch of times , called recursively> <form name="partialform></form </div> </div> </div> so, there can ton of instances of partialform within dom, may different degrees of childhood outercontroller, , want able check if of them have ng-invalid ng-disabled on save button. any thoughts? :)

how do I restart the live google app engine server? -

i keep getting 'that user can undo transaction "appcfg rollback"' error, want know, how can restart server, instead of trying deploy? step 1: appcfg.py rollback . output: 06:36 pm application: blah-app-dev-2 06:36 pm host: appengine.google.com 06:36 pm rolling update. step 2: appcfg.py update workers/workers.yaml output: 06:37 pm host: appengine.google.com 06:37 pm application: blah-app-dev-2; module: workers; version: v1 06:37 pm starting update of app: blah-app-dev-2, module: workers, version: v1 06:37 pm getting current resource limits. 06:37 pm scanning files on local disk. error 409: --- begin server output --- transaction user jill in progress app: s~blah-app-dev-2, version: v1. user can undo transaction "appcfg rollback". --- end server output --- now what? you can shut down instances in developer console, not solve problem. have execute rollback command.

sketchup - Ruby to load profile component in selected lines -

i have question in writing ruby code can 3d modeling in sketchup program profile components stretch lengths in selected lines creating glass curtain wall systems of stick , unitized system. now, knew there's method creating 1 connected line, not have multiple , separated lines yet. therefore, i'm looking way write code in 1 click of sample profile component , load on multiple lines. is there suggestion kind of code ?. have been trying solve codes, can't in on own since i'm new in programming. the follow me feature extrudes profile along 1 segment. if have multiple branching segments need go differently. 1 method can try sort out different segments , create them separately groups - should each result in solid object use solid boolean operation introduced in sketchup 8 pro.

php - Laravel Eloquent for loop query to single prepared query -

need converting following laravel eloquent loop query single mysql query hits database single time. hit database n number of times based on how many items in $cardquerylist. for($i=0; $i<count($cardquerylist); $i++) { $usercard = collection::firstornew( ['username' => $cardquerylist[$i]['username'], 'card_uid' => $cardquerylist[$i]['card_uid']] ); $usercard->have_quantity = $cardquerylist[$i]['have_quantity']; $usercard->save(); } this have: db::raw('replace users_collection (username, card_uid, have_quantity) values('.$cardquerylist[$i]["username"].', '.$cardquerylist[$i]["card_uid"].', '.$cardquerylist[$i]["have_quantity"].')'); the problem i'm using 'username' , 'card_uid' unique key find corresponding row update. issue requires me specify values fields otherwise fields lost or replaced default values. how can ...

windows - Can't find WinJS when creating new project -

i'm pretty new windows development, i'm @ js. since love develop universal apps did research , found winjs. started watch microsoft's build conferences , tutorial on youtube can't find winjs option , template in "new project" window of visual studio. suggestion? please me! want start developing winjs apps! (also sorry bad english:) ) please follow steps bellow: click "new project" click "templates" in new project window. click "other language" click "javascript" , chose "blank app(universal windows)" , don't forget change project name. please see screenshot .

tfs - Can I bind query from WIQL to dataviewer/grid? -

i have code outputs results textbox try { // connect work item store tfsteamprojectcollection tpc = new tfsteamprojectcollection( new uri("xxx")); workitemstore workitemstore = (workitemstore)tpc.getservice(typeof(workitemstore)); // run query. workitemcollection queryresults = workitemstore.query(richtextbox1.text); foreach (workitem workitem in queryresults) { richtextbox2.text = string.join(environment.newline, workitem.areapath, workitem.project); } } catch (exception exceptionmessage) { messagebox.show(exceptionmessage.tostring()); } } can treat query result sql query sql server , bind datagrid or dataviewer? can't seem work, don't understand how data handled , returned wiql/tfs. no, need query result , place them table in dataset, , bind dataset datagrid. ref...

c# - Navigating one frame from within a second frame not working -

my mainpage has 2 frames. can navigate both frames mainpage. want navigate secondframe page within firstframe. code runs fine, frame doesn't navigate. thanks. mainpage.xaml <splitview.content> <grid> <grid.rowdefinitions> <rowdefinition height="*" /> <rowdefinition height="auto" /> </grid.rowdefinitions> <grid.columndefinitions> <columndefinition width="*" /> <columndefinition width="300" /> </grid.columndefinitions> <frame x:name="firstframe" horizontalalignment="stretch" grid.row="0" grid.column="0" /> <frame x:name="secondframe" grid.row="0" grid.column="1" borderbrush="lightblue"...

swift - Restore label to variables when switching back to a view -

i new swift , have been building timer app. main (first) view controller stopwatch. recently, added view controller view splits stopwatch. problem occurs when timer has been or running , user switches second view controller , returns main view controller. instead of displaying correct stopwatch time (for example: 12:34.56), label reset default text have stopwatch (00:00.00). if resume stopwatch, restarts left off (this how intend function since user has not manually reset watch). how can display current time when switching stopwatch view controller? you store current time in global variable before going split view. then, on viewdidappear method of original view, set label correct string based on stored in variable for over-simplified example //set "00:00.00" default var currenttime: string = "00:00.00" override func viewdidappear(animated: bool){ mylabel.text = currenttime } func gotosplitview(){ currenttime = mylabel.text }

objective c - iOS - Get first name and last name using Google SignIn SDK -

i using google sign in sdk , works perfectly. able following data: nsstring *userid = user.userid; // client-side use only! nsstring *idtoken = user.authentication.idtoken; // safe send server nsstring *name = user.profile.name; nsstring *email = user.profile.email; how retrieve first name , last name? , other information, instance city user lives in, , on? i faced similar problem yours. cannot first name , last name separately google sdk. instead can manually follows, nsstring *name = user.profile.name; nsarray *items = [name componentsseparatedbystring:@" "]; //take 1 array splitting string nsstring *fname = [items objectatindex:0]; nsstring *lname = [items objectatindex:1];

arrays - int cannot be converted to int[] -

i'm counting of specific numbers in array keep receiving error int cannot converted int[] . the variables val , two have been defined in program before, not error. public static int[] removeval(int[] two, int val) { int count=0; (int a=0; a<two.length; a++) { if (two[a]==val) count++; } return count; } the method returns array of ints, returning int, not array of ints.

ruby on rails 3.2 - Devise redirecting to different resource when using force_ssl -

i have force_ssl enabled entire application , using devise authentication. in production when try , access http devise-path e.g., http://domain.com/users/sign_in , redirected https version of path different resource e.g., https://domain.com/admins/sign_in . this seems dependent on order resources given in routes.rb. instance if have: devise_for :users devise_for :admins then accessing http://domain.com/admins/sign_in will redirect https://domain.com/users/sign_in , whereas http://domain.com/users/sign_in will maintain correct resource , redirect https://domain.com/users/sign_in . if change order of resources in routes.rb, opposite true. i have implemented customized version of force_ssl in application controller in order able later specify controller actions exceptions. class applicationcontroller < actioncontroller::base include applicationhelper protect_from_forgery #re-implement force_ssl allow override in controllers def self.force_ssl(options = {}) host = opti...

swift - Calculate average pace -

i need convert decimal hour in hh:mm:ss display average pace walking app. i have converted time decimal , have calculated pace in decimal unsure how convert time. my timedecimal is: let timedecimal:double = (hoursource + (minutesource / 60) + (secondsource / 3600)) / distancesource which gives me 0.4375 0 = 0 .4375 * 60 = 26.25 .25 = * 60 = 15 i know time should 00:26:15 not sure formula achieve without splitting result , performing multiplication multiple times. any appreciated. let formatter = nsdatecomponentsformatter() formatter.allowedunits = [ .hour, .minute, .second ] formatter.unitsstyle = .positional formatter.zeroformattingbehavior = .pad let string = formatter.stringfromtimeinterval(0.4375 * 3600)! result: 0:26:15 .

html - Floating two 50% width divs with a 10px margin between -

i want float pair of fluid divs across page, each taking half of container's width, margin of 10px between them. i've done jsfiddle http://jsfiddle.net/andfinally/sa53b/5/ , , here's html: <div class="clearfix"> <a class="prev" href="#">previous</a> <a class="next" href="#">next</a> </div> and css: .prev { background: black; color: white; font-size: 16px; margin-bottom: 10px; display: block; float: left; box-sizing: border-box; width: 50%; margin-right: 5px; } .next { background: black; color: white; font-size: 16px; margin-bottom: 10px; display: block; float: right; box-sizing: border-box; width: 50%; margin-left: 5px; } the box-sizing rule isn't enough make work - divs more 50% wide. in 1 of answers this question suggested using css display-table. can explain how make work in situation? th...

android - programmatically adding custom animation to fragment using objectAnimator -

i add custom animation fragments using following code. fragmenttransaction ft = getfragmentmanager().begintransaction(); ft.setcustomanimations(r.animator.slide_in, r.animator.slide_in, r.animator.slide_out, r.animator.slide_out ); ft.add(r.id.container, new doze1fragment()); ft.addtobackstack(null); ft.commit(); now i'm playing around adding few different fragments on top of each other in span of 3 5 seconds , pop of them out of stack "fanning" animation out of fragments. in order either add delay in between each popbackstack() call (i think horrible solution), or make custom xml animator resource each fragment. wondering if has idea of how programmatically right before calling ft.add(r.id.container, new doze1fragment()). know use following code animate view , looking similar objectanimator oa = objectanimator.offloat(r.id.container, "x", 0, 1000f); oa.setduration(300); oa.start(); thanks in advance.

broadcastreceiver - Get Notification even when app is not running -

hello can please me how notification on specific date when app not in running state, in advance you have calculate exact date , transfer long type. set time in notification. looks like: long time = system.currenttimemillis(); // example, should revise. notificationmanager manager = (notificationmanager) context.getsystemservice(context.notification_service); notification n = new notification(r.drawable.notification_icon, context.getstring(r.string.app_name), time); manager.notify(constants.notification_id, n);

objective c - Will off loading tasks to background threads improve overall performance in iOS? -

while using xcode time profile, see of function calls being performed in main thread. since they're not ui related, want move them background thread. offloading these tasks background thread improve performance of app or still same. know @ least it'd benefit updating ui. how measure performance of app using instruments, profiling module should use? thanks offloading tasks don't require main thread way go. main thread deals action demand user attention or related ui actions. i don't know mean performance when talk delegating background threads. indeed, putting forward better ui/ux performance such can't uplifted through threads. i recommend profile application , see objects creating? -monitor leaks. -consider doing time profiling. -check if i/o , cpu activities optimum. these surely nail down , performance related issues. (nb: 5% of time should go profiling app.)

c++ - How to Reduce the noisy While Scale a Image/Picture with Qt -

Image
i use code like: void mylabel::paintevent(qpaintevent *event){ qpainter painters(this); /*对img进行平滑缩放*/ int image_width,image_height; image_width = width(); image_height = height(); qimage result = img.scaled(image_width<<2, image_height<<2).scaled(image_width, image_height,qt::ignoreaspectratio,qt::smoothtransformation ); painters.drawpixmap(0,0,image_width,image_height,qpixmap::fromimage(img)); } i want scale image size want, when scale non equal proportion , terrible things happened ,noisy huge ,and image/picture this: and want know how way scale image/picture instead: i suspect because call qimage::scaled() twice, first upscale 4× desired size , second actual desired size. first call uses default value transformation mode (which qt::fasttransformation ). you're combining non-smooth , smooth transformation. note first transformation should unnecessary anyway. scale...

What does the => operator do in the arguments of a foreach loop in PHP? -

this question has answer here: what “=>” mean in php? 6 answers reference — symbol mean in php? 15 answers another clear n00b question: in following snippet of code (that works fine), '=>' operator do? thought creating associative arrays. going on here? any explanation helpful. foreach ($parent $task_id => $todo) { echo "<li>$todo"; if (isset($tasks[$task_id])) { make_list($tasks[$task_id]); } echo '</li>'; } it splits key , value element of array. example: $fruitcolor = array('apple'=>'red', 'banana'=>'yellow'); foreach($fruitcolor $fruit => $color){ echo $fruit . ' ...

ios - Navigation Controller - Swift -

i want create food app. image1 , 2 want app like. don't know how implement swift xcode. right now, have 2 view controllers go , forth. any advice or tip appreciated. stuck @ how create circles. thinking putting circles tableview thing, not sure best way implement this. i have set parse project. image 1 (list of restaurants): restaurants image 2 (list of food/drinks): food/drinks in tableview delegate setting yourimageview in swift yourimageview?.layer.cornerradius = (yourimageview?.frame.size.height)!/2 yourimageview?.layer.maskstobounds = true yourimageview?.layer.borderwidth = 0 in objective-c cell.yourimageview.layer.cornerradius = cell.yourimageview.frame.size.height /2; cell.yourimageview.layer.maskstobounds = yes; cell.yourimageview.layer.borderwidth = 0;

java - Insert date in oracle using prepared statemnt -

my user interface returns date string (01/06/2016 2:30 am)to controller , want insert oracle 10 database changing string date , format (dd-mmm-yy hh:mm:ss a) field date type. below tried getting illegal argument exception . in controller formatted date , passed service layer through dto created : 01/06/2016 09:00 pm simpledateformat fromuser = new simpledateformat("mm/dd/yyyy hh:mm a"); simpledateformat myformat = new simpledateformat("dd-mmm-yy hh:mm:ss a"); string reformattedstr = myformat.format(fromuser.parse(created)); system.out.println("reformattedstr : " + reformattedstr); **reformattedstr 06-jan-16 09:00:00 pm date formatedate=myformat.parse(reformattedstr); in service through prepared statement trying insert , date , other fields. stmt.settimestamp (8,new java.sql.timestamp(news.getcreated().gettime())); can please suggest? thanks , have updated code, might one. if column data type timestamp , don't need...

java - How to not crash if a foreign key refers to a null row while the key is not nullable? -

i have table "regions": id | name | parent_id 1 | whatever | 100000 where parent_id should self referencing id, meaning row geographically belongs 100000. however due data being imported @ beginning dirty, row id 100000 doesn't exist. therefore in given entity: @entity("regions") public class region { private int id; private string name; private region parent; ... @manytoone() @joincolumn(name = "parent_id") public region getparent() { return parent; } public void setparent(region parent) { this.parent = parent; } } when list hibernate: session session = sessionhandler.getsession(); //gets current session transaction tx = session.begintransaction(); try { return (list<t>)session.createquery("from regions").list(); } catch(hibernateexception ex) { ex.printstacktrace(); if (tx!=null) tx.rollback(); throw ex; ...

php - Crontab Linux not running at specific time -

i have crontab job running @ 07.00 every day. set 0 7 * * * /usr/bin/curl http://localhost//blablaba it did not work but if replace with */10 * * * * /usr/bin/curl http://localhost//blablaba then running every 10 minutes. not working if give specific time for information, have check server time , shows right time thanks :( your cron expression looks correct. follows format: minute hour day-of-month month day-of-week [user] command 0 7 * * * /usr/bin/curl http://localhost//blablaba ps: need add user field if using /etc/crontab file , not user specific crontab. so, if cron job defined in /etc/crontab file, need add user field cron job make run. if it's not case, check url on client , server side. but, think best thing debugging cron job. so, need enable logging cron jobs doing following: if on ubuntu : sudo vi /etc/rsyslog.d/50-default.conf if on centos : sudo vi /etc/rsyslog.conf uncomment li...

Use ports for rendering in elm -

i use flot.js 2d plot library elm. first thought i'd write native wrapper seems discouraged. therefore want try use ports send values plot javascript (ie call flot.js made on javascript side). possible? yes, can use ports send data elm plot flot graph. here's rewrite of basic flot example using elm data source. port flotexample1 : list (list (maybe (list float))) port flotexample1 = let halfstepsto14 = list.map (\x -> x / 2) [0..28] d1 = list.map (\x -> [x, sin x]) halfstepsto14 d2 = list.map [[0, 3], [4, 8], [8, 5], [9, 13]] d3 = [just [0, 12], [7, 12], nothing, [7, 2.5], [12, 2.5]] in [ d1, d2, d3 ] elm conversion of basic elm datatypes in ports javascript types on other side. maybe in function signature above account fact nulls can used separate line segments in flot (see example d3 ) <script> var app = elm.worker(elm.main); $(function() { $.plot("#placehold...

What is the difference between scope and encapsulation? (C++) -

picking programming after 8 years of... not programming (starting college soon, brushing on old knowledge). what difference between scope , encapsulation? seem rather similar. a scope area within program within automatic variables may created , @ end of automatically destroyed. examples function body or code-block of for-loop . scopes may enclose 1 , variables in outer scope may, or may not, accessible code in inner scope . for example global scope encloses other scopes , variables created in global scope visible other scopes (according various name resolution rules). therefore scope refers visibility of objects can accessed given point in program. there different types of scope each own visibility rules, example class scope refers visibility of member variables , member functions member functions of class object . for more detailed definitions see http://en.cppreference.com/w/cpp/language/scope encapsulation when hide specific data makes o...

javascript - Getting values from database on select dropdown in textbox -

please answer below question i want details database on select of option , display values of related select option accordingly <table border="1" class="form" id="datatable"> <tbody> <tr class="vd_bg-green vd_white" id='row_0'> <td><input name="chk" type="checkbox"></td> <td><select id="product_name" name="product_name" oninput= "calculate('row_0')" required="" style="width: 180px; color: black"> <option>//options database</option> </select></td> <td><input id="description" maxlength="70" name="description" oninput= "calculate('row_0')" required="" st...

html - Replace Text with Image by get user input in Javascript? -

i have modify program replace image text. in program, value of input box should reflect in place of balloon image. me ? program link: $('#draw').click(function() { var text = document.getelementbyid('txtballon').value; var $ballon = $('#ballon'), $canvas = $('#canvas'); var ballon_x = $ballon.offset().left - $canvas.offset().left, ballon_y = $ballon.offset().top - $canvas.offset().top; context.drawimage(ballon, ballon_x, ballon_y); $ballon.hide(); $(this).attr('disabled', 'disabled'); }); jsfiddle you can following way: context.font = "30px verdana"; context.filltext(text,ballon_x,ballon_y); instead of context.drawimage(ballon, ballon_x, ballon_y); working fiddle updated fiddle text drag

javascript - Uncaught TypeError: Type error with drawImage -

i new html5 , canvas element , in last few weeks have been trying understand better. anyways getting uncaught typeerror: type error when trying change red square code http://jsfiddle.net/kmhzt/10/ image http://i.imgur.com/k73egsw.png . when try uncaught typeerror: type error . here code have http://jsfiddle.net/ccdfs/ . if need me explain better ask. you're trying pass url drawimage , can't - need load image element , pass instead, after image has finished loading. this article has examples of i'm describing. the code end this: var img = new image(); img.onload = function() { context.drawimage(img, 2, 2); } img.src = 'http://i.imgur.com/k73egsw.png'; in fact, code when loads , draws tiles.

vba - In Excel, use "Range.Replace" method to substitute characters, but do not affect formulae -

i want create macro excel (2010) substitute characters of latin alphabet equivalents cyrillic alphabet. at first glance, seems quite easy, e.g. this: activesheet.range("a1:z500").replace "sht", chrw(1097) '--> щ activesheet.range("a1:z500").replace "sht", chrw(1095) '--> Щ 'and on relevant characters , character combinations however, when run on active worksheet, not cell values affected formulae. makes them worthless, because e.g. sum(b1:b3) become Сум(Б1:Б3) [i.e. using cyrillic letters] which, excel, gibberish. therefore question: there way tell excel use replace method on cell values, not on formulae? note: dirty workaround include procedure on each cell in range first checks if starts "=", , if so, leave cell contents unchanged. perhaps there better, less home-brewed way? range.replace search in formulas. there hasformula property in range object. using must iterate on cells in given ra...

angularjs - How do I update devDependencies with latest version using NPM command? -

i want update devdependencies latest version using npm command. npm update update packages in dependencies , npm update --save-dev add latest dependencies in local module. my concern - i want check latest version available. npm-check-updates want update 1 one. $ npm install -g npm-check-updates $ npm-check-updates -u $ npm install one more question component can update without affecting project.. please guide me. my package.json: { "author": { "name": "test", "company": "test" }, "name": "test", "private": true, "description": "test", "version": "10.0.010", "devdependencies": { "expect.js": "~0.2.0", "glob": "~3.2.7", "grunt-angular-templates": "^0.5.5", "grunt-cli": "~0.1.13", "grunt-contrib-clean": ...

How to insert selected data into new table using php mysql -

i need code on how insert data file " continue_sel.php " new table. please read attached code below. advice appreciated. best regards. new table format : id-gdate-parlay1-gdate-parlay2-........gdate-parlay5-amount continue_sel.php <?php include_once 'include/function_define.php'; connect(); ?> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- above 3 meta tags *must* come first in head; other head content must come *after* these tags --> <!-- bootstrap --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> <link href="datatables.bootstrap.min.css" rel="stylesheet"> <!-- html5 shim , respond.js ...

ios - Restrict angle of swipe to scroll UIScrollView -

i have vertical scroll view needs scrollable want use left , right swipe gestures else. have behavior each swipe direction working, want restrict angle of swipe scrolls uiscrollview, has really, vertical, , left or right leaning swipes activate other behavior , not change scroll position. i know can swipe angle overriding scrollviewdidscroll , comparing previous , current contentoffset , cannot stop scrollview scrolling there. how can limit angle of swipe scrolls uiscrollview ? i think scrollviewdidscroll late want achieve. maybe try setting directionallockenabled property of uiscrollview yes . (not sure if helps... play it) and/or implement uiscrollviewdelegate method - (void)scrollviewwillbegindragging:(uiscrollview *)scrollview , within methods implementation grab pointer pangesturerecognizer (readonly) property of uiscrollview passed in. from there call translationinview: on uipangesturerecognizer , passing in view in coordinate system translation o...

c# - how to restore database to particular folder? -

i have db backfile in d:\prabhagar\projects\zip\priya db\backups\sample.bak when restore restore c:\program files\microsoft sql server\mssql11.sqlexpress2012\mssql\data this directory. want restore d:\prabhagar\projects\zip\priya db\backups\testdb\ how can do? used following query restore database backup_lookup disk = 'd:\prabhagar\projects\zip\priya db\backups\sample.bak.' please me. thank you try following command. restore database backup_lookup disk = 'd:\prabhagar\projects\zip\priya db\backups\sample.bak' replace, move 'backup_lookup_data' 'd:\prabhagar\projects\zip\priya db\backups\testdb\backup_lookup.mdf', move 'backup_lookup_log' 'd:\prabhagar\projects\zip\priya db\backups\testdb\backup_lookup_1.ldf'

lucene - SOLR range query for fraction numbers no going to work properly -

i have field in solr contains fraction value 1.2, 0.523, 4.7 etc. field defined like <field name="ratio" type="float" stored="true" indexed="true"/> in order search range 0.2 1, using following query http://localhost:8983/solr/collection1/select?q=bag&df=keywords&wt=json&indent=true&group=true&group.field=ratio&fq=ratio:[0.2 1] but results obtained contain ratio grater 1. problem in query. note: have group on field why applied grouping also. not worry it the float field type in solr has odd behavior when comes range queries... field values sort numerically, range queries (and other features rely on numeric ranges) not work expected: values evaluated in unicode string order, not numeric order. from: http://lucene.apache.org/solr/4_10_4/solr-core/org/apache/solr/schema/floatfield.html what want use equivalent trie field in case trie float. field should defined follows... <fiel...

spring - Httpsessionlistener: two sessions are created and none are destroyed -

edit: reformulated question i'm using spring , gwteventservice (which basicly same comet ). when make simpler httpsessionlistener, see sessioncreated() called twice , sessiondestroyed() not called in between. why that? have 2 sessions 1 user??? second httpsession created when set information first time @ session bean ( spring ). import javax.servlet.http.httpsessionevent; import javax.servlet.http.httpsessionlistener; public class somesessionlistener implements httpsessionlistener { @override public void sessioncreated(httpsessionevent se) { log.info("new session created, source= " + se.getsource()); } @override public void sessiondestroyed(httpsessionevent se) { log.info("a session closed"); } } example output: application has started new session created, source= org.mortbay.jetty.servlet.hashsessionmanager$session:21u4n0rnyp4i@24662444 new session created, source= org.mortbay.jetty.servlet.hashsessionmanager$session:n9wm...

Problems changing ownership from service account to google apps domain -

i have app uses google service account create either fusion tables or google spreadsheet document. app changes ownership of document user (joe@gmail.com). enables app publish (insert rows) document, gives full control on document specified user. everything works fine if other user @gmail.com user. however, if apps domain user (e.g., xxx@camfed.org), permission change results in error: { "error": { "errors": [ { "domain": "global", "reason": "internalerror", "message": "internal error" } ], "code": 500, "message": "internal error" }}{"value":"xxx@camfed.org","role":"owner","type":"user","kind":"drive#permission"} here outcomes matrix: service account created xxx@gmail.com ...

Unable to create a variable in javascript -

i creating app tell price of product when barcode scanned. basically, when barcode scanned, goes text field, , based on barcode is, textarea have price put via javascript. i've gotten work, can't seem create variable save me looking through tons of code later on. here javascript: function showprice() { var userinput = document.getelementbyid('barcode').value; var price = document.getelementbyid('textarea').innerhtml; if (userinput === "783466209834") { price = "16.99"; } else { price = "not valid barcode"; } } and here html: <input type="text" name="text" class="textinput" id="barcode"> <input type="button" onclick="showprice()" value="submit"> <textarea name="" cols="" rows="" readonly="readonly" id="textarea"></textarea> right now, code is...

android - Can't resolve the dependency -

my other dependencies being resolved except-: compile 'com.parse.bolts:bolts-android:1.2.1' compile 'com.parse:parse-android:1.+' my build.gradle -: apply plugin: 'com.android.application' android { compilesdkversion 23 buildtoolsversion "22.0.1" defaultconfig { applicationid "com.transenigma.iskconapp" minsdkversion 15 targetsdkversion 23 versioncode 1 versionname "1.0" //multidexenabled true } buildtypes { release { minifyenabled false proguardfiles getdefaultproguardfile('proguard-android.txt'), 'proguard-rules.pro' } } uselibrary 'org.apache.http.legacy' } dependencies { compile filetree(include: ['*.jar'], dir: 'libs') testcompile 'junit:junit:4.12' ...

java - Spring AMQP take action on message timeout -

i using spring amqp asynchronous messaging. model assumes there 2 applications , b, both producers , consumers. a sends job request b , starts listening. b listening job request, , when comes, starts job , periodically sends progress messages a. b sends job finish message after job finished. a consumes progress messages until job finish message comes, exists. i using @rabbitlistener on class level , @rabbithandler on method level, message consuming. works nice , design clean, spring's solution. my problem - have no idea how detect, , how act, when expecting receive progress message b (any message) , it's not coming in. there timeout such cases? if so, how implement callback method? i found timeout settings, works connection itself, or when using rpc pattern (one request 1 response). desired solution - should receive progress message every minute. if no progress message consumed for, say, 3 minutes, want cancel job. when using async consumers, there...

wolfram mathematica - Save plot options in list -

i wonder if possible make variable holds info obout wanted style show[] function. ewery time want display plots in show[] insert variable in show[] set options style. i want this... options= axesorigin -> automatic, labelstyle -> directive[14, black, bold, italic], imagesize -> {450} show[ listlineplot[data], options ] the solution simple im green. :) options = {axesorigin -> automatic, labelstyle -> directive[14, red, bold, italic], imagesize -> {450}} show[listlineplot[{1, 2, 3, 4, 5}], options] works me.

python - Invalid reference to table while order_by applied -

i have sqlalchemy data model (other fields missed): class region(base): __tablename__ = 'region' id = db.column(db.integer, primary_key=true) class district(base): __tablename__ = 'district' id = db.column(db.integer, primary_key=true) region_id = db.column(db.integer, foreignkey(region.id)) region = relationship(region) and build query: session.query(district)\ .options(joinedload(district.region))\ .order_by(region.name, region.id)\ .slice(0, 25) the query emits error programmingerror: (programmingerror) invalid reference from-clause entry table "region" . after investigation raw sql reason of error found. order by clause non correct: select district.id district_id, district.name district_name, district.region_id district_region_id, region_1.id region_1_id district left outer join region region_1 on region_1.id = district.region_id order region.name, region.id limit 25 into order by...