Posts

Showing posts from May, 2012

ios - JSON parsing is not working -

im trying parse , show json content in tableviewcell, goes wrong. json here: http://bumpee.net/xcode/index.php -(void)connectiondidfinishloading:(nsurlconnection *)connection { nsdictionary *json = [nsjsonserialization jsonobjectwithdata:webdata options:0 error:nil]; nsarray *arr = [json objectforkey:@"feed"]; for(nsdictionary *aaa in arr) { nsdictionary *one = [aaa objectforkey:@"1"]; nsstring *oneprint= [one objectforkey:@"name"]; [array addobject:oneprint]; } [[self tableview ] reloaddata]; } the problem arr nsdictionary not nsarray , when iterate on with for (nsdictionary *aaa in arr) [...] you go through nsstring keys, , not values.

angularjs - By enabling $http cache, what response time should be expected after initial requests? -

Image
i've got {cache:true{ $http requests. know if enabled, data returned asynchronously, though, find response times surprisingly long. i'd know if normal, or more clear, shouldn't expected initial request response time higher same (but next) request response time ? for example, cache enabled both $http requests: /foo/api/yellow this returns data, after promise resolved, taking 3 seconds. expect cached angularjs, since i've enabled cache. after few moments, new request made: /foo/api/yellow this returns data, though supposedly cached in first request, response time same or higher 3 seconds. said, know though cache true, data returned asynchronously response times normal, or there wrong ? if normal, guess best thing do, create new service, save cached data , check if data there , synchronously maybe ? my current code looks this, first request: $http.get(mysettings.apiurl + '/foo/api/yellow', { cache: true }); the second request same! i&#

windows 8 - Crop image with rectangle -

