Posts

Showing posts from May, 2011

angularjs - Angular 2 delete a file from uploaded list of files -

i new angular 2. uploading files , displaying them in template. on checking checkbox when press delete, not deleting required file list. below code template <form #f="ngform" (ngsubmit)="onsubmit(f.value)"> <table cellpadding="4" class="grid" > <thead><tr><th></th><th>document name</th><th>document id</th><th>document type</th><th>source</th> <th>document date</th><th>trip id</th><th>notes</th><th>action</th></tr></thead> <tbody *ngfor="let file of files"> <tr > <td class="form-group"><input type="checkbox" [checked]="checked"></td> <td class="form-group"><input type="text" class="form-control" ngcontrol="file.name">{{file.name}}</td> <td class="fo

sql - Partition by using multiple case statements -

i attempting dedupe records in database using partition clause query run in order dedupe. ranks records populated , keeps highest ranked record. ctedupes ( -- -- partition based on contact.owner , email select row_number() over(partition contactowner, email order -- ranking populated field case when otherstreet not null 1 else 0 end + case when othercity not null 1 else 0 end ) rnd, * scontact (contact_owner_name__c not null , contact_owner_name__c<>'') , (email not null , email<>'') ) --rank data , place new table created select * contact_case1 ctedupes rnd=1; i wanted know if possible partition using case. example partitioning contactowner , email. when contactowner null want partition contactofficer instead. can create case statements or not possible since ranking altered in someway. you can use case , think coalesce() simpler in case: select row_number() on (partition coalesce(contactowner, contactof

python 2.7 - pylab install error gcc windows 10 -

so installed theano on python 2.7 environment within anaconda 3, on windows 10. theano passed theano.test() @ least. using example code deeplearning.net . heva sucessfully run first block on linked page defines theano function. when go install pylab via pip install pylab can use skimage second block, installer quits while doing gcc call portion looks says "shared geometry". 1 thing noticed right away -debug flag misspelled -ddebug . cause? have msvcr90.dll , if , need it? also, important, i'm using (6 months or so) outdated tdm-gcc 4.9 something. here line in question, few others might interesting: `copying skimage\_shared\tests\__init__.py -> build\lib.win-amd64-2.7\skimage\_shared\tests running build_ext looking python27.dll cannot build msvcr library: "msvcr90d.dll" not found customize mingw32ccompiler customize mingw32ccompiler using build_ext building 'skimage._shared.geometry' extension compiling c sources c compiler: gcc -g -ddebug -d

Opencv - polynomial function fitting -

in opencv (or other c++ lib), there similar function matlab fit can 3d polynomial surface fitting (i.e. f(x,y)= p00 + p10*x + p01*y + p20*x^2 + p11*x*y + p02*y^2 ). thanks i don't think there lib in opencv can : int main( int argc, char** argv ) { mat z = imread("1449862093156643.jpg",cv_load_image_grayscale); mat m = mat_<double>(z.rows*z.cols,6); mat i=mat_<double>(z.rows*z.cols,1); (int i=0;i<z.rows;i++) (int j = 0; j < z.cols; j++) { double x=(j - z.cols / 2) / double(z.cols),y= (i - z.rows / 2) / double(z.rows); m.at<double>(i*z.cols+j, 0) = x*x; m.at<double>(i*z.cols+j, 1) = y*y; m.at<double>(i*z.cols+j, 2) = x*y; m.at<double>(i*z.cols+j, 3) = x; m.at<double>(i*z.cols+j, 4) = y; m.at<double>(i*z.cols+j, 5) = 1; i.at<double>(i*z.cols+j, 0) = z.at<uchar>(i,j); } svd s(m); mat q; s.backsubst(i,q); cout<<

Append string in the middle of a query in python -

i'm trying build query in python, i'm looking elegant way append condition in middle of string: def get_raw_queryset(frequency=none, where_condition=none): qs = "select id, count(*) count user_transaction_log " \ # want append if not none if where_condition: "where .... = 1" \ "group type , strftime('{0}', datetime) order id" \ .format(frequency) return qs this work long can safely evaluate string if where_condition not string: "select ..." + bool(where_condition) * ("where ...") + "group ..." i hope you're being extremely careful avoid sql injection.

street address - Android Linkify for UK adresses -

regarding use of linkify on textbox / label know how enable uk address work? using or canadian address works fine, changing international address not same link-to-map treatment. i avoid building pattern matching library compensate this. any or pointers documentation related issue?

autocomplete - Enable returning multiple arguments as completion reply at once in fish shell -

i working on porting google cloud sdk command line auto completion feature fish shell. when have unambiguous reply multiple arguments: a) either command completed arguments spaces gets escaped (\ ) when specify function call in complete command inside ''s or ""s, like: > complete ... -a '(__fun)' b) or if don't (just: -a (__fun)), first argument of reply gets completion , other arguments "get lost" is possible reply multiple arguments @ once in fish completion? could done in number of ways. have hack bit, though, since ridiculous_fish says it's not designed this. easiest ship own wrapper function can take escaped output , pass on in way works. not pretty, though, , screw autosuggestions unless go , modify history lines. here's semi-hacky/semi-elegant propose: if have looked "sequence" of args you'd want complete @ once, @ first invocation put trailing args description first one. once 1 has been locke

