Posts

Showing posts from June, 2012

php - How can I tell if someone is subscribed with a Paypal Subscribe Button? -

so have paypal subscribe button set on test website. it's monthly subscription user have pay gain access profile. can't seem logic right in head. might lack of knowledge paypal classic api's, i've searched has led me dead end. using php , mysql, how keep track of user , make sure subscribed and/or if cancel subscription? may lead me solving this, appreciate it. if need of code, i'll glad add , edit, don't know if code needed question.

Using HTML5/Javascript to generate and save a file -

i've been fiddling webgl lately, , have gotten collada reader working. problem it's pretty slow (collada verbose format), i'm going start converting files easier use format (probably json). thing is, have code parse file in javascript, may use exporter too! problem saving. now, know can parse file, send result server, , have browser request file server download. in reality server has nothing particular process, why involved? have contents of desired file in memory. there way present user download using pure javascript? (i doubt it, might ask...) and clear: not trying access filesystem without users knowledge! user provide file (probably via drag , drop), script transform file in memory, , user prompted download result. of should "safe" activities far browser concerned. [edit]: didn't mention upfront, posters answered "flash" valid enough, part of i'm doing attempt highlight can done pure html5... flash right out in case. (though it'

linux - bash script fails when password contains backtick -

a colleague wrote script acts wrapper executing other scripts remotely. set ask password echo 'ed remote systems use in sudo . relevant code*: read -s pw .... ${ssh_tt} ${host} "echo ${pw} | ${sudo_s} ./${script_name} > ${home}/${host_output}" 2> /dev/null * please ignore upper-case variables. if enter password contains backtick following error: bash: -c: line 0: unexpected eof while looking matching ``' bash: -c: line 1: syntax error: unexpected end of file if change password 1 not contain backtick script runs fine. imagine happen passwords contain single- , double-quotes well. while changing password option not desirable due size of our platform (we don't use centralized authentication). i'm wondering if there way sanitize or otherwise escape backtick isn't interpreted shell either locally or remotely. you can escape password before execute last line. in bash: escaped_pw=`printf "%q" ${pw}` then use escape

php - How do I create a complex left outer join in Yii2? -

how perform query in yii2? select `keyword`.`id`, `keyword`, `volume`, `cpc`, `competition`, `keyword_id` `keyword` left join `ad_group_keyword` on keyword.id = ad_group_keyword.keyword_id , ad_group_id = 1 ((`keyword_id` null) , (not (`volume` null))) , (not (`cpc` null)) order volume desc limit 1; i tried following , many combinations can't on part right. $kw = keyword::find()->select(['keyword.id', 'keyword', 'volume', 'cpc', 'competition', 'keyword_id'])-> leftjoin('ad_group_keyword', 'keyword.id = ad_group_keyword.keyword_id', ['ad_group_id'=>1])-> andwhere(['keyword_id'=>null])-> andwhere(['not', ['volume' => null]])->andwhere(['not', ['cpc' => null]])-> orderby('volume desc')->asarray()->limit(1)->all(); the above generates sql, missing second condition of on : select keyword

angularjs - Mocking API with httpBackend [Protractor] -

i'm developing frontend app rest api. i'm using protractor end-to-end tests api mocked out. able mock authtoken api response , navigate chosen url, page displayed under destined url renders empty. here's code: describe('e2e tests', function() { it('fo tests', function() { browser.addmockmodule('webclientapp', function() { console.log('test'); angular.module('webclientapp', ['ngmocke2e']) .run(function($httpbackend) { console.log('test2'); $httpbackend.whenpost('http://0.0.0.0:9000/api/organizations').respond(200); $httpbackend.whenpost('/api/auth/get_resource_by_token').respond(200); $httpbackend.whenget('/api/auth/current_resource').respond(200); $httpbackend.whenget(/.*/).respond(200); }); }); browser.getregisteredmockmodules(); browser.get('http://0.0.0.0:9000/#/organizations/profile'); browser.pause(); }); }); sadly, protractor console not pr

How to convert a set of 4 rows to columns in MySQL? -

Image
i have mysql question, , have no idea how resolve it. i have following query: select p.nombre, ti.tallerhorario_id persona p, talleresinscritos ti p.pasaporte = ti.pasaporte at result this: i'm looking make query in second column doesn't show row every "tallerhorario_id", every "nombre". for example: euclides | 7 | 24 | 32 | 48 liz lorena | 4 | 18 | 33 | 47 every person have 4 rows associated, without exceptions. could me please? thank you! the simplest method put values in 1 column, using group_concat() : select p.nombre, group_concat(ti.tallerhorario_id) persona p join -- learn use proper explicit join syntax talleresinscritos ti on p.pasaporte = ti.pasaporte group p.nombre; a comma-delimited list not asked for, might solve problem. if have counter, 1, 2, 3, , 4, second table, can using conditional aggregation: select p.nombre, max(case when counter = 1 ti.tallerhorario_id end) id1, max(

swift - Change CGSize with a variable -

i want change size of sknode variable can made smaller loop. giving me error: cannot find initializer type 'cgsize' accepts argument list of type '(width:... , height:...)' for (var = 0.9; > 0.0; -= 0.1){ (var k = 1.25; > 0.0; -= 0.1){ self.sun.size = cgsize(width: self.size.width * i, height: self.size.height * k) // error here } } i ran skaction code instead of loop suggested abakersmith , looks lot cleaner. var shrinksun = skaction.scaleby(0.5, duration: 2) self.sun.runaction(shrinksun)

python - How is Levenshtein Distance calculated on Simplified Chinese characters? -

i have 2 queries: query1:你好世界 query2:你好 when run code using python library levenshtein: from levenshtein import distance, hamming, median lev_edit_dist = distance(query1,query2) print lev_edit_dist i output of 12. question how value 12 derived? because in terms of strokes difference, theres more 12. according documentation , supports unicode: it supports both normal , unicode strings, can't mix them, arguments function (method) have of same type (or subclasses). you need make sure chinese characters in unicode though: in [1]: levenshtein import distance, hamming, median in [2]: query1 = '你好世界' in [3]: query2 = '你好' in [4]: print distance(query1,query2) 6 in [5]: print distance(query1.decode('utf8'),query2.decode('utf8')) 2

c# - Dealing with cumbersome string.Split overloads? -

the string.split() in .net can cumbersome use. many overloads must specify array when passing single delimiter (in fact 1 overload marked params). is there such alternative? there way of accomplishing task without creating arrays. the issue there 2 conflicting best practices in developing such api(they both practices , not conflict except in particular case): only params parameter can/ must appear last parameter. overloads of function should maintain same parameter ordering. so have first overload: split(params char[] separator) which leverages params keyword don't explicitly need create array done implicitly. the other overloads follow second guideline, maintaining separator parameter first parameter, therefore cannot specify params keyword since can appear on last parameter. so it's design choice balanced between 2 best practices. in case, followed maintain-parameter-order guideline, , did not use params keyword on other overloads becaus

osx - Difference between symlink and alias -

i trying set opening sublime text editor terminal on mac os. when searching found out 1 way that: create soft link (symlink) , change path in .profile ln -s /applications/sublime\ text\ 2.app/contents/sharedsupport/bin/subl /usr/local/bin/sublime since path did not change in .profile added alias sublime=' open /applications/sublime\ text\ 2.app/contents/sharedsupport/bin/subl' could please tell me difference between these ways?which way better?how change path terminal not opening .profile?

osx - Get URL from active Firefox session with Swift or Objective C -

is possible retrieve url active firefox session swift or objective-c. far able retrieve name of actual tab applescript not url. what right way? not without installing selenium (or, perhaps, selenium), afaik. if use selenium, can use various languages "webdriver"'s current_url property. without selenium, if want kind of clunky (but effective), can use system events (applescript) command-l (ell) command-c highlight url field , copy clipboard, access that.

Replacing missing data with the mean of a subgroup in R -

i have table in there missing data i'd replace mean of other, related data, based on conditions. have toy data show problem below: var1 var2 var3 123.1 2.1 113 166.5 2.1 113 200.3 2.1 112 na 2.1 113 na 2.1 na 212.1 3.3 112 ... ... ... what i'd able to fill in na values var1 mean of va1 in case both have same var2 , var3 . ie, first na in var1 column, matches on both var2 , var3 1st , 2nd entries, value of (123.1 + 166.5) / 2 . the second na in var1 column missing var3 information given mean of other var1 values var2 = 2.1. i'm relatively new r , can't seem conditional logic correct - in advance! what i'd able to fill in na values var1 mean of var2 in case both have same var3. hmm... don't think that's want, that: means <- tapply(var2, var3, mean, na.rm=t) var1[is.na(var1)] <- means[match(var3[is.na(var1)], sort(unique(var3)))]

javascript - Loading libraries and additional modules with requirejs -

i'm struggling understand how load external library , additional module using requirejs. this have: this works ok, doesn't seem right me: requirejs.config({ paths: { highcharts: 'http://localhost:3000/hicharts/js/highcharts' } }); requirejs.config({ paths: { exporting: 'http://localhost:3000/hicharts/js/modules/exporting' } }); i sort of expecting have worked: require.config({ paths: { highcharts: 'http://localhost:3000/hicharts/js/highcharts', exporting: 'http://localhost:3000/hicharts/js/modules/exporting' } }); but doesn't seem expose exporting module, though gets called web server. missing here, , know documented ? can't seem find discusses it. there highcharts npm package contains highcharts, highstock , highmaps plus modules. start installing highcharts node module , save dependency in package.json: npm install highcharts --save load require: var highcharts = requir

java - Take an array of objects and turn into array of strings? -

i trying convert array of objects array of strings inside loop. i extracting property object title inside loop have several title strings, want pass new array? jsonarray shots = response.getjsonarray("shots"); (int i=0; < shots.length(); i++) { // play data jsonobject post = shots.getjsonobject(i); string title = post.getstring("title"); // turn title array of strings?? } edit: i tried this string[] mstrings = new string[15]; jsonarray shots = response.getjsonarray("shots"); (int i=0; < shots.length(); i++) { // play data jsonobject post = shots.getjsonobject(i); string title = post.getstring("title"); //log.d("this array", "arr: " + title); mstrings[i] = title; } log.d("this array", "arr: " + mstrings); the result of log.d d/this array﹕ arr: [ljava.lang.string;@4294e620 if understand question correctly: want array titles json sho

PHP don't return number by jquery ajax -

Image
i unable solve problem , have no idea i'm doing wrong i got php file called gettotalprotocolobyfilter.php <?php require_once(dirname(__file__).'/../datos/conexionmssql.class.php'); try { $conexionmssql = conexionmssql::getinstance(); $query="select count(1) total protocolos_web_new tipo = ".$_post['tipo']; $conexionmssql->abrir('ingcer_bd'); $result = $conexionmssql->consulta($query); $conexionmssql->cerrar(); $total=new stdclass(); while ($row = mssql_fetch_object($result)) { echo json_encode($row->total); } } catch (exception $e) { error_log($e->getmessage()); } ?> and js function: var gettotalprotocolosbyfilter = function(filter){ total=0; $.ajax({ url: '/protected/functions/gettotalprotocolosbyfilter.php', type: 'post', async:false, datatype: 'json', data:

javascript - How to reload the page on the scroll event? -

i'm trying reload page on scroll event, condition works other methods not window.location.reload() why not functioning intended? var $searchbox = $('#searchbox'); var $the = $(window); $the.on('resize', function() { if($searchbox.is(':focus')) { if($the.width() > 940) { window.location.reload(true); }; } }); i not have 50 reputation have use answer field. i uploaded code here: jsfiddle html: <input type="text" id="searchbox" /> css: #searchbox { width: 100%; } #searchbox:focus { background: #000; } javascript var $searchbox = $('#searchbox'); var $the = $(window); $the.on('resize', function() { if($searchbox.is(':focus')) { if($the.width() > 940) { // alert('page reloading'); window.location.reload(true); }; } }); your code works fine if focus input box , pull left border left side page big

osx - Jenkins web download corrupts mac app code signing -

i'm seeing bizarre code-signing / file-transfer issue , haven't found clue cause, wonder if else has idea. i have mac os x build server running jenkins builds , signs mac components , apps fine. these include apps final cut pro x plugins. when download zip file produced build system through browser (from jenkins build page) these fcpx apps, after unzipping app won't launch - says it's unknown developer, if isn't code signed. and yet if same build output zip way - downloading via sftp or afp-mounting build machine filesystem - works fine. it code-signed on build system originally, because installer (which built downstream on build system) deploys app code-signed. why downloading zip through browser jenkins destroy app's code signature? i've tried few browsers (chrome, firefox, safari) , it's same. i'd suspect it's issue app bundle bits or sim. except download wrapped in zip archive shouldn't matter. it's created os-native /us

Is there a way to query when the latest rally milestone revision occurred with rallyrestapi? -

i trying find creation date of changes milestones in rally, seems possible because column under milestone's revision history, creation date not child of revisions or revision history. is there alternative object should try querying for? the revision type have creationdate field (it's inherited base type, workspacedomainobject). if load revisions collection of revisionhistory associated milestone should have it. returned chronologically, first revision recent change.

How to do a calculation on Python with a random operator -

i making maths test each question either adding, multiplying or subtracting randomly chosen numbers. operator chosen @ random, cannot work out how calculate operator. problem here: answer = input() if answer ==(number1,operator,number2): print('correct') how can make operator used in calculation. example, if random numbers 2 , five, , random operator '+', how code program end doing calculation , getting answer, in case be: answer =input() if answer == 10: print('correct') basically, how can calculation check see if answer correct? full code below. import random score = 0 #score of user questions = 0 #number of questions asked operator = ["+","-","*"] number1 = random.randint(1,20) number2 = random.randint(1,20) print("you have reached next level!this test of addition , subtraction") print("you asked ten random questions") while questions<10: #while have asked less ten questions ope

python - seaborn barplot() output figure is overwritten -

i using following lines of code plot couple of seaborn bar graphs in jupyter notebooks sns.set(style="darkgrid") rcparams['figure.figsize'] = (12, 8) bar_plot = sns.barplot(x='country',y='average rate',data=pddf1, palette="muted", x_order=pddf1["country"].tolist()) abc = bar_plot.set_xticklabels(pddf1["country"],rotation=90) sns.set(style="darkgrid") rcparams['figure.figsize'] = (12, 4) bar_plot = sns.barplot(x='country',y='% jobs completed',data=pddf2, palette="muted", x_order=pddf2["country"].tolist()) abc = bar_plot.set_xticklabels(pddf2["country"],rotation=90) where pddf variables panda dataframes constructed lists. if comment out 1 set of statements, other graph plotted correctly. however, if both of them run together, both graphs drawn @ same axes. in other words, first 1 overwritten second one. sure because see longer bars first graph sho

java - Convert String to the name of a array in another class -

i'm amateur programmer , i'm wondering if it's possible solve problem in specific way. public class stats { public static int[] hero = {20, 20, 10, 10, 10}; public static int[] villain = {20, 20, 10, 10, 10}; public static void name(int[] name) { //if insert array print values system.out.println("health: " + name[1] + "/" + name[0]); system.out.println("damage: " + name[2]); system.out.println("defense: " + name[3]); system.out.println("agility: " + name[4]); return; } this want use , if call on using 'hero' or 'villain' works fine. public class userinterface extends jpanel implements mouselistener, mousemotionlistener { //a lot of code in between not of notice right @override public void mouseclicked(mouseevent e) { if (" ".equals(chess.board[e.gety() / squaresize][e.getx() / squaresize]) == false) { //checks if p

retrieve different values from a single string with regular expressions and python -

suggest have this: valuestringdate = "24/6/2010" and want variable day = 24 month = 6 year = 2010 use .split() method. in case, datelist = valuestringdate.split("/") produce list: datelist = ["24","6","2010] using indexes: day = datelist[0] set day = "24" from there can use day = int(day) convert day string integer. you should able figure out there.

Simple Python program to create numeric values based on Unicode values, would like tips to streamline my code -

print("this program calculate numeric value of name given input.") name = input("please enter full name: ") name_list = name.split(' ') name_list2 = [] x in name_list: y = list(x) x in y: name_list2.append(x) print(name_list2) num_value = 0 x in name_list2: y = ord(x) print("the numeric value of", x, "is", y) num_value = num_value + y print("the numeric value of name is: ", num_value) any tips on how simplify appreciated, knowledge couldn't see easier way split list, split out each character (to avoid adding in whitespace value of 32), , add them up. you can iterate on name , sum ord's of each character excluding spaces count if not ch.isspace() : name = input("please enter full name: ") print("the numeric value of name is: ", sum(ord(ch) ch in name if not ch.isspace())) if want see each letter use loop: name = input("please enter full name: &q

performance - VS2010- app runs super slow in debugger on new PC -

i maintain c#/wpf app controls industrial processes, using visual studio 2010. got new windows 7 pc replace old xp clunker had been using. on old pc there no noticeable difference in performance whether run app via start without debugging or start debugging . operation took 5 seconds in 1 case took 5 seconds in other. on new pc running via start debugging 25x slower, i.e., 5 second operation takes on 2 minutes! making debugging tedious. how analyze why running in visual studio debugger slower on new pc? new pc in every respect higher-performance pc - quad-core, faster memory bandwidth, bigger cpu caches, etc. i'm assuming it's settings of visual studio. can't compare them since i've uninstalled vs2010 old pc. try adding "~visualstudio directory~\common7\ide" in exclusions in antivirus. improve performance, try run registry cleaner , clear temporary files.

qlikview query taking long time to execute -

i loading data in qlikview through flat file, data loaded in table called imported. table imported table called transaction_details loads data. the query using transaction_details: load key, line_number, key&line_number line_key, currency, exchrate, account, [account text], [cost ctr], [wbs element], [line text], [tc amount], [lc amount], [d/c], [tax code], [account type], cocode resident imported ; after want calculations in table , join main table transaction_details the table have created calculations called sums: sums: load distinct key resident transaction_details; left join (sums) load key, sum([lc amount]) [lc amount sum] resident transaction_details group key; the original table transactions_details have around 400 million rows, reason simple group , sum in sums table taking long time, running past 4 hours now. there better way of doing , , can 1 guide me qlikview query performance. you don'

ruby - Rails 'parse_query' error on server in brand new app -

i have installed on os x 10.10.3: homebrew, command line tools, installed ruby using rbenv: ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin14] rails 4.2.2 when create new app (with default sqlite database) , try run it, says: => booting webrick => rails 4.2.2 application starting in development on http://localhost:3000 => run `rails server -h` more startup options => ctrl-c shutdown server [2015-06-18 23:11:30] info webrick 1.3.1 [2015-06-18 23:11:30] info ruby 2.2.2 (2015-04-13) [x86_64-darwin14] [2015-06-18 23:11:30] info webrick::httpserver#start: pid=41860 port=3000 but in browser see: 500 internal server error if administrator of website, please read web application's log file and/or web server's log file find out went wrong. log file: started "/" ::1 @ 2015-06-18 23:11:48 +0300 **argumenterror (wrong number of arguments (2 1)):** actionpack (4.2.2) lib/action_dispatch/http/request.rb:338:in `parse_query' rack (1

how to delete specific elements from a numpy array by index in python -

this question has answer here: how remove specific elements in numpy array 4 answers i have array , wish delete first element. tried nummpy.delete , not index. wonder how can in python. thanks check out answer. please search before post new questions. https://stackoverflow.com/a/10996196/4044442

ValueError: too many values to unpack python 2.7 -

so trying compile following code it's showing me error on cv2.findcontours. though, using python 2.7 version. reason why error: many values unpack python 2.7 coming? import cv2 import numpy np import time #open camera object cap = cv2.videocapture(0) #decrease frame size cap.set(cv2.cap_prop_frame_width, 1000) cap.set(cv2.cap_prop_frame_height, 600) def nothing(x): pass # function find angle between 2 vectors def angle(v1,v2): dot = np.dot(v1,v2) x_modulus = np.sqrt((v1*v1).sum()) y_modulus = np.sqrt((v2*v2).sum()) cos_angle = dot / x_modulus / y_modulus angle = np.degrees(np.arccos(cos_angle)) return angle # function find distance between 2 points in list of lists def finddistance(a,b): return np.sqrt(np.power((a[0][0]-b[0][0]),2) + np.power((a[0][1]-b[0][1]),2)) # creating window hsv track bars cv2.namedwindow('hsv_trackbar') # starting 100's prevent error while masking h,s,v = 100,100,100 # creating track bar cv2.create

jsf - javax.servlet.ServletException: UT010016: Not a multi part request at io.undertow.servlet.spec.HttpServletRequestImpl.loadParts -

i've jsf 2.2 page below file upload form deployed wildfly 8.2.0. <h:form> <h:inputfile value="#{filepair.miscpart}" /> <h:commandbutton value="submit" action="validationresult" /> </h:form> when submit it, below exception: javax.servlet.servletexception: ut010016: not multi part request @ io.undertow.servlet.spec.httpservletrequestimpl.loadparts(httpservletrequestimpl.java:508) @ io.undertow.servlet.spec.httpservletrequestimpl.getparts(httpservletrequestimpl.java:459) @ com.sun.faces.renderkit.html_basic.filerenderer.decode(filerenderer.java:91) @ javax.faces.component.uicomponentbase.decode(uicomponentbase.java:831) @ javax.faces.component.uiinput.decode(uiinput.java:771) @ javax.faces.component.uicomponentbase.processdecodes(uicomponentbase.java:1226) @ javax.faces.component.uiinput.processdecodes(uiinput.java:676) @ javax.faces.component.uiform.processdecodes(uiform.java:225)

Fitting image within wrapper using overflow:hidden (CSS/ HTML/ PHP) -

Image
i have directory full of product images. trying display each image 150px x 150px without distorting image , place border around product code (which image name) , image itself. looks now: i image , product code sit @ bottom of border, having issues because noob , using overflow:hidden . center image other two. here php code (using php because need access sql later): <php $dir = "/some/location/"; if ($opendir = opendir($dir)){ while(($file= readdir($opendir))!== false){ if($file!="."&&$file!=".."){ echo('<div class = "image" > '); echo "<img src='/some/location/$file'><br>"; $sku = substr($file,0,-4); echo("<p>"); echo($sku); echo("</p>"); echo("</div>");} } } ?> css code: <style> div.image { display: inline-block;

IOS: Easy Facebook SDK email retrieval Objective C -

edit (rewording question because didn't make sense before.) i have loginviewcontroller has following ibaction: -(ibaction)fblogin:(id)sender { fbsdkloginmanager *login = [[fbsdkloginmanager alloc] init]; [login loginwithreadpermissions:@[@"email"] handler:^(fbsdkloginmanagerloginresult *result, nserror *error) { if (error) { // process error } else if (result.iscancelled) { // handle cancellations } else { // if ask multiple permissions @ once, // should check if specific permissions missing if ([result.grantedpermissions containsobject:@"email"]) { if ([fbsdkaccesstoken currentaccesstoken]) { [[[fbsdkgraphrequest alloc] initwithgraphpath:@"me" parameters:nil] startwithcompletionhandler:^(fbsdkgraphrequestconnection *connection, id result, nserror

Why python 2.7 on Windows need a space before unicode character when print? -

Image
i use cmd windows, chcp 65001, code: print u'\u0110 \u0110' + '\n' result: (a character cmd can't display) (character want) traceback (most recent call last): file "b.py", line 26, in <module> print u'\u0110 \u0110' ioerror: [errno 2] no such file or directory but, when use code: print u' \u0110 \u0110' + '\n' result: (a space)(charecter want) (character want) traceback (most recent call last): file "b.py", line 26, in <module> print u' \u0110 \u0110' + '\n' ioerror: [errno 2] no such file or directory my screen: and question is: why python 2.7 need space when print unicode character? how fix ioerror: [errno 2] short answer on windows can't print arbitrary strings using print . there workarounds, shown here: how make python 3 print() utf8 . but, despite title of question, can't use print utf-8 using code page 65001, repea

Robospice Android - spiceRequest that begins in one activity and ends in another activity -

i'm trying start robospice request in activity , receive results of request in activity b. in activity a fetchspicerequest fetchspicerequest = new fetchspicerequest(); spicemanager.execute(fetchspicerequest, new activityb().postlistener); the postlistener implements pendingrequestlistener , sitting within activity b. in activity b we addlistener pending request started in activity below. @override protected void onstart() { spicemanager.start( ); spicemanager.addlistenerifpending(post.class, 0, new postlistener()); we implement postlistener in activity b below. public final class postlistener implements pendingrequestlistener<post> { @override public void onrequestfailure(spiceexception spiceexception) { toast.maketext(mainactivity.this, "exception: " + spiceexception.tostring(), toast.length_short).show(); } @override public void onrequestsuccess(post post) { toast.maketext(mainactivity.this, "a

ios - "type of expression is ambiguous without more context" - Referencing appDelegate -

i have appdelegate written in obj-c. i'm trying access in new swift class, strange error think misleading, , i'm trying root. in swift file, i've set breakpoint after: var appdelegate = uiapplication.sharedapplication().delegate if po: po appdelegate i get: printing description of appdelegate: optional(<appdelegate: 0x7f81a2d1cc40>) everything fine. however, when try to: po appdelegate.navigationcontroller in debug console get: error: <expr>:1:13: error: type of expression ambiguous without more context and navigationcontroller property of appdelegate, declared in original obj-c appdelegate.h file. here's original question: cannot invoke '...' argument list of type '...' edit based on @martin's comment, changed code to: var appdelegate = uiapplication.sharedapplication().delegate! appdelegate.navigationcontroller.popviewcontrollerisanimated(true) which brings error: 'uiapplicationdelega

python - Django - queryset caching request-independent? -

i need cache mid-sized queryset (about 500 rows). had on solutions, django-cache-machine being promising. since queryset pretty static (it's table of cities that's been populated in advance , gets updated me , anyway, never), need serve same queryset @ every request filtering. in search, 1 detail not clear me: cache sort of singleton object, available every request? mean, if 2 different users access same page, , queryset evaluated first user, second 1 cached queryset? i not figure out, problem facing. saying classical use case caching. memcache , redis 2 popular options. needs write method or function first tries load result cache, if not there , queries database. e.g:- from django.core.cache import cache def cache_user(userid): key = "user_{0}".format(userid) value = cache.get(key) if value none: # fetch value db cache.set(value) return value although simplicity, have written function, ideal

python - Using docopt double dash option with optional parameter? -

using docopt, there way make double-dashed parameter works , without equals sign? i want both of following commands make --tls true: cmd --tls cmd --tls=true i seem able 1 or other work using options: --tls or options: --tls=false separating them comma not seem work options: --tls, --tls=false

How to modify Python str object to produce a provenance report noting all files that modify a string -

i'd figure out how modify or replace instances of base string type str in python 3 program. want add provenance string. idea being anytime string created notes source file created string. there time string assigned i'd prior string's history follow string. import sys import inspect import builtins class provenancestring(str): def __new__(cls, string, source=none): return super().__new__(cls, string) def __init__(self, value=none, source=none): super().__init__() self._myinit(value, source) def _myinit(self, value, source): self.history = [] self.sources = [] if hasattr(value, 'history'): self.history = value.history callerframerecord = inspect.stack()[2] frame = callerframerecord[0] info = inspect.getframeinfo(frame) self.history.append("{}:{}".format(info.filename, info.lineno)) if hasattr(value, 'sources'): self.so

Rendering Performance when populating Nested Form - Rails 4 - OmniContacts -

in app using omnicontacts gem allow users import contacts. works. getting contacts gmail takes 300-500ms. in order allow importing of contacts putting them in nested form. rendering of each contact takes 175-300ms, multiply 1000 , crappy. i love there rails solution issue. otherwise guessing using ajax , js form might work. thoughts , time appreciated. import controller: def import @user = current_user @import = request.env['omnicontacts.contacts'] @contacts = @import.map |contact_info| contact.new( first_name: contact_info[:first_name], last_name: contact_info[:last_name], email_home: contact_info[:email], phone_home: contact_info[:phone] ) end respond_to |format| format.html end end import view: <div class="row"> <div class="small-12"> <%= simple_form_for(@user, url: import_path) |f| %> <%= f.simple_fields_for :contacts, @conta

Android barcode printing with Bixolon SPP-R200II -

i need print barcode in mobile bluetooth printer brand “bixolon” model “spp-r200ii” android application. using bixolon sdk android work samsung sii not motorola moto g g2. decided not using sdk, instead sending commands printer based on “unified command manual” bixolon. using these lines: string codigo=”1234567894”; int gs=29; int k=107; int m=5; byte[] codigobytes=codigo.getbytes(); outputstream.write((byte)gs); outputstream.write((byte)k); outputstream.write((byte)m); outputstream.write(codigobytes); based on manual command should print “itf” barcode not. connection printer stablished; can print text not barcodes command. has had better luck in printing barcodes method , printer? appreciate , comments. you have missed 1 important part while printing bar codes. should end nul sign. add this: string nul = new string(new byte [] {0x00}); outputstream.write(nul.getbytes());

winforms - Will this implementation using TPL work inside a process running on an STA thread? -

i want create instance of object assembly implements interface define in forms app. create object @ app startup using activator.createinstance , , keep application-level reference it. at points during application want call methods on object without holding main thread using task.run(() => imyobject.dosomework(somelist, somelist2)) . want make "fire , forget" void method call , don't need await or register callbacks. will fact app running in sta thread pose issue? have worry leaks or premature collection of objects instantiate on main thread , reference inside task closure? intend read contents of these lists, not modify them. no need worry; create delegate, objects references kept in memory, @ least until task.run exits. there's nothing sta thread changes that. threads don't factor gc @ - except stacks running threads contain root objects. can cross-reference objects want , won't confuse gc.

xcode - Error: Failed to connect outlet from ... to (NSTextField): missing setter or instance variable -

why code: if note1math.stringvalue == "" { txtfilled = 0 }else{ txtfilled = 1 } give error?: 2015-06-18 20:20:17.633 office[41763:430750] failed connect (note1) outlet (office.viewcontroller) (nstextfield): missing setter or instance variable. fatal error: unexpectedly found nil while unwrapping optional value (lldb) this part of message: 2015-06-18 20:20:17.633 office[41763:430750] failed connect (note1) outlet (office.viewcontroller) (nstextfield): missing setter or instance variable. does not come code. comes loading of nib or storyboard. presumably, had named outlet note1 @ 1 time, connected in nib or storyboard, , renamed note1math in code without fixing nib/storyboard. then, later, when accessed note1math , nil (because not connected in nib/storyboard). caused second message: fatal error: unexpectedly found nil while unwrapping optional value (lldb) the solution go nib or storyboard

What kind of pattern has a class that contains an instance of itself cast to the interface? -

Image
i have inherited code, , can't figure out reasoning behind architecture of 1 of classes. class looks this: [serializable] internal class myclass : myinterface { private dbmodel datamodel { get; set; } private myinterface ithis { { return (myinterface)this; } } public string someproperty { { return ithis.someproperty } } ... string myinterface.someproperty { { return datamodel.getsomeproperty(); } } } is sort of common (or uncommon) design pattern i've never seen? why want access properties way? benefit this? notice ithis not static, isn't sort of singleton pattern. looks snapshot variant of memento, perhaps encapsulation being used @ assembly level (hence internal). can see if caretaker , originator roles filled somewhere?

javascript - Using Express' route paths to match `/` and `/index` -

i'm using express , want match / , /index same route. if write app.route('/(index)?') node throws error: c:\myproject\node_modules\express\node_modules\path-to-regexp\index.js:69 return new regexp(path, flags); ^ syntaxerror: invalid regular expression: /^\/(?(?:([^\/]+?)))?e\/?$/: invalid group @ new regexp (native) @ pathtoregexp (c:\myproject\node_modules\express\node_modules\path-to-regexp\index.js:69:10) @ new layer (c:\myproject\node_modules\express\lib\router\layer.js:32:17) @ function.proto.route (c:\myproject\node_modules\express\lib\router\index.js:482:15) @ eventemitter.app.route (c:\myproject\node_modules\express\lib\application.js:252:23) @ c:\myproject\server.js:28:19 @ array.foreach (native) @ object.<anonymous> (c:\myproject\server.js:27:18) @ module._compile (module.js:460:26) @ object.module._extensions..js (module.js:478:10) note if use app.route('/foo(bar)?') it works fine

c# - Calculate CRC 15 for CAN BUS -

i need calculate crc checksum can bus. scenario: my input looks following (where x either 1 or 0 , * marks multiple times x , | marks section , - change of input method, lb is label , tb textbox , cb combobox ): lb : 0 tb : 11x cb : x cb : x lb : 1 tb : 4x => convert.tostring(8-64 / 8, 2).padleft(4, '0'); tb : 8-64x, => 8-64 % 8 == 0 tb : 15x => crc of above lb : 1 lb : 11 lb : 1111111 lb : 111 which returns layout: 0|11*x-x|x-1-4*x|64*x|15*x-1|11|1111111|111 example: 00101010101000100100101010100101010(missing 15*x crc sum)1111111111111 this string processed following string extension, maximal 5 equal digits follow each other: public static string correct4crc(this string s) { return s.replace("00000", "000001").replace("11111", "111110"); } after following method returns divisor: public static biginteger createdivisor(string s) { var = biginteger.parse(s); var d = biginte

extract nouns and verbs from a text dataframe and save it in two different dataframes in R -

this question has answer here: extracting nouns , verbs text 1 answer i have text dataframe text columns. 1 of columns hw motorola scanner model rssn missing issue damaged power connectionif serial provide extended part numberrs fsr = short cable attached wrist build type rpcolleague colin patterson contact number ensure main depot id selected ensure selected correct model position id save log i have removed numbers, stopwords , punctuations text. want separate nouns , verbs , put them in different dataframes. that not strictly trivial task. load library parts of speech each word (e.g. opennlp -> maxent_pos_tag_annotator ), of them may either 1 part of speech or depending upon context, makes harder task programmatically perfect. hope opennpl package helps though.

What is wrong with my code for quadratic formula -

public class quadraticeqn { private double a, b, c; public quadraticeqn(double x, double y, double z){ a=x; b=y; c=z; } private double disc = b*b-4*a*c; public boolean hassolutions(){ if(disc>=0) return true; else return false; } public double getsolutions1(){ return (-b-math.sqrt(disc))/(2*a); } public double getsolutions2(){ return (-b+math.sqrt(disc))/(2*a); } } import java.util.scanner; public class quadraticequationtest { public static void main(string[] args) { scanner values = new scanner(system.in); system.out.println("enter values a, b, c:"); double a=values.nextdouble(); double b=values.nextdouble(); double c=values.nextdouble(); quadraticeqn qe = new quadraticeqn(a, b, c); if (qe.hassolutions()) system.out.println(qe.getsolutions1()+" "+qe.getsolutions2()); else system.out.println("no real solution

R plot of a matrix of complex numbers -

Image
i have matrix of complex values. if issue command: plot(mymatrix) then shows on graphics device kind of scatterplot, x-axis labeled re(mymatrix) , y-axis im(mymatrix). shows information i'm looking for, can see distinct clusters, cannot see 1 column. my questions : i assume there 1 point per matrix row. right ? how calculated re(mymatrix) each row vector ? it not re(mymatrix[1,row]), seems mix of values of row vector. able these values, know how compute them r. no, there 1 point each matrix element. set.seed(42) mat <- matrix(complex(real = rnorm(16), imaginary = rlnorm(16)), 4) plot(mat) points(re(mat[1,1]), im(mat[1,1]), col = "red", pch = ".", cex = 5) look red dot: you'd same plot, if plotted vector instead of matrix, i.e., plot(c(mat)) . this happens because plot.default calls xy.coords , function contains following code: else if (is.complex(x)) { y <- im(x) x <- re(x)

c++ - Socket Descriptor closed from another thread on certain condition when accept() call on the same socket is going on in Linux? -

1 thread making accept call in for(;;;) loop .on condition closesocket called , closes same socket on accept call being made . accept call gives error . ebdaf error on solaris , einval error on linux . how should overcome problem . can check socketnum state before making accept call . how should approach problem . you cannot close socket in 1 thread while thread using it. basic problem there no way know whether other thread using socket or about use socket. , if it's about use socket, there unavoidable race conditions. mistake has caused real world problems, including 1 serious security implications. instead, don't close socket. signal thread might using socket other way, , have thread close socket.