Posts

Showing posts from August, 2014

web crawler - Scrapy python error - Missing scheme in request URL -

i'm trying pull file password protected ftp server. code i'm using: import scrapy scrapy.contrib.spiders import xmlfeedspider scrapy.http import request crawler.items import crawleritem class sitespider(xmlfeedspider): name = 'site' allowed_domains = ['ftp.site.co.uk'] itertag = 'item' def start_requests(self): yield request('ftp.site.co.uk/feed.xml', meta={'ftp_user': 'test', 'ftp_password': 'test'}) def parse_node(self, response, selector): item = crawleritem() item['title'] = (selector.xpath('//title/text()').extract() or [''])[0] return item this traceback error get: traceback (most recent call last): file "/usr/local/lib/python2.7/dist-packages/twisted/internet/base.py", line 1192, in run self.mainlo

javascript - angular templating: ng-repeat comma-separated links -

i got disappointed angular... i'm trying quite simple presentation-layer stuff , can see no solution while browsing web (and stack overflow well). the case is: i've got list of elements generate links to, of them comma-separated in html . let's it's: var list = [{id: 1, name: "ab"},{id:2, name: "cd"}, ...]; my link should like: <a href="#/somelink/{{ el.id }}">{{ el.name }}</a> easy, isn't it? so, basing on other questions, tried this: <a ng-repeat="el in list" href="#/somelink/{{ el.id }}">{{ el.name }}</a>{{$last ? '' : ', '}} which doesn't work, because ng-repeat inside ng-repeat , $index , $last , $first caught outer ng-repeat values instead of inner one, want. moreover, don't making html one-liner 5 things @ time, because [1] costs read , [2] it's easier mess something, while changing, because of complexity. prefer split more lines. but

apache - Is node.js better behind a reverse proxy for sending json? -

i have make web service can handle many r&w requests (up 50/seconds) , think have static server (who host angular.js app, , heavy resources video , image) is idea have node.js server behind reverse proxy nginx or apache? goal reduce load of node.js server. and communication method must use between reverse proxy , node.js? http? cgi? other? and best reverse proxy in case? nginx? apache? it shouldn't make of difference behind reverse proxy or not, proto, http fine.

java - Why is map.values().stream() much slower than Array.stream(array) -

creating 2 constructs university second semester computer science count words in text. 1 implementation uses array word-objects save word string , frequency int. other uses hashmap word key , frequency value. function "totalwords" should return sum of frequency. in hashmap variant: return _map.values().stream().reduce(0, (a, b) -> + b); in array variant: return arrays.stream(_words) .map((word) -> word != null ? word.count() : 0) .reduce(0, (a, b) -> + b); my problem is: in junit test short test text array variant need approximately 0.001s , map variant needs 0.040s , not understand why map need more time. has explanation , maybe better solution? one of reason iterating hashmap can slower array , reason locality . computation bottleneck of modern processor dominated memory access, , that's why cache used. array stores data in contiguous chunk of memory, means when swap chunk of memory cache, more using in cache, o

How to get variables from the command line in Java? -