Why does using keep_if in Ruby skip over the first element in an array? -

def unique(arr) return arr.keep_if { |x| arr.count(x) == 1 } end print unique([2, 5, 5, 4, 22, 8, 2, 8]) #=> [4, 22, 2] the value 2 appears twice in array, using following method incorrectly returns it. why happen, , can fix it? unfortunately, due hidden behavior in how keep_if works. illustrate behavior, can make use of lowest-hanging fruit in our debugging orchard, ol' puts : def unique(arr) return arr.keep_if { |x| puts x, arr.join(',') arr.count(x) == 1 } end print unique([2, 5, 5, 4, 22, 8, 2, 8]) this gives following output: 2 2,5,5,4,22,8,2,8 5 2,5,5,4,22,8,2,8 5 2,5,5,4,22,8,2,8 4 2,5,5,4,22,8,2,8 22 4,5,5,4,22,8,2,8 8 4,22,5,4,22,8,2,8 2 4,22,5,4,22,8,2,8 8 4,22,2,4,22,8,2,8 [4, 22, 2] look @ happens whenever method discovers new value wants keep: stores value in 1 of indexes in array, overwriting what's there. next time finds value wants keep, places in next spot, , on. this means first time keep_if looks @ 2 , se

java - How compare Enum Value? -

this question has answer here: why java not allow overriding equals(object) in enum? 4 answers i want compare enum's value in example. public enum en{ vanila("good"), marlena("luck"), garnela("good"); private string value; private en(string s){ this.value = s; } } as vanila , garnela have same value comparing them should return true. there 2 ways 1 == operator , second equals() method. tried own logic , add method enum. public boolean comparevalue(en e){ return (this.value).equals(e.value); } and it's working fine. en = en.vanila; en b = en.garnela; en c = en.marlena; if(a.comparevalue(b)){ system.out.println("a == b"); } if(a.comparevalue(c)){ system.out.println("a == c"); } if(b.comparevalue(c)){ system.out.println("b == c"); }

shell - how to escape quotes in command argument to sh -c? -

this question has answer here: how escape double quote inside double quote? 8 answers the shell command cmd may have whitespace , single , double quotes. how escape these quotes correctly pass command posix shell: >dash -c ' cmd ' the other question pointed dup, asks double quotes. 1 of answers there going work - split command , use concatenated quotes. example, if cmd were cd "dir"; ls 'foobar' then transform into >dash -c 'cd "dir"; ls '"'foobar'" this messy... there no easier way? added: seems nobody understands me... want general procedure, algorithm, takes on input, string (to precise, made out of printable ascii characters 0 127 in ascii table), , outputs, second string. requirement if first string executed this posix_shell>string1 the result same as >posix_shel

ios - UISearchBar stays when seguing to another view controller via push -

