Posts

Showing posts from March, 2015

javascript - isNAN not evaluating -

newb here trying learn i'm attempting check data entered form, if data entered second or third inputs not numeric (i.e. alphabetical) display notice user info not numeric. using 'isnan' function this, it's not working i'd hoped based on i've read on google, stack , other places. i've tried both 'isnan' , '!isnan', neither 1 triggers hoped event within script. here javascript attempting: if(empty(thisform.epiname,"episode name left blank. please enter name of episode submitting can boldly go , check results!")){return false;} if(empty(thisform.rstot,"red shirt total left blank. please enter total estimated number of starfleet officers wearing red shirts appear in episode can boldly go , check results!")){return false;} if(empty(thisform.reremaining,"red shirts surviving left blank. please enter number of starfleet officers survive episode can boldly go , check results!")){return fals...

java - Pascal's triangle without using arrays (only loops) -

i trying output pascal's triangle asterisks (*). code: public static void main(string [] arg) { int n=3; for(int i=0;i<n;i++) { for(int j=0;j<n-i;j++) { system.out.print(" "); } boolean b=true; for(int k=0;k<i*2+1;k++) { if(b) { system.out.print("*"); b=false; } else { system.out.print(" "); b=true; } } } system.out.println(" "); } } i have rechecked several times , failed find error. let me know whether if-block implemented correctly. following code not giving required output below: * * * * * * your system.out.println() statement outside of loop instead of inside. (int = 0; < n; i++) { (int j = 0; j < n - i; j++) { system.out.print("...

c# - Extracting a number from between parenthesis -