i've finished writing java program drinksbot. have 1 issue; need 2 variables command line saved int variables eg. the user types in: java drinksbot 30 40 and program begins run, , saves int cupstock= 30; int shotstock = 40; //or whatever user typed command line. any appreciated; i'm new this! my code begins this: import java.util.scanner; public class drinksbot { static scanner keyboard = new scanner (system.in); public static void main(string[] args) { system.out.print("hello, what's name? have"+cupstock+" cups left, , " + shotstock+" shots left.); ... continues run rest of program etc. read args[] array in main method. variables passed in command line assigned string array defined in main method. public static void main(string[] args) { string cupstock = args[0]; string shotstock = args[1]; system.out.print("hello, what's name? have"+cupstock

multithreading - Killing Process after specific time(Java) -

i want have mechanism expected process shouldn't run more specific time. after specific time over, status whether process running or not should displayed , process should no longer run. for tried make 2 classes execute , check , execute object's run method execute process. check object sleep specific time, after checks whether object of execute still running. if running check object expected kill thread , print "yes". else, check object should print "no". class execute extends thread{ public void run(){ //execute process } public static void main(string[] args){ execute ex = new execute(); ex.start(); check ch = new check(ex); ch.start(); } } class check extends thread{ execute ex; check(execute ex){ this.ex = ex; } public void run(){ try{thread.sleep(5000);} //specific time given 5 seconds

c# - while writing result into csv , format of number/text not getting set properly -

i writing data csv. while doing have written below result csv (size of file in bytes). fnumber name size 1 save.png 6.89766e+11 i have tried use string, long, double size variable not keeping text or number format that. written size looks above or sometime appending 000000 @ end of size.. i want whole value should number. please let me know how set text/number setting before writing csv thanks in advance the following code should work static void writecsvfile() { fileinfo file = new fileinfo(@"<path of file>"); streamwriter writer = new streamwriter(@"d:\output.csv", false); writer.writeline("{0},{1},{2}", "fnumber", "name", "size"); writer.writeline("{0},{1},{2:d}", "1", "save.bng", file.length); writer.close(); }

Notify server that client system shut down -

i have situation need know client system has shut down manually or due power failure (irrespective of same lan or wide network). i need know after logging in application (web), client forget logout , shut down system manually or due power failure. i'm storing logged in users status in hashmap not in db , removing when clicking logout button.... if system got shut down without logging out not removing hashmap. there event listener in java catch client shut down status? how can achieve scenario, possible? i'm using vaadin 7.4.3 framework web application. add session destroy listener web application , remove user there. session destroy listener called when session expires. should implement logout button way invalidates session place need remove users session destroy listener.

javascript - How to check if two convex polyhedrons intersect with each other in Three.js? -

i'm working on problem need randomly generate , put convex polyhedrons cube/cylinder container @ randomly chosen points without overlapping. i'm using three.js graphic output. a demo. while putting polyhedron, how check whether intersects other polyhedrons? the convex polyhedron involved tetrahedron or hexahedron , constructed using three.convexgeometry. need precise check, bounding box not enough, use make sure 2 polyhedrons not intersected. i've done lot research , found many complicated theories , methods, need boolean result tells if there exists intersection between 2 convex polyhedrons. sat (separating axis theorem) in 3d enough, three.js doesn't seem capable of doing this. can tell me how kind of check in simple way or explain how sat in 3d? you can take @ http://www.realtimerendering.com/intersections.html . though site 2011 intersection algorithms have not changed in last years. demo seems once polyhedrons placed in cube, don't

jquery - Animate specific paragraph using wow.js onclick -

i using wow.js animate different elements on page when scrolling. want rise animation on specific paragraph when clicked on button (in jquery). <p id="reasons" class="wow fadeinup" data-wow-delay="0.2s">x y z</p> i don't want initialize page animation once again (see below), animate concrete paragraph (with id = "reasons" ). new wow().init(); how can this? wow.js works page scroll. you can trigger animation using jquery toggleclass() method on click. $(document).ready(function() { $("#reasons").click(function() { $(".box").toggleclass("animated"); }); }); <link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.6/animate.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p id="reasons" class="box infini

if statement - If there is no command-line argument, read stdin Python -

so have text file called ids looks this: 15 james 13 leon 1 steve 5 brian and python program (id.py) supposed read file name command-line argument, put in dictionary ids keys, , print output sorted numerically ids. expected output: 1 steve 5 brian 13 leon 15 james i got working part (calling on terminal python id.py ids ). however, supposed check if there no arguments, read stdin (for example, python id.py < ids ), , print out same expected output. however, crashes right here. program: entries = {} file; if (len(sys.argv) == 1): file = sys.stdin else: file = sys.argv[-1] # command-line argument open (file, "r") inputfile: line in inputfile: # loop through every line list = line.split(" ", 1) # split between spaces , store list name = list.pop(1) # extract name , remove list name = name.strip("\n") # remove \n key = list[0] # extract id entries[int(key)] = name # store keys int , name in d

java - AngluarJS directive alternative of jsp tag library? -

i have gone through angular js tutorials. directives 1 of pillar of angularjs. understnading directives can substitue of custom jsp tag libraies (which developers develop specific each project). correct ? the reason saying jsp taglib developed have reusable ui component can achieved angularjs directive on client side . yes absolutely correct. angular js directives play same role tag libraries in jsp. difference in jsp tags generated code on server side , sent client whereas angular directives generate code on client side

c - Passing a FILE pointer to a function and getting error message 'FILE is an unknown type name' -

i'm trying pass pointer function, compiler throws error saying 'file unknown type name'. in main: file *fp = fopen(argv[1], "r"); get_tok(fp); function declaration throws error: int get_tok(file *fp) am not including .h file or something? the best way not open file outside function..declare file pointer. , inside function, use fopen , if return value 0 or null return 0 or else return 1..and read returning value main yo decide of file has been opened successfully..

javascript - Loading sequential web pages in a browser -

this question has answer here: can greasemonkey fetch values paginated sequence of url's? 1 answer i can't find meets needs here have simple answer. i want browser load pages 1 after other, i.e. www.sitename.com/page 0405 , www.sitename.com/page 0406 etc, variable interval. i don't need other above. want visit each sequentially-numbered page in succession. onload triggered when element loads. put iframe , load next page every time onload triggers. var = 0 var iframe = document.queryselector('iframe') iframe.onload = function() { iframe.src = 'http://www.sitename.com/page'+i i++ } iframe.onload()

angular - Cannot read property 'split' of undefined -

i have following code running on local server. <!doctype html> <html> <head> <link rel="stylesheet" href="style.css"> <script src="https://jspm.io/system@0.16.js"></script> <script src="https://code.angularjs.org/2.0.0-alpha.19/angular2.dev.js"></script> </head> <body> <my-app></my-app> <script> system.config({ paths: { '*': '*.js', 'angular2/*': 'angular2/*' } }); system.import('main'); </script> </body> </html> the above index.html page. import {component, view, bootstrap} 'angular2/angular2'; @component({ selector: 'my-app' }) @view({ template: '<h1>my first angular 2 app</h1>' }) class appcomponent { } bootstrap(appcomponent); the above main.js file. when run on server following in console. http://lo

jquery - Reducing code redundancy in a series of javascript function expressions -

i have long series of javascript functions invoked 'onclick' on function name in html. corporate number <input type="text" autofocus id="corp_text"> <button onclick="getcorpnum(this.form)">save</button><br><br> llc number <input type="text" autofocus id="llc_text"> <button onclick="getllcnum(this.form)">save</button><br><br> type of nonprofit <input type="text" autofocus id="np_text"> <button onclick="getnonprofit(this.form)">save</button><br><br> other description <input type="text" autofocus id="od_text"> <button onclick="getdesc(this.form)">save</button><br><br> in javascript functions similar in form: /** * corporation number text field data. */ var getcorpnum = function() {

cakephp - Declaration of Upload::beforeSave() should be compatible with Model::beforeSave($options = Array) [APP/Model/Upload.php, line 5] -

i being shown following error on top of page when using beforesave method in upload model. strict (2048): declaration of upload::beforesave() should compatible model::beforesave($options = array) [app/model/upload.php, line 5] could point out i'm doing wrong? here model: <?php app::uses('appmodel', 'model'); class upload extends appmodel { protected function _processfile() { $file = $this->data['upload']['file']; if ($file['error'] === upload_err_ok) { $name = md5($file['name']); $path = www_root . 'files' . ds . $name; if (is_uploaded_file($file['tmp_name']) && move_uploaded_file($file['tmp_name'], $path) ) { $this->data['upload']['name'] = $file['name']; $this->data['upload']['size'] = $file['size'];

python - Getting a key error while using a dict with TEMPLATE.format() -

at loss on this. i'm getting key error can't figure out why key referenced looks it's in dict. any help? template = "{ticker:6s}:{shares:3d} x {price:8.2f} = {value:8.2f}" report = [] stock = {'ticker': 'aapl', 'price': 128.75, 'value': 2575.0, 'shares': 20} report.append(template.format(stock)) this error got: report.append(template.format(stock)) keyerror: 'ticker' you need put ** in front of dictionary argument. so, last line be: report.append(template.format(**stock)) and should work. so code should be: template = "{ticker:6s}:{shares:3d} x {price:8.2f} = {value:8.2f}" report = [] stock = {'ticker': 'aapl', 'price': 128.75, 'value': 2575.0, 'shares': 20} report.append(template.format(**stock)) related: python 3.2: how pass dictionary str.format()

javascript - How to animate and change a slider counter position in a clean way? -

Image
i have swiper slider , counter position "1/10". change current slide number (the 1) animation. know how replace number animation, it's story: as can see on gif, it's working nicely if click moderately on slider, when double-triple-or-crazy click on next link, totally breaks counter, due clone made in gif example. know how can in better way? i made jsfiddle, working first count change only: — http://jsfiddle.net/asb39sff/1/ // init var $c_cur = $("#count_cur"), $c_next = $("#count_next"); tweenlite.set($c_next, {y: 12, opacity: 0}, "count"); // change counter function function photos_change(swiper) { var index = swiper.activeindex +1, $current = $(".photo-slide").eq(index), dur = 0.8, tl = new timelinelite(); // test tl.to($c_cur, dur, {y: -12, opacity: 0}, "count") .to($c_next, dur, {y: 0, opacity: 1}, "count") //$c_cur.text(index); //$

php - UPDATE to database using PDO error -

i used pdo update values table using following method form <form role="form" method="post" action="submitupdate.php" autocomplete="off"> <input class="update" type="text" name="fullname"></li> <input class="update" type="text" name="dob"></li> <textarea style="width:740px;height:220px;" class="update" type="text" name="intrested"></textarea></li> <textarea style="width:740px;height:220px;" class="update" type="text" name="description"></textarea></li> </form> processing <?php require('includes/config.php'); //if not logged in redirect login page if (!$user->is_logged_in()) { header('location: login.php'); } //define page title $title = 'members page'; //include header template ?&g

r - Hardcode hexadecimal string values as color in ggplot -

i have data frame "x" , "y" columns numeric values, , third column "cluster" hexidecimal string, example seen below: library(ggplot2) library(scales) collist = c(scales::hue_pal()(3),"#520090") dat = data.frame(x=runif(100,0,1),y=runif(100,0,1),cluster=sample(1:4, 100, replace=t)) dat$cluster = factor(dat$cluster) levels(dat$cluster) = c(collist) head(dat) i trying create scatterplot "x" , "y" columns mapped x , y axis, , points colored according hexadecimal value stored in "cluster" column. have tried following: ggplot(dat,aes(x,y))+ geom_point(aes(colour = cluster), alpha=0.5) however, assigns default first 4 values stored in scales::hue_pal()(4), , have changed last 1 dark purple color hexadecimal value #520090. trying change default hexadecimal values appearing text in legend. tried unsuccessfully hardcode in "cluster 1", "cluster 2", ..., "cluster 4" legend text: ggplo

meteor - object is not a function in iron-router routes at onBeforeAction hook's this.next() -

i'm running iron-router 1.0.7, , onbeforeaction hook causing exception. here's stack trace: exception in callback of async function: typeerror: object not function @ router.onbeforeaction.except (http://localhost:3000/lib/router.js?ebfe803416134e7c5b16265486b3998532289c58:45:8) @ http://localhost:3000/packages/iron_router.js?a427868585af16bb88b7c9996b2449aebb8dbf51:1199:36 @ _.extend.withvalue (http://localhost:3000/packages/meteor.js?43b7958c1598803e94014f27f5f622b0bddc0aaf:955:17) @ router.addhook.hookwithoptions (http://localhost:3000/packages/iron_router.js?a427868585af16bb88b7c9996b2449aebb8dbf51:1198:27) @ boundnext (http://localhost:3000/packages/iron_middleware-stack.js?0e0f6983a838a6516556b08e62894f89720e2c44:424:31) @ meteor.bindenvironment (http://localhost:3000/packages/meteor.js?43b7958c1598803e94014f27f5f622b0bddc0aaf:983:22) @ router.onbeforeaction.only (http://localhost:3000/lib/router.js?ebfe803416134e7c5b16265486b3998532289c5

rest - Spring Security for RESTful API -

i'm building restful api using spring 4.1.6 , spring-boot-starter-data-rest . to make rest api functional need last piece of puzzle: security. noticed spring has it's own spring-security-* packages can aid task. i tried using spring-security-config , spring-security-web , works charm, exception if user not authenticated, spring redirect user login, giving html login form. because it's restful api, need error returned in json object if user lacks credentials or not have enough permissions read particular resource. i'm sure i'm not first ask question , searched on web people asking same thing, couldn't quite find was looking for. so.. should continue research in direction spring-security, or should find something? any advice welcome, thank you to change login form response custom http response need configure custom http response handler http security config. if using xml security configuration use configuration shown below, failurehandler us

ios - Removing all subviews from a UITableViewCell except imageView -

i creating custom cell , add subviews text mostly. @ first subviews not getting deleted when cell reused, text overwrite , blot bad. added loop function , solved problem except removes imageview , never gets re-added, whole tableview missing image supposed associated each cell. the if statement didn't work, didn't explicitly use cell.addsubview() did cell labels, wondering if has it. have googled , found people saying worked them, cannot seem figure out. why remove images, why won't come pack other subviews, , how can fix this? i have following code: func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell { let cell = tableview.dequeuereusablecellwithidentifier("cell") as! uitableviewcell subview in cell.subviews { if subview as? nsobject != cell.imageview { subview.removefromsuperview() } } var statusimage = uiimage(named:imageconfigration(indexpath.row))!

Pass javascript variable to a javascript on a different website -

is possible pass javascript-variable script on site? this: this code in page on www.myfirstsite.net: <script> var id = 'randomstring'; </script> <script src="http://www.mysecondesite.net/processingscript.js"></script> how can read var id in script on mysecondsite.net? update: question wrong, explained in helpful answers @vihan1086 , others. why never that you should never declare variables that, has been described here then what? on 1 page, do: window.globals = {}; window.globals.my_variable = 'abc'; on script, add: var globals = window.globals; globals.my_variable;//gets 'abc' keep variables safe in global place. can global variables @ once, increasing speed. don't forget wrap code in like: (function() { //code here })(); functions to make easier made functions: setsharedvar (name, value) { if (!"globals" in window) { window.globals = {}; }

c# - How to Change the color of each pixel in a image by using Magick.Net -

i'm new magick.net. tried change color of each pixel in image there's no change in new image. here's code. tell me what's going on? lot. using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; using imagemagick; namespace magicktutor { class program { static void main(string[] args) { magickimage image = new magickimage(); image.read("c:\\.....\\test1.png"); foreach (pixel p in image.getwritablepixels()) { p.setchannel(0, 65535); } image.write("c:\\.....\\test2.png"); } } } you should call write method of writablepixelcollection class returned image.getwritablepixels() make sure pixels written image. you doing in different way: using (magickimage image = new magickimage()) { image.read(@"c:\.....\test1.png"); image.evaluate(channels.red, eval

events - Where do you put Log::listen? -

i have simple laravel 5 application. i don't know put snippet log::listen(function($level, $message, $context) { // dostuff(); }); i tried put in routes.php but: first, dostuff() never reached secondly, i'm not sure right place have artisan commands , don't think use routes file. thanks advice. one place write new middleware or own serviceprovider. find myself middleware easier. read more http://laravel.com/docs/5.0/middleware

ViewPager.PageTransformer Android -

i want following, create grid of images using gridlayout inside scrollview inside viewpager, let's have pages of pictures, page 1 animals, page2 plants, etc. , want able scroll , down view images, of animals on page 1, , scroll right , left change page animation using pagetransformer. , need see pages on left , right described here . done there conflict in touch events can't resolve , need help. now when use pager.setpagetransformer(true, new zoomoutpagetransformer()); lose the scrollview , down scroll , cool animation. , when don't use need except animation, how can them all? this main activity, public class mainactivity extends activity { pagercontainer mcontainer; public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); mcontainer = (pagercontainer) findviewbyid(r.id.pager_container); final viewpager pager = mcontainer.getviewpager(); pag

apache spark - pyspark how to load compressed snappy file -

i have compressed file using python-snappy , put in hdfs store. trying read in following traceback. can't find example of how read file in can process it. can read text file (uncompressed) version fine. should using sc.sequencefile ? thanks! i first compressed file , pushed hdfs python-snappy -m snappy -c gene_regions.vcf gene_regions.vcf.snappy hdfs dfs -put gene_regions.vcf.snappy / added following spark-env.sh export spark_executor_memory=16g export hadoop_home=/usr/local/hadoop export java_library_path=$java_library_path:$hadoop_home/lib/native export ld_library_path=$ld_library_path:$hadoop_home/lib/native export spark_library_path=$spark_library_path:$hadoop_home/lib/native export spark_classpath=$spark_classpath:$hadoop_home/lib/lib/snappy-java-1.1.1.8-snapshot.jar launch spark master , slave , ipython notebook executing code bel

javascript - Select and open a selectbox with jquery -

i know can focus , select html selectbox drop-down jquery: <script> $('#otherbox').on('change', function() { $("#selbox").focus(); $("#selbox").select(); }); </script> but focuses selectbox doesn't open it, still have click on select-element mouse open it. how can automatically open selectbox event? there 2 ways it: you can either try use mouseevent simulate mousedown ( https://developer.mozilla.org/en/docs/web/api/mouseevent + check links in comments) or can create invisible div select 's options duplicated in right under select , upon click event make div visible, emulating open dropdown.

swing - Display tree map in gui java -

firstly new java please can explain things simple possible! so have treemap, keys dates point strings. i want display on screen not sure how so. i did come across jtable. after reasearching confused columns string array (simply titles of 2 columns) whilst data tree map. after looking further online found should create table model after reading through didn't understand needed do. appreciated! thanks in advance. the way want display content varies depending on requirement or on how information displayed in user-friendly way. jtable approach, jtree approach, although, see jtable more standard way it. i came approach implemented fast trying simplify complex stuff , fulfill understood question: public class tableexample { //asuming have treemap static map<date, string> samplemap = new treemap<date, string>(); //initialize sample treemap values (this static block execute first time run app) static { samplemap.put(createbirthdayfromstring(&qu

algorithm - How can I iterate through all possible grid layouts? -

i have grid (an nsarray of cgpoint s)where want layout objects @ points based on constraints. know: how big grid is the number of objects have laid out on grid, @ point the minimum distance between 1 object (calculated using pythagorean magic) the distance between points on grid each point can have 1 object located there i pick random object (using arc4random ) , validate whether or not valid point. if is, flag such , choose point. if not, continue until either entire array searched @ point grid layout marked impossible , start again. this continues until valid grid layout found. problem: i don't know how many if any valid layouts exist given constraints. i'm having trouble trying find way either calculate possible permutations, or iteratively search through permutations find if valid grids exist, prior embarking on impossible search.

php - MYSQL auto increment becomes corrupt -

Image
for reason i'm having issue after while table turns "corrupt" guess error: mysql failed read auto-increment value storage engine i found solution run following query: alter table `users` auto_increment = 1 the bad part randomly occurred 3 times far in 3 weeks without me altering in table. reason found out hearing user unable register :/ this query run register new user, can see doesn't insert user_id obviously insert users (user_name, user_lastip, user_password_hash, user_email, user_activation_hash, user_registration_ip, user_registration_datetime) values(:user_name, :user_lastip ,:user_password_hash, :user_email, :user_activation_hash, :user_registration_ip, now()) here quick screenshot of table: (i had user_id length set 11 before started happen , tried setting 255 last time error occurred didn't help) does know causing or how fix this? i'm not 1 having problem there has logical explanation hope check autoincrement_offset. t

c# - Multiple dbContexts in ASP.NET vNext and EF7 -

i'm trying along building web systems asp.net vnext using mvc 6 , ef7. i'm looking @ tutorial: http://stephenwalther.com/archive/2015/01/17/asp-net-5-and-angularjs-part-4-using-entity-framework-7 on page you'll see how add dbcontext project , it's registered in startup file this: // register entity framework services.addentityframework(configuration) .addsqlserver() .adddbcontext<moviesappcontext>(); and context class looks this: public class moviesappcontext:dbcontext { public dbset<movie> movies { get; set; } } it works good, i'm in need of adding additional dbcontext. though don't know how register additional context used ef , possible use in project. let's i've created new context this: public class mynewsuper:dbcontext { public dbset<model1> model1 { get; set; } public dbset<model2> model2 { get; set; } } how go ahead register use in project then? important note: synta

Having trouble trying to solve bit level manipulation puzzle in C -

so have use bitwise manipulation solve problem. should duplicate effect of c expression (x*63), including overflow behavior. examples: multi63(1) = 63 multi63(-1) = -63 available ops: ! ~ & ^ | + << >> maybe i'm not understanding being looked im trying different variations , each time result either close needs returned isn't correct. this playing with. figured if mask x, 1 perimeter, know whether i'm multiplying negative or positive. int y = x>>31; return ~(y^x) this returns: test times63(2147483647[0x7fffffff]) failed... ...gives -2147483648[0x80000000]. should 2147483585[0x7fffffc1] and if try return 2147483585[0x7fffffc1] tells me need return -2147483648[0x80000000] i'm confused need return. as general(!) rule can consider these formulas expression x*n, using shifts , addition/subtraction only: a: (x << n) + (x << n-1) << + ... + << (x << m) b: (x << n+1) - (x << m)

swift - SkSpriteNode won't show up -

override func didmovetoview(view: skview) { /* setup scene here */ var sun = skspritenode(imagenamed: "sun") sun.position = cgpoint(x:cgrectgetmidx(self.frame), y:cgrectgetmidy(self.frame)) sun.xscale = 0.2 sun.yscale = 0.2 addchild(sun) } i'm new coding games, i've worked swift, , added code , sun not show up, there isn't error, , have image name sun in images.xcassets. you have make sure gameviewcontroller-frame fits gamescene-frame. just add line gameviewcontroller.swift-class in viewdidload -method before skview.presentscene(scene) : scene.size = skview.bounds.size here make sure frames same , .position works want.

Keyboard navigation with Android GridView doesn't scroll grid -

Image
i'm trying use keyboard navigate through gridview of items. in short demo, contains gridview (containing item views android:focusable="true" ), can see none of items gain focus - grid thing scrolls (the items don't turn orange). adding android:descendantfocusability="afterdescendants" allows each item focused first, still, doesn't continue scroll gridview can navigate down: clicking on item (with mouse or pressing return if item focused, after descendent focusability fix) turns item blue - indicating it's in pressed state. @layout/activity_my.xml: <?xml version="1.0" encoding="utf-8"?> <gridview xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listview" android:layout_width="match_parent" android:layout_height="match_parent" android:numcolumns="2" /> @layout/dummy_item.xml: <?xml version="1.0" enco

ios - Shared iAd on Tabbed Application -

new ios development , have tabbed app 4 tabs. have iad showing on 1 tab , don't want regurgetate code on every view controller , know not correct way implement anyway. have looked @ apple code here , i'm struggling honest. https://developer.apple.com/library/ios/samplecode/iadsuite/introduction/intro.html i have included bannerviewcontroller.m , bannerviewcontroller.h in application i'm not sure how run ad on each view controller. yours confused jkx just grab reference of uiwindow in of viewcontroller class go .m of viewcontroller #import "appdelegate.h" @interface viewcontroller () { //make object of appdelegate appdelegate *appdelegate; } now in viewdidload or viewdidappear grab reference of window. appdelegate=(appdelegate*)[uiapplication sharedapplication].delegate; [appdelegate.window addsubview:yourbannerview];

psycopg2 - Python error: execute cannot be used while an asynchronous query is underway -

how prevent error “ programmingerror: execute cannot used while asynchronous query underway ”? docs says should use psycopg2.extras.wait_select if i’m using coroutine support gevent., i’m still error when i’m using it. i’ve isolated error i’m getting in snippet below. con = psycopg2.connect(database=database_name, user=database_username) def execute_query(cur, query, params): psycopg2.extras.wait_select(con) cur.execute(query, params) psycopg2.extras.wait_select(con) rows = cur.fetchall() print rows[0] cur = con.cursor() query = "select * mytable" gevent.joinall([ gevent.spawn(execute_query, cur, query, none), gevent.spawn(execute_query, cur, query, none), gevent.spawn(execute_query, cur, query, none), gevent.spawn(execute_query, cur, query, none) ]) you trying more 1 transaction simultaneously on single connection. psycopg documentation says not thread safe , lead error. see under asynchronous support , support corouti

How do I set up online hosting for an eclipse war file and initial MySQL server data currently on my laptop? -

i built small web app in eclipse (has jsp pages, java interface, , hibernate database connectivity). now want host website. have basic idea web hosting, database ?? how connect website database ?? in short... 1: how host website in form of war file ? 2: how put data present in database online (if there called online database) , keep connected web app ? to host java based website, need use publicly accessible application server such tomcat set deploy to. openshift free cloud hosting service suited task. if create new tomcat app, provide git url push application to, deployed on service binding service database specific host using openshift add effect hibernatecontext.xml (if using mysql) <bean id="datasource" class="org.springframework.jdbc.datasource.drivermanagerdatasource"> <property name="driverclassname" value="${jdbc.driver}" /> <property name="url" value="jdbc:mysql://${op

JQuery children loop XML -

using jquery , ajax, getting xml document , looping through document in attempt @ each level of xml tags/nodes, parent children , children of children respectively. what have works written limit of children of children of children (not ideal). the final application may have open ended number of children action to. how can make account number of children without inefficiency? i have tried making function basis of wish achieve @ each child level. not work expected, breaking script. the function function childx() { $(this).children().each(function() { $("#output").append("<div id='"+(this).nodename+"'>"+(this).nodename+"</div><br />"); }); } the main script $(xml).find("recenttutorials").children().each(function() { $("#output").append("<div id='"+(this).nodename+"'>"+(this).nodename+"</div><br />");

c# - Where to look for DB file after update-database? -

i created domain classes , db tables representations using entity framework. using migrations seed method created init data. in console window, use update-database command create db , seed data. now, don't know find database file, , how attach in server explorer. my app.config connection string looks <configuration> <connectionstrings> <add name="mydbcontext" connectionstring="data source=.\sqlexpress;initial catalog=mydbcontext;integrated security=true;attachdbfilename=|datadirectory|mydbcontext.mdf" providername="system.data.sqlclient" /> </connectionstrings> </configuration> i in app_data folder, , tried attach db using server explorer, don't know browse add. i'm doing wrong here? if understand correctly , looking physical location of files in sql server express 2008 r2 can find them here : c:\program files\microsoft sql server\mssql10.sqlexpress\mssql\data i not using sql serve

assembly - X86_64 AT&T How to put one ascii letter(1byte) at the end of the text placed in register -

i need open text file. have filename in register , need add '\0' (0x00 in hex) @ end. my register rcx contains name: e.txt , can check in gdb , presents correctly : rcx: 0x7478742e65 there name in ascii code. i'd put '00' after , should that: rcx: 0x007478742e65 i using assembler x86_64bit at&t

flex - automatic layout adjustment to varying browser window size -

in flex4/mxml, have bunch of elements textfields, buttons or else. want place them horizontally next each other. cases browser window or screen resolution small such not of them fit horizontally, want layout automatically shifts superfluous elements row below. in other words, need layout comprises both, horizontal , vertical layouting, whereas horizontal has priority on vertical. simple layout, yet i'm unable find solution. how can achieve that? for example, following starting point: <mx:hbox horizontalgap="0" width="{width-30}" horizontalalign="center" textalign="center"> <mx:label paddingleft="10" text="anytext1" /> <mx:label id="warn12" text="anytext2" /> <mx:button label="do something1" click="{cf.dosomething(1)}"/> <mx:label paddingleft="0" text="anytext3" /> <mx:button label="

javascript - Authenticating documentDB REST API calls -

in sample application , name of host , key added config.json file. when application run in browser, configuration downloaded user's computer? can me understand js file being downloaded users computer, , js file runs on server? the short answer no, config.js lives on server. sample app mentioned written using node.js (which server-side javascript run-time) using express framework . by default, should assume every file lives on server (unless explicitly exposed). for sample app, in /public/ directory (which contains simple .css stylesheet) exposed client. exposed app.js on line 29 : app.use(express.static(path.join(__dirname, 'public'))); you can find full code sample tutorial mentioned on github: https://github.com/azure/azure-documentdb-node/tree/master/tutorial/todo

How to compare length of data in mysql type text using php? -

this question has answer here: sql / mysql - order length of column 3 answers i have table name = text_tab _________________________ | id | message | | 1 | aaa | | 2 | bb | | 3 | ffff | | 4 | ooooooo | | 5 | gg | i want check row data in column message have max char. , column message type text . in answer show id=4 i use order message desc not work, how can ? have tried char_length or length function yet? work select id text_tab order char_length(message) desc instead of ordering message column directly, order char_length of said column.