Image
i followed guide: http://www.jhof.me/simple-uisearchcontroller-implementation/ the difference in code is instead of self.tableview.tableheaderview = self.searchcontroller.searchbar; i have self.navigationitem.titleview = self.searchcontroller.searchbar; when segue results table view controller, uisearchbar stays in navigation bar. i rewrite sample apple, can see comment self.tableview.tableheaderview = self.searchcontroller.searchbar; set navigation bar's title view, you. can find search bar here in snapshot. - (void)viewdidload { [super viewdidload]; aplresultstablecontroller *qresultstablecontroller = [[aplresultstablecontroller alloc] init]; self.resultstablecontroller = qresultstablecontroller; _searchcontroller = [[uisearchcontroller alloc] initwithsearchresultscontroller:qresultstablecontroller]; self.searchcontroller.searchresultsupdater = self; [self.searchcontroller.searchbar sizetofit]; // self.tableview.tableheaderview

Tomcat 6 - Java proxy tunneling failed on Windows - ERROR - 407 -

i've created class deal http proxy connect remote server web services. deployed on tomcat 6, on windows server 2008 , called in servlet. it working $catalina_home\bin\tomcat6.exe, i.e. on cmd. it couldn't go through proxy windows service utility, i.e. $catalina_home\bin\tomcat6w.exe. both reading same configurations, behaving differently while establishing connection remote server through proxy. i've found few way proxy settings, follows: proxy vole utility jar (proxy-vole_20131209.jar). java.net.usesystemproxies set true , fetch proxy info. reading pac java code (deploy.jar). passing constant hostname/ip , port. all of above work $catalina_home\bin\tomcat6.exe, other pac reading fetches private ip instead or public ip (well can ignore long know exact hostname , port). note: there no proxy credentials i've found , working without cmd. when try run tomcat windows service utility, i.e. $catalina_home\bin\tomcat6w.exe fails connect remote server , th

Reset animation to original position using javascript -

using following script able move picture right when clicked: <script> var mytimer = null; function move(){ document.getelementbyid("fish").style.left = parseint(document.getelementbyid("fish").style.left)+1+'px'; } window.onload=function(){ document.getelementbyid("fish").onclick=function(){ if(mytimer == null){ mytimer = setinterval("move();", 10); }else{ clearinterval(mytimer); mytimer = null; } } } </script> i having trouble reseting picture original location without using jquery. if can appreciated. if capture original position ahead of time can reset later captured value: var originalposition = document.getelementbyid("fish").style.left; function resetposition() { document.getelementbyid("fish").style.left = originalposition; }

java - Capture screenshot -