i have regular expression designed extract number between 2 parenthesis. had been working fine until made input string customizable. now, if number found somewhere else in string, last number taken. expression below: int icorrespid = convert.toint32(regex.match(subject, @"(\d+)(?!.#\d)", regexoptions.righttoleft).value); if send string this (12) test , works fine, extracting 12. however, if send this (12) test2 , result 2. realize can change righttoleft lefttoright, fix instance, want number between parenthesis. i sure easy regular expression experience (which not me). hoping show me how correct want, give brief explanation of doing wrong can improve. thank you. additional information i appreciate of responses. have taken agreed upon advice, , tried each of these formats: int icorrespid = convert.toint32(regex.match(subject, @"(\(\d+\))(?!.#\d)", regexoptions.righttoleft).value); int icorrespid = convert.toint32(regex.match(subject, @"(\(\d+\...

python - How to use several subprocess.check_output and avoid non-zero exit status 67 -

i'm @ beginning of learning python, may obvious. i'm trying create script change desktop pictures in os x 10.9 according group membership. if check 1 thing, script works. it's when try expend on fail. i've tried putting declarations before if else, tried if elif else. how 1 python use several subprocess.check_output in row? the script dies traceback: traceback (most recent call last): file "/library/setdesktopimages/setdesktopimages.py", line 36, in module checkstudentuser = subprocess.check_output(['dseditgroup', '-o' , 'checkmember', '-m', username, 'students']) file "/system/library/frameworks/python.framework/versions/2.7/lib/python2.7/subprocess.py", line 575, in check_output raise calledprocesserror(retcode, cmd, output=output) subprocess.calledprocesserror: command '['dseditgroup', '-o', 'checkmember', '-m', 'root', '...

gruntjs - Grunt Watch - Verifiying property -

i'm attempting seperate grunt file can process 2 separate chunks of code, seems work apart watch task. i following error loops out until exceeds call stack waiting...verifying property watch.app.files exists in config...error >> unable process task. warning: required config property "watch.app.files" missing. it seems doesn't watch task being split two. i've around , doesn't seem issue other people. my gruntfile looks this: module.exports = function(grunt) { // 1. configuration goes here grunt.initconfig({ pkg: grunt.file.readjson('package.json'), concat: { app: { src: [ 'themes/site_themes/app/scripts/build/libs/!(html5shiv|respond).js', 'themes/site_themes/app/scripts/build/modules/*.js' ], dest: 'themes/site_themes/app/scripts/production/app.min.js' }, market...

ios - What does 'array' method in RACSequence (ReactiveCocoa) do? -

this code snippet ray wenderich's ios 7 best practices article . he's fetching json file , making model each in list; return [[self fetchjsonfromurl:url] map:^id(nsdictionary *json) { racsequence *list = [json[@"list"] rac_sequence]; return [[list map:^(nsdictionary *item) { return [mtljsonadapter modelofclass:[wxdailyforecase class] fromjsondictionary:item error:nil]; }] array]; }]; what array do? racsequence 's instance method map returns racsequence instance. if want nsarray instance, have use -[racsequence array] method evaluate entire sequence , convert values nsarray . by way, map method executed lazily; sequence produces values, receive them 1 one until unsubscribe or reach end of sequence. calling -array method block current thread if of values not yet available (until become available, @ point method un-block , return array).

c++ - How to get float value from object wrapped float in the sam way? -

pi'm trying wrap float, int, etc primitves value sparam class. have problem getting values struct. want use struct use example floats. template<class t> struct sparam { t value; sparam() { } operator t() const { return value; } }; sparam<float> a; a.value = 4; printf("%f", a); //<--this don't print a.value the problem using "naked" sparam<float> a printf (or other function takes variable number of arguments, matter) compiler not know want pass float . why type-specific conversion not applied. if call function specific parameter type, say void printfloat(float f) { printf("%f", f); } ... sparam<float> a; a.value = 4; printfloat(a); then compiler figure out signature of printfloat conversion float needs applied, , work expected. of course can apply conversion manually: printf("%f",...

php - strftime giving wrong month name (February only...) -

i have following code, month name of date, , using name of month in hebrew. $thismonthname = date("f", mktime(0, 0, 0, $thismonthnumber, 10)); date_default_timezone_set('asia/tel_aviv'); // set timezone israel $locale = 'he_il.utf8'; setlocale(lc_all, $locale); // set locale hebrew $thismonthnameheb = strftime('%b', strtotime($thismonthname)); it works perfectly, except february. when print out $thismonthname says "february" when print out $thismonthnameheb says מרץ (march) in hebrew. going crazy, can't figure out. you're doing conversion time string , back. instead of converting time -> string -> time , keep time value , base results on that: $thismonthtime = mktime(0, 0, 0, $thismonthnumber, 10); $thismonthname = date("f", $thismonthtime); date_default_timezone_set('asia/tel_aviv'); // set timezone israel $locale = 'he_il.utf8'; setlocale(lc_all, $locale); /...

php - Separator in my results -

this query works fine me, gets results , echos them back. missing , can not work separator in between results. have tried use implode function unable to. "|" in between results in echo. below code using, or direction appreciated. $dbh = mysqli_connect("xxxxxxxxxxx", $user_name, $password, $database_name); if (!$dbh) { die("not connected : " . mysqli_error($dbh)); } else { $query = "select value `$table_name` field in('$field1', '$field2')"; $result = mysqli_query($dbh,$query); if (mysqli_num_rows($result) == 0) { echo "no_data_found"; } else { while ($result_list = mysqli_fetch_array($result, mysql_assoc)) echo '' .$result_list["value"] . ''; } mysqli_close($dbh); } ?>

node.js - Mongoose find use result in the main code -

var mongoose = require('mongoose'); var result = false; thecollecton.findone({name: "hey"}, function(err,obj) { if(err) console.log(err); if(obj) result=true; }); console.log(result); // other things result and... doesn't work (and know why). how can make works ? it doesn't work because findone() call asynchronous. when call console.log() , execution of findone() not finished yet. need call console.log() inside asynchronous function: var mongoose = require('mongoose'); var result = false; thecollecton.findone({name: "hey"}, function(err,obj) { if(err) console.log(err); if(obj) result=true; console.log(result); }); edit: replying comment. if query in function , want use result of query in caller, need pass callback function. this, need modify function accept callback, example: function exists(name, callback) { thecollecton.findone({name: name}, function(err,obj) { var result = (err |...

printwriter - Hiding headers from a query in java program -

so have program spits out data google csv file. want allow users choose display headers or not via using string. here printer: ...some code // getting queries print if (results.getrows() == null || results.getrows().isempty()) { pw.println("no results found."); system.out.println("no results found."); } else { // print column headers. (columnheaders header : results.getcolumnheaders()) { pw.print(header.getname() + ", "); } pw.println(); // print actual data. (list<string> row : results.getrows()) { (string column : row) { pw.print(column + ","); } pw.println(); } pw.close(); } } } i have properties file connected program , want put when user types in no in header part of properties file dont want headers show. i thinking converting header part string , putting in if statement. suggestions? thx in advanced edit...

java - Save/Read File in android -

i want save file in android , of arraylist deleted after that.i have 2 methods write/read android file here problem want 2 methods that: the first method must save element of arraylist if call again not write new element in same line write in line the second must read line (for example give method line , returns lines contains) the file looks : firstelem secondelem thridelem anotherelem .. is possible in android java? ps: don't need database. update methods : private void writetofile(string data) { try { outputstreamwriter outputstreamwriter = new outputstreamwriter(openfileoutput("config.txt", context.mode_private)); outputstreamwriter.write(data); outputstreamwriter.close(); } catch (ioexception e) { log.e("exception", "file write failed: " + e.tostring()); } } private string readfromfile() { string ret = ""; ...

This IP, site or mobile application is not authorized to use this API key - Android -

Image
i have problem connection google maps api v2 , android. i' ve enabled services: google maps android api v2 places api also i've added sha1 fingerprint. but still message: this ip, site or mobile application not authorized use api key i'm calling service android. know might problem, cause don't know search. you must creating browser key instead of android key. faced similar problem when accidentely created android key google cloud messaging instead of server key. please check key required purpose. google maps v2 need android key , google places api need server key(searched google not sure on 1 never used it). need 2 keys. update: need server key places api.

amazon s3 - Google Drive equivalent for S3 Signed Request URLs -

how can create request url google drive resource such associated authentication information in url valid object. objects stored on s3, 1 can create signed request url expiration date (as explained here https://djangosnippets.org/snippets/1174/ ). looking similar google drive. have been able find to-date append access_token downloadurl of file. downloadurl expire after while access_token can used access owner's entire drive (correct me if wrong here). complete scenario: user (lets call him bob) grants app access google drive. fetch list of videos on google drive. bob selects couple of videos , asks app share user (lets call cindy). cindy gets email link page on app should show videos. since app has access_token bob's gdrive, retrieves temporary downloadurl google drive, appends access_token , shows videos on web page using these links. cindy can grab access_token browser , break bob's gdrive. not want cindy able break bob's account. the above can avoided if video...

mysql - Why do this error appear "#1215 - Cannot add foreign key constraint "? -

create table postcodes ( postcode_id int not null, location varchar(50), primary key (postcode_id) ); create table countries ( country_id int not null auto_increment, country_name varchar(50), primary key (country_id) ); create table suppliers ( supplier_id int not null auto_increment primary key, supplier_name varchar(50), supplier_forename varchar(50), supplier_phonenumber varchar(20), supplier_address varchar(50), supplier_postcode int, supplier_country int, foreign key (supplier_postcode) references postcode(postcode_id), foreign key (supplier_country) references countries(country_id) ) ; typo: create table postcodes ( ^----plural foreign key (supplier_postcode) references postcode(postcode_id), ^----no s, singular you're trying reference table doesn't exist.

c++ - how to deal with error:double free or corruption -

update: removenode code revised. no error, run, no output. output should printout vector in main function. still check bug now. lot help. if find anybug,please let me know. lot. ======================= the error got *** glibc detected *** ./bintree: double free or corruption (fasttop): 0x0000000000727060 *** the program simple following step: find min value of binary tree; record min value in vector; delete node min value in tree; repeat 1-3 till tree empty. the tree defined following, language c++ typedef struct mynode* lpnode; typedef struct mynode node; struct mynode { double key; lpnode left; //left subtree lpnode right; //right subtree }; this simple delete node function, since each time smallest value deleted. node kind leaf, not complicated. comparedouble(double a,double b) return true if a < b ; false if a > b //delete node void removenode(lpnode root,double min) { if(comparedouble(min,root->key)) { if(root->left !...

ios - I got this issue "Terminating with uncaught exception of type NSException" with my execution, can anybody help me with this? -

can helped below issue? i'm struck on here. while executing code i'm getting log. couldn't find solution it. tried whole day couldn't find solution it. 2014-05-29 10:34:35.723 timesheet[14438:60b] -[uitableviewcell setalternaterowcolor:]: unrecognized selector sent instance 0x8f98a70 2014-05-29 10:34:35.764 timesheet[14438:60b] *** terminating app due uncaught exception 'nsinvalidargumentexception', reason: '-[uitableviewcell setalternaterowcolor:]: unrecognized selector sent instance 0x8f98a70' *** first throw call stack: ( 0 corefoundation 0x0180a1e4 __exceptionpreprocess + 180 1 libobjc.a.dylib 0x015898e5 objc_exception_throw + 44 2 corefoundation 0x018a7243 -[nsobject(nsobject) doesnotrecognizeselector:] + 275 3 corefoundation 0x017fa50b ___forwarding___ + 1019 4 corefoundation 0x017fa0ee _cf_forwarding_prep_0 + ...

scala - Running tasks automatically using apache spark -

i new apache spark , trying run test application using spark. problem i'm facing when create rdd using collection of data want process, gets created spark doesn't start processing unless , until call .collect method present in rdd class. in way have wait spark process rdd. there way spark automatically processes collection form rdd , can call .collect method processed data time without have wait spark? moreover there way can use spark put processed data database instead of returning me? the code i'm using given below: object appmain extends app { val spark = new sparkcontext("local", "sparktest") val list = list(1,2,3,4,5) // want rdd processed created val rdd = spark.parallelize(list.toseq, 1).map{ => i%2 // checking if number or odd } // more functionality here // job above starts when line below executed val result = rdd.collect result.foreach(println) } spark uses lazy evaluation mode...

c# - How Can I Use Data Annotations Attribute Classes to Fail Empty Strings in Forms? -

i trying require text input field in form, implies there needs in form. however, adding [required] tag model wasn't working. specifically, @ user name property: public class columnwidthmetadata { [displayname("column name")] [required] public string colname { get; set; } [displayname("primary key")] public int pkey { get; set; } [displayname("user name")] [required] public string username { get; set; } [displayname("column width")] [required] public int width { get; set; } } this allows empty strings past model validation , database error thrown when attempts insert null value user name. how can change these attributes seem should do? after lot of googling , looking on stackoverflow, had nothing. i went msdn , looked @ system.componentmodel.dataannotations namespace . there looked more closely @ required attribute, , noticed allowemptystrings property . setting false te...

gps - Roads and places database? -

i'm trying determine if there's database or api available use detailed roadway data, meaning shape , length of roads, intersection points, speed limits, exit numbers highways, etc. obviously google, mapquest , others have access information , use give driving directions, i'd else data. thanks information. you can use openstreetmap database, contains mentioned data , more. can read more on openstreetmap wiki please mind openstreetmap license

multithreading - Cocoa: Delaying one method call until a subsequent call is processed -

i've found myself in following situation: i've got nstableview subclass active cell. when click elsewhere on user interface, delegate method (i) fired, in turn fires (ii) (my own method) cocoa proceeds process click, resulting in final 2 calls. surprised , disappointed sequence, since had assumed mouse click first rather last event processed. causes me problem because ideal implementation of managestate dependent on of processing in mousedown: , of course when managestate called mousedown: has not yet been executed. is way delay execution of managestate until mousedown has returned? example, in managestate i'd stop! mouse down event might in events queue. wait until it's finished, resume . previous sentence implies, it's possible method triggered other mouse down. in situation, there's no need out mouse down event , processing can continue normal. mouse click on nstextview while nstableview cell has focus... +-------------------------+----------...

assembly - Why does `call dword 0x12345678` compile to [66,E8,72,56,34,12]? -

$ cat call.s call dword 0x12345678 $ nasm call.s $ ndisasm call 00000000 66e872563412 call dword 0x12345678 why result [66,e8, 72 ,56,34,12] not [66,e8, 78 ,56,34,12]? why did 0x78 change 0x72 ? you are calling absolute address instruction, although may not seem obvious @ first glance. let's go through assembly process step step. firstly, can see instruction has been assembled 66 e8 . 66 operand size prefix - i'll explain why got there later. e8 points call instruction, expected, , following bytes - 72563412 - little-endian representation of 32-bit displacement relative instruction after call instruction. how relative jumps , calls encoded in x86 : because cpu knows current value of instruction pointer, can add value specified instruction value , execute call/jump. secondly, there question why assembler chose assemble instruction way. if running nasm without flags, defaults bin output mode, outputs raw opcodes file specify. additionally, defa...

javascript - Make image link open in new window in php file -

hi have website has banner want link website of mine, want open in new window. want cursor hand in browsers well. tried target = "_blank" method don't believe right. how can in php? here code i know there answers similar question none have solved problem <div class="banner-part" onclick="location.href='www.blabla.org/' target="_blank";" style="cursor: pointer;" style="cursor: hand;"><img src="<?php bloginfo('url') ?>/images/banner.png" alt="" /></div> you're making bit of mess there. you're forcing <div> act <a> , when achieve same thing sprinkle of css: <a href="http://www.blabla.org" target="_blank" class="banner-part"> <img src="<?php bloginfo('url') ?>/images/banner.png" alt="" /> </a> and make <a> block element through ...

gruntjs - Write file even if output css is empty -

i want write empty file destination file empty. is possible? the error "destination not written because minified css empty". i'm using grunt-contrib-cssmin module. only using grunt-contrib-cssmin , cannot. a place start when wondering specific piece of open source software: source code — task ~70 lines. the source can see "error" you're getting: if (min.length === 0) { return grunt.log.warn('destination not written because minified css empty.'); } you might want "touching" file. if familiar *nix, you'll know touch create file if doesn't exist , not truncate if does. in grunt (node.js) might want node-touch or grunt-exec . as gruntfile , you'd need one of following 2 tasks: module.exports = function (grunt) { var touch = require('touch'); grunt.initconfig({ 'cssmin': { 'combine': { 'files': { 'path/to/output.css...

cmake ExternalProject cache overwritten -

hello i'm facing problem regarding cmake , external projects. i set compiler , flags via cmake_cache_args and/or cmake_args works first time run make on subsequent call cmake cache of external project rebuild (deleted) , flags not set accordingly flags specified! wonder there workaround/way specify compiler once prevent rebuilding of cache? following basic test project downloads , compiles gtest, first call make compiles clang++ , given flags, following call make cause cmake cache rebuild without proper flags being set! cmake_minimum_version_required(version 2.8.6) project(test) include(externalproject) externalproject_add( gtest svn_repository http://googletest.googlecode.com/svn/tags/release-1.7.0/ cmake_args -dcmake_cxx_compiler:string=clang++ -dcmake_cxx_flags:string="\"-std=c++1y -stdlib=libc++\"" install_command "" # 1 can not install gtest dont here log_download 1 log_update 1 log_configure 1 ...

three.js - Grab objects near camera -

i looking @ http://threejs.org/examples/webgl_nearestneighbour.html , had few questions come up. see use kdtree stick particles positions , have function determine nearest particle , color it. let's have canvas around 100 buffered geometries around 72000 vertices / geometry. way know positions of buffered geometries , put them kdtree determine nearest vertice , go there. sounds expensive. what other way there return objects near camera. how three.lod it? http://threejs.org/examples/#webgl_lod has ability see how far object , render different levels depending on setting inputted. define "expensive". point of kdtree find nearest neighbour elements quickly, primary focus not on saving memory (although inplace on typed array, it's quit cheap in terms of memory already). if need save memory maybe have find way. yet typed array length 21'600'000 indeed bit long. highly doubt have have every single vertex in there. why not have position reference po...

mysql - How to show the content of Multiple tables in SQL using PHP (Inner Join) -

given following code: <?php include "connect.php"; $query = "select d.name,d.image,d.main_style,g.id,g.name dj d inner join genres g on g.id=d.main_style order d.name"; $exec = $mysql->query($query) or die("erreur"); $n = $exec->num_rows; if($n > 0) { echo '<!doctype html public "-//w3c//dtd html 4.01//en""http://www.w3.org/tr/html4/strict.dtd"> <html><table>'; for($i=0;$i<$n;$i++) { $row = $exec->fetch_array(); //echo '<tr><td></td><td><a href='dj.php?id=$row[id]'>$row[name]</a></td><td>$row[main_style]</td></tr>'; echo "<tr><td><img src=\"$row[d.image]\" width=\"100\" height=\"100\"/></td><td><a href='dj.php?id=$row[id]'>$row[name]</a></td><td>$row[main_style]</td></tr...

javascript - Behavior of html form onsubmit event in JSFiddle -

i have simple form has nothing other submit button. want prevent submission of form (i know doesn't make sense illustration). i'm making use of form's onsubmit event , event returns false . work 'incomprehensible behavior' arises. i can associate return false; statement onsubmit event of form either using inline javascript or keep in different place. <form onsubmit="return false;" id="form1" method="post"> <input type="submit" id="btnbutton" value="submit" /> </form> now, aforementioned code works fine. see => http://jsfiddle.net/mcck5/ i can modify above code follows in order make javascript separate (unobtrusive). --some html markup <form onsubmit="return falsifier()" id="form1" method="post"> <input type="submit" id="btnbutton" value="submit" /> </form> <script> function...

Facebook comments count in fbml doesn't work anymore -

so can't comment count work using html5 boxes: html: <fb:comments-count href="http://example.com"></fb:comments-count> comments js sdk included this: <script>(function(d, s, id) { var js, fjs = d.getelementsbytagname(s)[0]; if (d.getelementbyid(id)) return; js = d.createelement(s); js.id = id; js.src = "//connect.facebook.net/en_us/sdk.js#xfbml=1&appid=233176953542656&version=v2.0"; fjs.parentnode.insertbefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> and.. instead of querying normal graph comments endpoint executed fql query https://graph.facebook.com/v2.0/fql?callback... in response gave this: /**/ fb.__globalcallbacks.f2670b77d1e44b({ "error": { "message":"an access token required request resource.", "type":"oauthexception", "code":104 } }) ...

mysql - LOAD DATA LOCAL INFILE skips html tags inside <> -

Image
i have file this myfile.tpl {if !$smarty.action} <div id="bar"> {/if} .... i using command loading file mysql table create table mytable (col text); load data local infile 'myfile.tpl' table mytable fields terminated '' enclosed '' escaped '' lines terminated '\n' starting '' when use select * mytable 1 result is: {if !$smarty.action} {/if} and skips <div id="bar"> in output. followed same steps yours: myfile.tpl has below contents {if !$smarty.action} <div id="bar"> {/if} create table create table mytable (col text); loading data load data local infile 'd:\\so_test\\myfile.tpl' table mytable fields terminated '' enclosed '' escaped '' lines terminated '\n' starting '' viewing data returns select * mytable mysql version running show variables "%version%" 'innodb_vers...

axapta - Delegates for capturing changes -

ax 2012 has introduced delegates on classes. i've reviewed bunch of documents on web. of them illustrate usage on custom classes. serve illustrate technology rather real-life scenarios have deal with. i'm looking example capture changes in ax such add/change worker, customer, vendor etc. start with. want capture information , pass .net application. i'm having hard time finding examples. see answer use of static event delegates capture changes: table update event handler please aware events may bypassed using doupdate etc. , calling record.skipevents(true) . also consider using sql server feature change data capture .

asp.net - Bootstrap 3 input group not working with select element -

Image
i trying input-group styled in bootstrap 3 drop-down selector, using sample code: <div class="form-group"> <div class="input-group"> <span class="input-group-btn"> <select class="btn"> <option>usd</option> <option>gbp</option> <option>zar</option> </select> </span> <input type="text" class="form-control"> <span class="input-group-btn"> <div class="btn btn-default" type="button">button</div> </span> </div> </div> it works fine in bootply ( http://www.bootply.com/zvsundnxif ): but if put site (asp.net web forms) using same code, breaks: i wouldn't mind (in vanilla bootstrap it's lacking border around select box), except i'm using bootswatch themed version, doesn't align properly: the css...

windows - PHP in XAMPP not functioning -

i have php running in xampp win 7 64 bit. when run php file: <!doctype html> <html> <body> <?php print "<h2>php fun!</h2>"; print "hello world!<br>"; print "i'm learn php!"; ?> </body> </html> i get: php fun!"; print "hello world! "; print "i'm learn php!"; ?> i same result using echo. i opened http://localhost/xampp/ , shows xampp configuration. php shown "activated". on xampp page clicking phpinfo gives me: **php version 5.3.5 system windows nt minwinpc 6.1 build 7601 (unknow windows version home premium edition service pack 1) i586 build date jan 6 2011 17:50:45 compiler msvc6 (visual c++ 6.0) architecture x86 configure command cscript /nologo configure.js "--enable-snapshot-build" "--disable-isapi" "--enable-debug-pack" "--disable-isapi" ...

variables - Python global scope troubles -

i'm having trouble modifying global variables between different files in python. example: file1.py: x = 5 file2.py: from file1 import * def updatex(): global x x += 1 main.py: from file2 import * updatex() print x #prints 5 there several important things note here. first, global isn't global. global things, built-in functions, stored in __builtin__ module, or builtins in python 3. global means module-level. second, when import * , new variables same names ones in module import * 'd from, referring same objects. means if reassign variable in 1 module, other doesn't see change. on other hand, mutating mutable object change both modules see. this means after first line of main.py : from file2 import * file1 , file2 , , __main__ (the module main script runs in) have separate x variables referring same 5 object. file2 , __main__ have updatex variables referring updatex function. after second line: updatex() only ...

java - JAXB un-marshaling return null -

i have class following structure @xmlrootelement @xmlaccessortype(xmlaccesstype.field) @xmlseealso({ child.class }) public abstract class parent implements serializable{} and public class child extends parent implements serializable{ private string attribute; private list<string> values = new arraylist<string>() ; } so while marshaling child object saved @ database : <?xml version="1.0" encoding="utf-8" standalone="yes"?> <child > <attribute>age</attribute> <values>1</values> <values>2</values> </child > the problem while un-marshaling object , unmarshal function return null. jaxb.unmarshal(reader, parent.class) could please advise problem , , how solve ? thanks in advance when unmarshalling, must: provide root of xml element marked @xmlrootelement. define classes compliant java beans (get/set methods on attributes). here code worked m...

Translating State Names in Python -

i have list of cities , states in csv: row[0] cities, row[1] full state names. want row[2] (currently empty) state abbreviations. i have list this: name_to_abbr: {"vermont": "vt", "georgia": "ga", "iowa": "ia", ... } how use this? eg (pseudocode) if row[1].upper() == (one of first items in pair sets): row[2] = (the corresponding second item in pair) name_to_abbr dictionary, not list. have several options accessing contents: use try : try: row[2] = name_to_abbr[row[1].upper()] except keyerror: pass use dict.get : row[2] = name_to_abbr.get(row[1].upper(), "") or check keys in : s = row[1].upper() if s in name_to_abbr: row[2] = name_to_abbr[s]

asp.net mvc 4 - ASP MVC default route is not applying for root site url -

i'm having trouble getting asp.net mvc serve default controllers index view root site url http://mysite:8080/ . 404 the resource cannot found . works fine if specify full route path in url : http://mysite:8080/default/index , however, want default route apply if user doesn't specify route path though. seems should work out of gate. fresh project vs2013 mvc 4 template. i've tried both route mappings below , neither seems work. how can achieved? routes.maproute( "root", "", new { controller = "defaultcontroller", action = "index" } ); routes.maproute( name: "default", url: "{controller}/{action}/{id}", defaults: new { controller = "defaultcontroller", action = "index", id = urlparameter.optional } ); here solution problem. it's disappointing default route's defaults not apply root site url though. routes.add(new route("", new siterootro...

c - Printf in inline Assembly -

i trying write inline assebly function exchanges 2 values.( , i'm using extended asm format) this code works: #include <stdio.h> void exchange(int *x, int *y) { printf("in exchange function: before exchange x is: %d\n",*x); printf("in exchange function: before exchange y is: %d\n",*y); asm("xchg %%eax,%%edx\n\t" \ :"+a"(*x),"+d"(*y)); printf("in exchange function: after exchange x is: %d\n",*x); printf("in exchange function: after exchange y is: %d\n",*y); } int main() { int x=20; int y=30; printf("in main: before exchange x is: %d\n",x); printf("in main: before exchange y is: %d\n",y); exchange(&x,&y); printf("in main: after exchange x is: %d\n",x); printf("in main: after exchange y is: %d\n",y); return 0; } but when try wirte in full assembly below segmentation fault (core dumped) error. void exchange(int *x, int *y) { asm("subl $8,%...

java - Spring MVC: No mapping in DispatcherServlet with name mvc-dispatcher -

i new spring , when try access application using below url getting error message - no mapping in dispatcherservlet name mvc-dispatcher http://localhost:8090/springexample/helloworld 1.web.xml <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.dispatcherservlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> 2.mvc-dispatcher-servlet.xml <context:component-scan base-package="com.test" /> <bean class="org.springframework.web.servlet.view.internalresourceviewresolver"> <property name="prefix"> <value>/web-inf/</value> </property> <...

javascript - Conflict with Ember.js and URL fragment (#) with Ecwid -

i'm using ecwid ember.js application, , ran conflict. in short, ecwid loads javascript embeds e-commerce store page. problem ecwid , ember both modify url fragment keep track of state, since ecwid inherently own single page application. basically, have 2 different js libraries fighting on url. so when use ecwid component, url changes ecwid url, , ember complains assertion failed: route !/~/category/id=2104219&offset=0&sort=normal not found because ecwid route, , not ember route. i tried catch-all ember route, didn't work because ember state changes away page i'm on. has had deal 2nd library fights ember on url? if so, how did maintain state , deal other application? pushstate , url fragments become more , more popular, image become more , more relevant. really you're going have choose between two, if both using url routing of nature both rely on notion of base url, changing hash. in ember can disable location routing, lose routing capabilitie...

architecture - Interview: Design Netflix Software Stack -

i asked in interview , didn't know how go answering question. few basic ideas: api calls know stream grab tons of video data stored, need able index provide user movie client-side loading of video seeking 3/4 way ahead during video, how load video there (send api call gives video id, , timing i.e. 1:34:00, , call provide stream there?) any tips on how tackle these type of problems? thanks! it looks example did not specify component in netflix end end solution interested in or if client side or server side. if correct question more see how approach problem this, in case breaking down start. netflix clients run on large variety of devices , there not single software stack across them all. the netflix video distribution side largely dependent on content distribution network (cdn) network gets content close user user can access on regular internet last bit of contents journey. cdn have lots of different software stacks in it. on server or headend side,...

SNMP net-snmp getting different than expected OID translation -

i have rfc1628_ups_mib (ups-mib) , snmpv2-smi (snmpv2-smi) installed on system. i using net-snmp tool snmptrapd receive traps. traps liebert npower ups being translated through snmpv2-smi rather ups-mib expect. i snmpv2-smi::mib-2.33.1.6.3.16 when expecting ups-mib::upsalarmfanfailure some troubleshooting information: # snmptranslate -on ups-mib::upsalarmfanfailure .1.3.6.1.2.1.33.1.6.3.16 # snmptranslate .1.3.6.1.2.1.33.1.6.3.16 snmpv2-smi::mib-2.33.1.6.3.16 it seems both mibs define same oid , lost coin toss. new snmp don't expect have discovered flaw in implementation. can explain happening here or point me resource might? i answering own question. net-snmp use default set of mibs default. adding new mibs mibs directory not enough snmptrapd use new mib. the simplest way of net-snmp tools see new mibs added mib directory add line mibs all snmp.conf . my system did not have default snmp.conf created file /etc/snmp/snmp.conf single...

javascript - When using "destination-in," only the last thing drawn seems to render -

i'm making little library emulate curses-like interface in javascript using bitmap font. font png characters in it, , transparent background. the method i'm using render character follows. draw square on space character going go. square foreground color of character change context.globalcompositeoperation destination-in draw character on square this done in function called putchar . reason, though, last putchar call seems render. in following jsfiddle, i've removed library except what's needed reproduce issue. putchar called in lines 56, 57, , 58. should render yellow "a", green "b", , blue "c" in row. third putchar call rendered (the blue "c".) http://jsfiddle.net/r96lh/3/ this first time using composite operations, must missing something. know why might happening? from http://www.html5canvastutorials.com/advanced/html5-canvas-global-composite-operations-tutorial/ it's important note canv...

Echoed, embedded php within javascript -

summary currently have webpage in running javascript allow user create ul list. want process list, saving file on server need done php of course. goal the overall goal hoping solve how embed php within javascript. keep in mind javascript being echoed html page surrounded single quotes of course. what have tried function test(){ var ul = document.getelementbyid("playlist"); var playlist = ""; (i = 1; < ul.children.length; i++){ var item = ul.childnodes[i]; playlist += item.innerhtml + string.fromcharcode(13); } playlist = playlist.slice(0, -1); jsvar = \'<?php echo $playlist;?>\'; alert(jsvar); } the variable playlist generated fine. @ end trying simple playlist variable. simply, now, trying pass playlist variable int php script echo variable me display alert. the above code result in popup box has literal displayed. reason isn't recognizing php script rather treating string.. missing simple or totally obvious? i have loo...

How to convert uint64_t to const char * in C++? -

i have 1 method accepts const char * shown below - bool get_data(const char* userid) const; now below loop in need call get_data method passing const char * . below loop uses uint64_t . need convert uint64_t const char * , pass get_data method. for (tmpidset::iterator = userids.begin(); != userids.end(); ++it) { // .. code // convert const char * mpl_files.get_data(*it) } here tmpidset typedef std::set<uint64_t> tmpidset; so question how should convert uint64_t in above code const char * ? one way convert first std::string using std::to_string , access raw data using std::string::c_str() member function: #include <string> .... uint64_t integer = 42; std::string str = std::to_string(integer); mpl_files.get_data(str.c_str());

php - Converting RAW to JPEG (attempting to use) ImageMagick -

i not care if solution converts raw jpegs uses imagemagick or not, appeared doucmented, started there. i have had success converting jpeg different sized jpeg, have been unable convert raw jpeg. after looking @ convert raw photos jpeg in linux/php , tried code: try { $im = new imagick($inputurl); $im->setimageformat("jpg"); $im->writeimage($outputurl); $im->clear(); $im->destroy(); } catch (exception $e) { echo $e; } and received error: exception 'imagickexception' message 'unable open image `/tmp/magick-xxaana6q.ppm': no such file or directory @ blob.c/openblob/2480' in /upstream/public_html/core/functions.php:116 stack trace: #0 /upstream/public_html/core/functions.php(116): imagick->__construct('/upstream/p...') #1 /upstream/public_html/core/functions.php(129): resizeimage('/upstream/p...', '/upstream/p...', array) #2 {main} i tried: exec("/usr/bin/convert -define jpeg:...