Image
i have image , want crop using rectangle, code below code put image , draw rectangle @ middle of image: mainpage.xaml: <canvas x:name="canvas" horizontalalignment="center" verticalalignment="center" width="340" height="480" background="blue"> <image x:name="photo" horizontalalignment="center" verticalalignment="center" manipulationmode="all"> <image.rendertransform> <compositetransform/> </image.rendertransform> </image> <path stroke="black" strokethickness="1"> <path.data> <rectanglegeometry rect="0,0,340,480"/> </path.data> </path> </canvas> i successful display image , draw rectangle. sample image below: now want click button crop image within rectangle(not a

jsf - JSF2.0, value="#" means? -

i have been trying write component control in <rich:datatable> . chose <h:outputlink> wrap it, inside data table. found this. <h:outputlink id="openlink" value="#"> what value="#" mean? it's link same page. refresh page in non-ajax mode. the outpulink tag produces simple html tag href value set value of the...'value' attribute. in asker example produce: <a id="openlink" href="#"> . . . </a> i added tag closure if corresponding missing in op question.

Different android version bug -

i've got simple app status bar icon. when user minimize app, status bar icon appear. when user click on icon, app should resume , continue job. i've tested on android 2.3.4 , works on 4.0 android version app not resuming , continue job open new version of app. how make universal noticifaction code , don't worry of android version? public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_jajko); text = (textview) findviewbyid(r.id.tvtime); play = (button) findviewbyid(r.id.butstart); miekko = (button) findviewbyid(r.id.butmiekko); srednio = (button) findviewbyid(r.id.butsrednio); twardo = (button) findviewbyid(r.id.buttwardo); miekko.setonclicklistener(this); srednio.setonclicklistener(this); twardo.setonclicklistener(this); play.setonclicklistener(this); mp = mediaplayer.create(jajko.this, r.raw.alarm); shownotification(this); } public static void sh

multithreading - How to create a subclass of thread Class properly in C++(subclass of std::thread) -

i trying create class parallel subclass of std::thread ,therefore class defined in parallel.h ,but main method defined in separate file main.cpp in same project(in visual studio).when create instance of parallel , execute join() function in main() method below code segment: new c++, here "parallel.h"- #include<thread> using namespace std; namespace para{ class parallel:thread { public: static void run(){ } parallel(void) { } virtual ~parallel(void) { } inline static void start(parallel* p){ // (*p).join(); } virtual void parallel::start(thread& t){ } static void parallelize(parallel& p1,parallel& p2){ } inline virtual parallel* operator=(thread* t){ return static_cast<parallel*>(t); } } //in main.cpp void main(){ parallel p; p.join(); thread t(print); t.join(); system("pause"); } problem how define proper su

javascript - Unittesting dependant tests -

i've searched site , literature , couldn't clear answer. i'm trying learn unittesting while constructing new webpage works whiteboard can add post-its. i have canvas object represents whiteboard, , ticket object represent post-its. have (for now) global function retrieve 1 , canvas, test this: this.testretrievecanvas = function() { var canvas = getcanvas(); this.asserttrue( canvas != null ); } this.testcanvastype = function() { var canvas = getcanvas(); this.asserttrue( canvas instanceof canvas ); } this.testifcanvasisreused = function() { var canvas = getcanvas(); this.assertequals( canvas, getcanvas() ); } so, test 3 things: does method return canvas? is acutal canvas? does method give me same canvas always? no problems far. little later, i'm testing "adding ticket canvas": this.testaddtickettocanvas = function() { var ticket = factory.createticket("yellow"); var canvas = getca

ios - Calculating Cumulative elevation gain give me wierd results -

i have app use corelocation , track user movement. when user walking or driving save each coordinate local database (lat/lng/alt) can draw route based on saved coordinates. few days ago have added cumulative elevation gain , use code in didlocationupdate: - (void)locationmanager:(cllocationmanager *)manager didupdatetolocation:(cllocation *)newlocation fromlocation:(cllocation *)oldlocation { netelevationgain += max(0, oldlocation.altitude - newlocation.altitude); } but wrong. started application , start walking , walking around few miles , netelevationgain 500 meters. no way it's correct. list of netelevation saved in database each point: 0,41,43,44,47,52,55,62,73,80,91,100,114,140,146,153,159,180,199,208,228,240,259,275,320,329,349,359,366,375,381,392,408,419,428,437,446,449,462,469,478,486 altitudes 0.000000,181.678055,181.891495,182.786850,179.315399,177.035721,182.636307,181.259399,178.653015,192.552551,185.398819,182.693436,181.369766,154.306747,157.0

php - How can I sort the substrings of an array of strings -

i have array of strings this: array 0 => string 'cheese=french' 1 => string 'pizza=large&cheese=french' 2 => string 'cheese=french&pizza=small' 3 => string 'cheese=italian' i need sort each substring (divided &) in string in array alphabettically. example: pizza=large&cheese=french should other way around: cheese=french&pizza=large, 'c' comes before 'p'. i thought explode original array this: foreach ($urls $url) { $exploded_urls[] = explode('&',$url); } array 0 => array 0 => string 'cheese=french' 1 => array 0 => string 'pizza=large' 1 => string 'cheese=french' 2 => array 0 => string 'cheese=french' 1 => string 'pizza=small' 3 => array 0 => string 'cheese=italian' and use sort in foreach loop, like: foreach($exploded_u

android - Don't understand viewpager life cycle with fragment -

i'm little bit dissapointed viewpager fragments, since 4 days try many solutions, without sucess. i 'm beginner in fragments, follow great tutorial create viewpager. can rotate phone no problem fragments. must open new activity fragment within viewpager , go on host activity contain viewpager. in point can't fragment host activity when go fron activity b. don't understand can ? exemple : tabsessionactivity --> fragment --> activity b --> tabsessionactivity(fragment =null) tabsessionactivity --> fragment -->rotate phone --> tabsessionactivity(fragment ok!) here adapter : public class mypageradapter extends fragmentpageradapter { private final list<fragment> fragments; private fragmentmanager mfragmentmanager; // on fournit à l'adapter la liste des fragments à afficher public mypageradapter(fragmentmanager fm, list<fragment> fragments) { super(fm); mfragmentmanager=fm; this.fragm

javascript - getElementsByClassName() is not working -

this question has answer here: what queryselectorall, getelementsbyclassname , other getelementsby* methods return? 7 answers the follwing code sort form list options alphabetically 'getelementsbyclassname()' not working , cant figure out why. i using latest jquery. window.onload=function(){ function sortlist() { var cl = document.getelementsbyclassname('car_options'); var cltexts = new array(); for(i = 1; < cl.length; i++) { cltexts[i-1] = cl.options[i].text.touppercase() + "," + cl.options[i].text + "," + cl.options[i].value; } cltexts.sort(); for(i = 1; < cl.length; i++) { var parts = cltexts[i-1].split(','); cl.options[i].text = parts[1]; cl.options[i].value = parts[2]; } sor

xml - Getting youtube data with python -

how url views in youtube? here link using, " http://gdata.youtube.com/feeds/api/videos?q=gangnam%20style " it returns xml data, how elements of this? module use return gdata link go viewed video? appreciated thank you. problem not know how elements why i'm asking , thank ahead of time. edit: thank answerd after hour or on google found way appreicate of suggestions, in few hours when can answer own question i'll post it use lxml . for example, following code prints titles, view counts: import lxml.etree tree = lxml.etree.parse('http://gdata.youtube.com/feeds/api/videos?q=gangnam%20style') root = tree.getroot() nsmap = root.nsmap nsmap['xmlns'] = nsmap.pop(none) entry in root.findall('.//xmlns:entry', namespaces=nsmap): title = entry.find('xmlns:title', namespaces=nsmap).text view_count = entry.find('yt:statistics', namespaces=nsmap).get('viewcount') print(u'{} {}'.format(title,

matrix - Rotating arbitrary plane to be z-axis-aligned -

correct me if i'm wrong, but... given normal of arbitrary source plane, , normal of plane after applying desired rotation: vector3f sourcenormal = (x, y, z).normalize() vector3f desirednormal = (0, 0, 1).normalize() 1) can find "axis of rotation" through cross-product of 2 normals vector3f rotationaxis = vector3f.cross(sourcenormal, desirednormal).normalize() 2) can find "angle of rotation" through arc-cosine of dot product of 2 normals. // nico - there in project source, omitted here. float theta = math.acos(vector3f.dot(sourcenormal, desirednormal)) 3) can apply rotation set of points in order orient source plane our desired plane. float[] rotationmatrix = new float[16]; // x component rotationmatrix[5] = rotationmatrix[10] = (float)math.cos(theta); rotationmatrix[9] = (float)math.sin(theta); rotationmatrix[6] = -rotationmatrix[9]; // y component rotationmatrix[0] = rotationmatrix[10] = (float)math.cos(theta); rotationmatrix[2] = (float)m

c# - Registry.CurrentUser.OpenSubKey -

ok, having particularly bad day , can't seem figure out why line of code not returning results should be. registrykey rksubkey = registry.currentuser.opensubkey(@"\software\<<path key>>", false); the value written registry form 2 text boxes, writes should , there value in registry , cannot life of me see why rksubkey returning null value. i read on msdn forums related 64 bit software accessing 32 bit registry .. in app settings 32 bit preferred. any appreciated. the problem in leading backslash, delete :) registrykey rksubkey = registry.currentuser.opensubkey(@"software\<<path key>>", false);

python - Django 1.5 (MEDIA_ROOT, TEMPLATE_DIRS) -

i'm new django (1.5) , i'm having hard time relative configuration of media folder in media_root. can't charge files .css, .js, .jpg in project. receive following msg in shell: [06/oct/2013 19:12:01] "get /media/css/style.css http/1.1" 404 4140 this tree of project: _3ms _3ms apps media css js images template this configuration setting.py media_root = os.path.join(os.path.dirname(__file__), 'media/') media_url = '/media/' static_root = '' static_url = '/static/' staticfiles_dirs = ( ) staticfiles_finders = ( 'django.contrib.staticfiles.finders.filesystemfinder', 'django.contrib.staticfiles.finders.appdirectoriesfinder', # 'django.contrib.staticfiles.finders.defaultstoragefinder', ) template_loaders = ( 'django.template.loaders.filesystem.loader', 'django.template.loaders.app_directories.loader', # 'django.template.loaders.eggs.load

Python 2.7: Unable to catch exception -

i have following code: def distributemembersfile(members): node in members: node = node.strip() # strip trailing \n if node == socket.hostname(): # no need send file continue conn = none try: s = socket.socket(socket.af_inet, socket.sock_stream) s.connect((node, port)) # todo: can possibly update list of members here s.sendall('dwld') s.recv(4) except socket.error, msg: logging.info(msg) finally: if s: s.close() now, question though s.connect() in try except socket.error block, exception not being caught. see following traceback on console: s.connect((node, port)) file "<string>", line 1, in connect error: (111, 'connection refused') interestingly, in other places have same try except socket.error block, , particular (connection refused) error caught as: info (111, 'c

ember.js - Model Not Found in Ember App Kit -

i'm trying use ember app kit ember data (i'm using latest of both) using fixtures - reason i'm getting following: assertion failed: no model found 'todo' [vm] ember.js (4005):415 error while loading route: typeerror {} [vm] ember.js (4005):415 uncaught typeerror: cannot set property 'store' of undefined ember-data.js:2182 application import resolver 'resolver'; import registercomponents 'appkit/utils/register_components'; var app = ember.application.extend({ log_active_generation: true, log_module_resolver: true, log_transitions: true, log_transitions_internal: true, log_view_lookups: true, moduleprefix: 'appkit', // todo: loaded via config resolver: resolver }); app.initializer({ name: 'register components', initialize: function(container, application) { registercomponents(container); } }); app.applicationadapter = ds.fixtureadapter.extend(); export default app; index route import

how can i delete records if two columns match mysql php -

my problem want delete 1 record on table "provicional" if "id" , "password" match... have simple code work id , want delete if both match! $sql = "delete `provicional` `id` in ('3','basico')"; many a not popular way of doing in mysql be: delete provicional (id, password) = (3, 'basico') note can add more 2 elements in each list. tip: not use apostrophes ' around numeric fields.

python - Indexing form the end of a generator -

say have generator in python , want iterate on in except first 10 iterations , last 10 iterations. itertools.islice supports first part of slicing operation, not second. there simple way accomplish this? not there not simple way, there not way @ all, if want allow generator (or iterable). in general, there no way know when 10 items end of generator, or whether generator has end. generators give 1 item @ time, , tell nothing how many items "left". have iterate through entire generator, keeping temporary cache of recent 10 items, , yield when (or if!) generator terminates. note "or if". generator need not finite. infinite generator, there no such thing "last" 10 elements.

split - splitting comma separated mixed text and numeric string with strsplit in R -

i have many strings of form name1, name2 , name3, 0, 1, 2 or name1, name2, name3 , name4, 0, 1, 2 , split vector 4 elements first 1 whole text string of names. problem strsplit doesn't differenciate between text , numbers , split string 5 elements in first case , 6 elements in second example. how can tell r dynamically skip text part of string variable number of names? you have 2 main options: (1) grep numbers, , extract those. (2) split on comma, coerce numeric , check na s i prefer second splat <- strsplit(x, ",")[[1]] numbs <- !is.na(suppresswarnings(as.numeric(splat))) c(paste(splat[!numbs], collapse=","), splat[numbs]) # [1] "name1, name2 , name3" " 0" " 1" " 2"

ios - UINavigationItem - no "free" backbutton for one of my buttons -

so in main window have these 2 buttons "settings"(leftbarbuttonitem) & "i"(info button,rightbarbuttonitem)" when press info button "free" button, have create 1 programmatically settings button? why that? here how programmed buttons in viewdidload uibarbuttonitem *settingsbarbuttonitem =[[uibarbuttonitem alloc]initwithtitle:@"settings" style:uibarbuttonitemstylebordered target:self action:@selector(settings:)]; self.navigationitem.leftbarbuttonitem = settingsbarbuttonitem; uibutton* infobutton = [uibutton buttonwithtype:uibuttontypeinfolight]; cgrect frame = infobutton.frame; frame.size.width = 40.0f; infobutton.frame = frame; [infobutton addtarget:self action:@selector(about:) forcontrolevents:uicontroleventtouchupinside]; butinfo = [[uibarbuttonitem alloc] initwithcustomview:infobutton]; self.navigationitem.rightbarbuttonitem = butinfo; how viewcontroller invoked? in general "free" button happens if view c

symfony - FOSUserBundle Entity with ManyToOne relation -

i have abstractuser super class extends fosuser, have entities extends abstractuser fields related class. instance customer has manytoone relation city entity. now when try log-in fosuser login form i'm getting error: .... sqlstate[42s22]: column not found: 1054 unknown column 't0.city' in 'field list' of course there no city field in users table because it's relation column named city_id. can shed light me why doctrine builds query this? missing ? thanks in advance. here related code parts. abstractuser: /** * @orm\table(name="users") * @orm\entity * @orm\mappedsuperclass * @orm\inheritancetype("single_table") * @orm\discriminatorcolumn(name="discr", type="string") * @orm\discriminatormap({"admin"="admin", "customer"="customer", "seller"="seller"}) */ abstract class abstractuser extends fosuser { /** * @orm\column(name="id&q

bash - Redirected output is interpreted when file is given as a variable -

when following within bash script file: #!/bin/bash echo -e $line >> 2.txt ... $line written inside 2.txt file without troubles. however, if use variable file this: #!/bin/bash file='2.txt' echo -e $line >> $file ... escaped \$ interpreted , in file '$' character written. outside of bash script file (in bash console) both codes work. know why? not information on on internet.

javascript - Ways to circumvent the same-origin policy -

the same origin policy i wanted make community wiki regarding html/js same-origin policies searching topic. 1 of searched-for topics on , there no consolidated wiki here go :) the same origin policy prevents document or script loaded 1 origin getting or setting properties of document origin. policy dates way netscape navigator 2.0. what of favorite ways go around same-origin policies? please keep examples verbose , preferably link sources. the document.domain method method type: iframe . note iframe method sets value of document.domain suffix of current domain. if so, shorter domain used subsequent origin checks. example, assume script in document @ http://store.company.com/dir/other.html executes following statement: document.domain = "company.com"; after statement executes, page pass origin check http://company.com/dir/page.html . however, same reasoning, company.com not set document.domain othercompany.com . with method,