how take screenshot of failed test case test case name? example: suppose test case name testvelifylogin(). if fails screenshot name should testvelifylogin_time_date.jpg please me how this. i have written code screen shot following: public void ontestfailure(itestresult itestresult) { string path = system.getproperty("user.dir") + "\\testoutput\\screenshots"; dateformat dateformat = new simpledateformat("hh_mm_ss_dd_mm"); calendar cal = calendar.getinstance(); string date = dateformat.format(cal.gettime()); file scrfile = ((takesscreenshot) driver) .getscreenshotas(outputtype.file); try { fileutils.copyfile(scrfile, new file(path,"screenshot_"+date+".jpg")); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } instead of screenshot_ want test case name. you ite

java - Jmockit: Unable to mock inner field. Always ends up being null -

i have trouble controlling going on variables inside methods test. in example, input method being tested mocked or injectable object yet if try it, null* exceptions. class , method being tested: public class someclass { public someclass() {} public void mymethod(inputclass input) { //how set field no matter what, don't exeption? long somelong = long.parselong(input.getsomelong()); // how prevent numberformatexception when long.parselong() called in situation? someinnerclass innerclass = someinnerclass(long.parselong(input.getsomelong())); // how prevent numberformatexception when long.parselong() called in situation? innerclass.dostuff(long.parselong(input.getsomelong())); // ... } } test class: public class testsomeclass { @tested private someclass classbeingtested; @injectable someinnerclass innerclass; @injectable inputclass input; // doesn't matter if use @mocked here @test

c - Sort an array in place according to a sort order defined in another array -

i have array defines sort order array. example, sort array consisting of char * data[] = {"c", "b", "a"}; , sort_order array {2, 1, 0} - when array sorted, first element should "c" (which data[sort_order[0]] ). (the background have 2 arrays want sort, second array should use same sort order first one. sort {0, 1, 2} using values first array, , i'd use sort order sort actual values of both arrays.) the obvious solution create copy of array ( new_data ), , assign every element correct value defined sort order: for (int = 0; < n; ++i) { new_data[i] = data[sort_order[i]]; } however, requires making copy of array. there way can swap elements of original array sort them in place without having copy array? edit: "possible duplicate" use array, precisely trying avoid. reorder in place, sorts both a[] , i[], rotating "cycles". each store places value in it's proper location, time complexity

android - Override lock screen with activity for alarm application -

i working on different type of alarm application , cannot seem figure out how have when alarm goes off , received, if screen off, turn on , open right applications activity turn off alarm. basically same way regular google clock it. i added these manifest file proper receiver , service tags. <uses-permission android:name="android.permission.wake_lock"/> <uses-permission android:name="android.permission.system_alert_window"/> i have alarm receiver class handles receive , calls wake lock class; here receiver below. @override public void onreceive(context context, intent intent) { wakelocker.acquire(context); intent serviceintent = new intent(context, ringtoneplayingservice.class); context.startservice(serviceintent); } and here beginning of ringtonplayingservice class called after received. handle playing of sound later in class didn't feel needed show. notificationmanager notificationmanager = (notificationmanager)getsystemse

Python NLTK :: Intersecting words and sentences -

i'm using nltk - specific toolkit manipulating corpus texts, , i've defined function intersect user inputs shakespeare's words. def shakespeareoutput(userinput): user = userinput.split() user = random.sample(set(user), 3) #here nltk's method play = gutenberg.sents('shakespeare-hamlet.txt') #all lowercase hamlet = map(lambda sublist: map(str.lower, sublist), play) print hamlet returns: [ ['[', 'the', 'tragedie', 'of', 'hamlet', 'by', 'william', 'shakespeare', '1599', ']'], ['actus', 'primus', '.'], ['scoena', 'prima', '.'], ['enter', 'barnardo', 'and', 'francisco', 'two', 'centinels', '.'], ['barnardo', '.'], ['who', "'", 's', 'there', '?']...['finis', '.'], ['th

c# - WPF How to change header color of gridview -

Image
i've been trying learn how customize listview contains gridview. i've been able figure out , learn each part require... except one. how change color of white lines between each header column name? xaml: <window x:class="uitest.mainwindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:uitest" mc:ignorable="d" title="mainwindow" height="200" width="400"> <stackpanel> <listview margin="0 50 0 0" name="lvusers" borderbrush="{x:null}" borderthickness="0" background="red" padding="0"> &l

How can one access Accelerometer in windows 10 generic C++ module? -

i have java app uses native interface c++ module access native api features. program running on windows 10 tablet computer has accelerometer. want access sensor output , pass java program. windows module generic "win32" module compiled using vc 2015 community edition , latest windows 10 sdk. is possible or way through totally new "universal app" system based on c# .net , xaml "coding" ??? i want subscribe sensor events , receive callbacks or tail end of queue or pipe data.

java - check String contains inside HashTable Value -

1=[fletcher christian, no, visualisation of egocentric networks, exploring irish political landscape on twitter, twitter network analysis, web-based server energy model generator, recommending movies using curated imdb lists, travel planner commuters, analysis of urban street networks - constructing dual representation, biography reading media assistant] i have hash-table above.i want find whether fletcher christian contained inside hash-table value here value vector simply go on values , check : static boolean contains (hashtable <integer, vector <string>> map, string value){ (vector<string> values : map.values()){ if (values.contains(value)) return true; } return false; } in java 8 can single row: static boolean contains (hashtable <integer, vector<string>> map, string value){ return map.values().stream().anymatch(list -> list.contains(value)); }

How to send a string, using java socket as client and delphi indy tcpserver as server -

server onexecute event like try s := acontext.connection.iohandler.readln(indytextencoding_utf8); ok:=true; except on e:exception winapi.windows.beep(500,500); end; the basic problem send client server i solved adding lf character in end of string in java code string str = "test\n"; try { socket = new socket("localhost", 13428); osw =new outputstreamwriter(socket.getoutputstream(), "utf-8"); osw.write( str, 0, str.length()); osw.flush(); } catch (ioexception e) { system.err.print(e); } { socket.close(); }

php - How to check which coupon is applied to which product in WooCommerce? -

since can apply different coupons each product in order, there method know coupon applied product? i've used $order->get_used_coupons() function returns used coupon codes only. please solution. thanks. this based on compiled searches around solving issue, unsure (untested) snippet code: function wc_my_order_coupons( $order_id ) { $order = new wc_order( $order_id ); // checking if order has used coupons if( $order->get_used_coupons() ) { $order_coupons = $order->get_used_coupons(); /* echo var_dump($order_coupons); */ foreach( $order->$order_coupons $coupon) { $coupon_id = $coupon->id; /* echo var_dump($coupon_id); */ // here list of data can use coupon $cp_discount_type = get_post_meta( $coupon_id, 'discount_type', true ); $cp_amount = get_post_meta( $coupon_id, 'coupon_amount', true ); $cp_indiv_use = get_post_meta( $coupo

sorting - How to sort SDCard image based on date in android -

i trying sort sdcard image gridview baseed on date. tried variety of codes. cant able achieve this. please provide me help. public class sdcard extends activity { // cursor used access results querying images on sd card. private cursor cursor; // column index thumbnails image ids. private int columnindex; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_sdcard); // set array of thumbnail image id column want string[] projection = {mediastore.images.thumbnails._id}; // create cursor pointing sdcard cursor = managedquery( mediastore.images.thumbnails.external_content_uri, projection, // columns return null, // return rows null, mediastore.images.thumbnails.image_id); // column index of thumbnails image id columnindex = cursor.getcolumnindexorthrow(mediastore.images.thumbnails._id); gridview sdcardimages =

how to redirect stderr with: android adb exec-out run-as cat foo.log 2>foo.error > foo.log -

i using script below on unrooted 2013 nexus 7's android 6.0.1 , may patches. if log files exists, well. if not, stderr goes local foo.log file on pc. is there way fix this? tried shell here doc, not seem work exec-out. set package=com.tayek.tablet.gui.android.cb7 ::setlocal enabledelayedexpansion %%i in (0a9196e8) ( adb devices -l | grep %%i >nul if errorlevel 1 ( echo %%i not connected! ) else ( echo %%i connected. adb -s %%i shell run-as %package% ls -l /data/data/%package%/files adb -s %%i exec-out run-as %package% cat /data/data/%package%/files/tablet.0.0.log 2>%%i.0.0.errors.txt 1> %%i.0.0.log adb -s %%i exec-out run-as %package% cat /data/data/%package%/files/tablet.1.0.log 2>%%i.1.0.errors.txt 1> %%i.1.0.log ) )

javascript - Keep a timer (coded in JS) that will automatically change color of image after 3 seconds -

i started learning js , saw below given example(in link) , thought of coding automatic bulb switch on /off modifying existing example code. thought process : after user hits image of bulb 1st time , bulb automatically switch on / off. interval between switch on /off : 3 seconds. 1 hit whole process continues 2 mins or less. code example : http://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_lightbulb existing code : <!doctype html> <html> <body> <h1>javascript can change images</h1> <img id="myimage" onclick="changeimage()" src="pic_bulboff.gif" width="100" height="180"> <p>click light bulb turn on/off light.</p> <script> function changeimage() { var image = document.getelementbyid('myimage'); if (image.src.match("bulbon")) { image.src = "pic_bulboff.gif"; } else { image.src = "pic_bulbon.gif";

android - Javascript function is not calling on mobile -

i have script function , working on laptop not calling on mobile (checked on androids only). not displaying simple alert message. what can reason this? this link: <a href="javascript:void(0)" onclick="doit(id='<?php echo $results[$i]->id; ?>', color = '<?php echo get_post_meta($pid, 'color', true);?>',color2='<?php echo get_post_meta($pid, 'color2', true);?>', unit_size='<?php echo get_post_meta($pid, 'unit_size', true);?>', unit_size2='<?php echo get_post_meta($pid, 'unit_size2', true);?>',col_unit_gst='<?php echo get_post_meta($pid, 'col_unit_gst', true);?>', col_unit_xgst='<?php echo get_post_meta($pid, 'col_unit_xgst', true);?>',col2_unit2_xgst='<?php echo get_post_meta($pid, 'col2_unit2_xgst', true);?>', col2_unit2_gs

javascript - Inserting a button inside a form and triggering different actions in an Angular app -

i'm making web app. i'm in middle of implementing braintree , works fine. have issue view code braintree. below essential view code need braintree integration: <form name="form" ng-submit="submitpayment()"> <div id="payment-form"></div> <input type="submit" class="button button-form-success button--primary vertical-offset--small" value="pay"> </form> now, trying add button next pay button, whenever put button in form, triggers submitpayment() instead of button's action. how add button inside form , trigger different function when clicked? just use a tag below <a href="" class="button button-form-success button--primary vertical-offset--small">second button</a>

node.js - Bluebird promise.all not respecting result order -

i'm using latest stable bluebird: "bluebird": "~3.4.0", and following code: promise.all([participantsservice.retrieveactiveparticipantsfromthelocaldb(), eventservice.retrieveactiveeventsfromthelocaldb(), heatservice.retrieveactiveheatsfromthelocaldb()]).then( function (results) { var namedresults = {participants: results[0], events: results[1], heats: results[2]}; return res.render('runners/runners', namedresults); }).catch( function (err) { winston.error('failed retrieve participants , or event details', err); return res.send(err); }); i expect namedresults have correct order of elements matching order in array of promises have been made not true! have different order every time. i assuming because says on bluebird's documentation: http://bluebirdjs.com/docs/api/promise.all.html unless i'm reading wrong... can help? thanks you should able use bluebird&#

c# - Linq calculate average,total and compare the result in query -

i having trouble in following query how add if else in select block want better way write following query var x = csvparser.parsecsv(@"data.csv"); var unsettledcustomers = x.groupby(g=>g.id). select(gg =>new { id=g.key, total=g.sum(xx=>xx.stake), avg=g.average(ss=>ss.win) }); var unsettledcustomers = x.groupby(g => g.id) .select(g => new { id = g.key, total = g.sum(xx => xx.stake), avg = g.average(ss => ss.win), avgeragebet = g.average(ss => ss.stake), unusualbets = g.where(bet => bet.stake > (10 * g.average(ss => ss.stake))).tolist() }); var allunusualbets = unsettledcustomers.selectmany(y => y.unusualbets); your posted question: i want identify bets stake (bet) more 10 times higher customer’s average bet in betting history... your data id = customer id. note there no instances average bet * 10 higher bet placed there no

java - How to create an Array without knowing the length it will have -

this question has answer here: java dynamic array sizes? 16 answers i've got problem solve follows: create method returns array contains positive values of int[] a i've kinda solved writing method: public static int[] solopositivi(int[] a) { int[] pos = new int[a.length]; int j=0; (int i=0; i<a.length; i++){ if (a[i]>0) { pos[j] = a[i]; j++; } } return pos; } of course when test using example: int[] = new int[] {2,-3,0,7,11}; i [2,7,11,0,0] , because set: int[] pos = new int[a.length]; the question is, how pos array have modular length can [2,7,11] , without having use lists? have solve problem using arrays methods. first, loop through , count number of positive elements know length, loop through again copy. public static int[] copypositivevals(int[] arr) { i

unit testing - JUnit Mockito mock one method in another class Error -

i use netbeans 8.1 , junit , mockito write unit test project. here pieces of code to tested function: public map<string, string> getallusers() { if (allusers == null) { if (session.checkacl2("donatebookprivilegelevel") || session.checkacl2("manageuserprivilegelevel")) { iterator<user> = userfc.findall().iterator(); system.out.println("pc::enum()"); allusers = new hashmap<string, string>(); while (it.hasnext()) { user item = it.next(); allusers.put(item.getname(), item.getuserid().tostring()); } } } return allusers; } my test class: package com.controller; import com.entities.user; import com.jsfc.util.jsfutil; import java.util.arraylist; import java.util.list; import java.util.map; import javax.faces.event.actionevent; import org.junit.after; import org.junit.afterclass; import org.junit.before; import org

python - How do I unit test a module that relies on urllib2? -

i've got piece of code can't figure out how unit test! module pulls content external xml feeds (twitter, flickr, youtube, etc.) urllib2. here's pseudo-code it: params = (url, urlencode(data),) if data else (url,) req = request(*params) response = urlopen(req) #check headers, content-length, etc... #parse response xml lxml... my first thought pickle response , load testing, apparently urllib's response object unserializable (it raises exception). just saving xml response body isn't ideal, because code uses header information too. it's designed act on response object. and of course, relying on external source data in unit test horrible idea. so how write unit test this? urllib2 has functions called build_opener() , install_opener() should use mock behaviour of urlopen() import urllib2 stringio import stringio def mock_response(req): if req.get_full_url() == "http://example.com": resp = urllib2.addinfourl(stringio(

CodenameOne Eclipse Install Error -

i unable install codenameone on eclipse (mars.2 release 4.5.2). os yosemite 10.10.4 update location: http://www.codenameone.com/files/eclipse/site.xml the error message is: error occurred while collecting items installed session context was:(profile=_users_abc_eclipse_jee-mars_eclipse.app_contents_eclipse, phase=org.eclipse.equinox.internal.p2.engine.phases.collect, operand=, action=). artifact not found: http:// www.codenameone.com/files/eclipse/plugins/codenameoneplugin_1.0.0.201606102329.jar. http:// www.codenameone.com/files/eclipse/plugins/codenameoneplugin_1.0.0.201606102329.jar any suggestions? that temporary issue latest update resolved couple of hours later.

c# - How to store the date in dd/MM/yyyy in sql server? -

here code datetime datetime = datetime.today; labeldate.text = datetime.tostring("'dd'/'mm'/'yyyy"); datetime d = datetime; sqlconnection con = new sqlconnection(); con.connectionstring= @"data source = desktop-u9dun78\sqlexpress;database = al_yousuf_db;integrated security=sspi"; con.open(); sqlcommand cmd = new sqlcommand("insert stockentrytb(date,product_no,product_name,quantity,original_cost,selling_cost)values('" + d + "'," + textboxprodno.text + ",'" + textboxprodname.text + "','" + textboxquantity.text + "'," + textboxoriginalcost.text + "," + textboxsellingcost.text + ")", con); cmd.executenonquery(); con.close(); but stored date in yyyy/dd/mm format. 2016-06-11 (2016/june/11), want store 11/06/2016 . stop that! you have bad habit kick choosing wrong data type in sql server. should never store datetime values string . in

android - How to assign only one value to the zeroth index of an array and that all in that array, in java -

if (uri.contains(",")) { more_than_one_url = uri.split(","); } else more_than_one_url[0] = uri; (string url : more_than_one_url) {/*operation*/} is possible such operation 1 element in string[] or there better way this, if use different names string , string[] becomes difficult me why check if string uri contains , ? split() return string[] if not find regex supplied. instead of checking using contains() , this. string[] more_than_one_url = uri.split(","); (string url : more_than_one_url) {/*operation*/} if not find delimiter supplied, split() return array of length 1 contain entire string.

java - Calculating Inverse of Polynomial Rings -

i try understand ntru-pkcs , wanted implement simple version in java, therefore used self-implemented method (extend euclid) calculating inverse of polynomial in ring. most of times algorithm works, when try example ntru-pkcs-tutorial pkcs-tutorial fails , dont know why. the example is: f: -x^10+1x^9+0x^8+0x^7+1x^6+0x^5-x^4+0x^3+1x^2+1x^1-x^0 f^-1 mod 32: 30x^10+18x^9+20x^8+22x^7+16x^6+15x^5+4x^4+16x^3+6x^2+9x^1+5x^0 ring: x^11-1 my code is: public polynomialmod inverse(int n, int mod) { int loop = 0; polynomialmod g = polynomialmod.zero.clone(); g.setnmod(n, mod); polynomialmod newg = (polynomialmod) polynomialmod.one.clone(); newg.setnmod(n, mod); int[] coeffr = { 1, 1, 0, 1, 1, 0, 0, 0, 1 }; polynomialmod quotient = null; polynomialmod newr = this.clone(); polynomialmod r = this.getring(n, mod); r.setnmod(n, mod); newr.setnmod(n, mod); while (!newr.equalszero()) { if (debug && loop != 0) sys

How to make git diff show the same result as github's pull request diff? -

after branches merged, , github no longer show difference when try make pull request, git diff still show differences. for example have branch d, created hotfix on branch h, merged h d, created more stuff on d. git hub pull reuqest h d shows no difference git diff h d show differences. what trying create commandline tool see old branches (there can lot) don't have code differences develop. right have go github, pull reuqest , select each branch see if there difference. thanks you want "triple-dot" syntax: git diff d...h see what differences between double-dot ".." , triple-dot "..." in git diff commit ranges?

ElasticSearch: compare dotted version strings -

i'm looking way save dotted version string (e.g "1.2.23") in elastic , use range query on field. e.g { "query": { "range": { "version": {"gte": "1.2.3", "lt": "1.3"} } } } i have 3 components (major, minor, build). need able determine 1.20.3 > 1.2.3 1.02.4 > 1.2.3 1.3 > 1.2.3 i thought following approaches: pad zeros (e.g "1.2.3" -> "000001.000002.000003"). assumes know max length of each component split 3 different integer fields (i.e "major", "minor", "build"). writing queries seems pain, i'd happy suggestions this. perhaps sort of custom analyser? saw this: elasticsearch analysis plugin natural sort might start. any other ideas or recommendations? if have latitude in indexing code massage semantic versions else, suggest transform each version unique integer , it's easy compare numbe

c - AVR gcc, weird array behaviour -

it's first time see this. i'm starting suspect it's hardware fault. whenever try send contents of array "test" , array larger 4 elements or initialize elements in declaration contains 0xff instead of values try initialise with. this works fine. when read values array in while(sending them lcd , uart) both readouts consistent test values: uint8_t i=0; uint8_t test[4] = {1,2,3,4}; while(i<5){ glcd_writedata(test[i]); usart_transmit(test[i]); i++; } this doesn't, returns 0xff instead of test[i] value: uint8_t i=0; uint8_t test[5] = {1,2,3,4,5}; while(i<5){ glcd_writedata(test[i]); usart_transmit(test[i]); i++; } but works! returns proper values uint8_t i=0; uint8_t test[6] = {1,2,3,4,5}; while(i<5){ glcd_writedata(test[i]); usart_transmit(test[i]); i++; } this works: uint8_t i=0; uint8_t test[5]; test[0]=1; test[1]=2; test[2]=3; test[3]=4; test[4]=5; while(i<5){

Tokbox Screen Sharing On/Off Toggle in iOS Objective C -

i want provide screen sharing on/off feature in ios using tokbox . i able switch device screen share after sharing screen not able switch device camara. i have tried following code. -(void)tooglescreen{ if (issharingenable == yes) { issharingenable = no; nslog(@"%@",_publisher.description); _publisher.videocapture = nil; [_publisher setvideotype:otpublisherkitvideotypecamera]; _publisher.audiofallbackenabled = yes; } else { issharingenable = yes; [_publisher setvideotype:otpublisherkitvideotypescreen]; _publisher.audiofallbackenabled = no; tbscreencapture* videocapture = [[tbscreencapture alloc] initwithview:self.view]; [_publisher setvideocapture:videocapture]; } } it looks might not setting video capturer when turning off screencapture. line: _publisher.videocapture = nil; is needlessly destructive. try keeping internal references camera ,

When installing php on Ubuntu/Debian, how do I choose the development php.ini -

i believe there php.ini settings optimized development. how can install 1 easy way? based on kronwalled's answer, enter in shell sudo cp /usr/lib/php/7.0/php.ini-development /etc/php/7.0/apache2/php.ini sudo cp /usr/lib/php/7.0/php.ini-development /etc/php/7.0/cli/php.ini

javascript - Laravel "MethodNotAllowedHttpException in RouteCollection.php line 219" -

Image
i'm wondering right why particular table interacting database returns error above subject in fact using same mechanism other table. refering table "inventory". store method returns error stated in subject above , have checked parameters in controller , in model , seems there no error. can me spot error here. please help. here codes. inventorycontroller.php public function store( request $request ){ $prod_ids = $request['product_ids']; $purchase_order_ids = $request['purchase_order_ids']; $purchase_ids = $request['purchase_ids']; $quantity = $request['purchasequantity']; for($i = 0; $i < count($prod_ids); $i++){ inventory::create([ 'product_id' => $prod_ids[$i], 'purchase_order_id' => $purchase_order_ids[$i], '