Posts

Showing posts from May, 2012

How can I access methods of different classes in java using the array of type Object -

here code: public static void main(string args[]) { circle objcircle = new circle(5); square objsquare = new square(5); triangle objtriangle = new triangle(3, 4); sphere objsphere = new sphere(5); cube objcube = new cube(5); tetrahedron objtetra = new tetrahedron(5); object[] shape = new object[5]; shape[0] = objcircle; shape[1] = objsquare; shape[2] = objtriangle; shape[3] = objsphere; shape[4] = objcube; shape[5] = objtetra; for(int = 0; i<shape.length; i++) { //problem occured in section of code system.out.println(shape[i].getarea()); } } } i have 6 different classes , of them have getarray() method definition of own. want print values getarray() method returns different classes using shape array. define interface below. implement interface in class circle , square .. public interface shape { public double getarea(); } then can different classes getarea below. shape [] sha...

javascript - Upload to Google Drive and show progress percentage -

i'm using code below upload large files google drive. how can display progress numeric percentage? i don't want show progress bar, percentage "20%". server.gs function doget(e) { return htmlservice.createhtmloutputfromfile('upload.html'); } function uploadfiles(form) { try { var dropbox = "uploads"; var folder, folders = driveapp.getfoldersbyname(dropbox); if (folders.hasnext()) { folder = folders.next(); } else { folder = driveapp.createfolder(dropbox); } var blob = form.myfile; var file = folder.createfile(blob); file.setdescription("videoname_number: " + form.myname); return "episode uploaded " + file.geturl(); } catch (error) { return error.tostring(); } } upload.html <div> <form id="myform"> <input type="text" name="myname" placeholder="videoname_number"> <input ...

`size` has no method matching size(::Data{Float32}) when using nested composite type in julia -

say defined composite type "data" follows: type dataformat format1::datatype format2::uint format3::uint format4::ptr{none} end type data{t} <: abstractvector{t} value::vector{t} format::dataformat end it's ok when run myformat = dataformat(float32, 0, 0, c_null) . run mydata = data{float32}([0.1, 0.2, 0.3], myformat) , these errors appear: error showing value of type data{float32}: error: `size` has no method matching size(::data{float32}) in writemime @ replutil.jl:18 in display @ repl.jl:117 in display @ repl.jl:120 in display @ multimedia.jl:149 in print_response @ repl.jl:139 in print_response @ repl.jl:124 in anonymous @ repl.jl:586 in run_interface @ /opt/homebrew-cask/caskroom/julia/0.3.7/julia- 0.3.7.app/contents/resources/julia/lib/julia/sys.dylib in run_frontend @ /opt/homebrew-cask/caskroom/julia/0.3.7/julia-0.3.7.app/contents/resources/julia/lib/julia/sys.dylib in run_repl @ /opt/homebrew-cask/caskroom/julia/0.3....

sql server - How to update column of a table after group by with condition in SQL? -

i new user of sql c# . i'm faced problem, have sql table column these are: id, receiptno, modelname, size, quantity, priceperunit, totalprice. after group size column want update ' quantity ' column condition. condition is, want decrease/minus/less/update ' quantity ' row after row. when 'quantity' '0' jump next row & find quantity & decrease this. here data: |id | |receiptno| |modelname| |size| |quantity| |priceperunit| |totalprice| --------------------------------------------------------------------------- |1| |001| |abcd| |xxl| |0| |120| |0| |2| |002| |abcd| |xxl| |6| |120| |720| |3| |003| |abcd| |xxl| |7| |120| |840| |4| |004| |appp| |xl | |2| |60 | |120| i want decrease first 3 rows ' 8 ' quantities using group size column. how that? you should able : update your_table set quan...

intranet - How can you limit a website/ resource to a list of IPs/ Network? -

i know may basic, or possibly wide-scope, question --- not extremely grounded in world, ---- how websites (or things company networks/ intranets) --- restricted range of computers or "the network" or range of ips? in other words, if wanted set website/ intranet can accessed employees, how accomplish this? or direction in?

android - ServiceLoader.load is not finding the META-INF/services -

so want build extensible android application developers can add 'customdevice' classes , main program run them automatically without editing existing code. i've read service provider interface , thought nice way go it. so tested , created interface called 'icustomdevice' custom device classes expected implement. i've created class called 'dummydevice' implements icustomdevice. both dummydevice , icustomdevice in same package "customdevicepackage". so in main program run following. serviceloader<icustomdevice> loader = serviceloader.load(icustomdevice.class); iterator<icustomdevice> devices = loader.iterator(); system.out.println("does have devices? " + devices.hasnext()); it returns false, means it's not finding 'dummydevice' in eclipse project created folder @ 'src' called meta-inf , under it, subfolder called 'services'. 'services' has file named '...

mongodb - Pymongo can not perform aggregating with pipeline in too large collection -

i have billions records in patients colletion , have no idea how filter pipeline. or limit on mongodb, couldn't aggregate pipeline on large collection ? i've add allowdiskuse=true option, doesn't work too. how filtered result pipeline ? how store filtered result collection ? sample code (i use pymongo follows in python syntax ) import datetime pipeline = [ {"$project": {"birthday":1, "id":1} }, { "$match": { "birthday":{"$gte":datetime.datetime(1987, 1, 1, 0, 0)} } },{"$group": ~~~ } ] res =db.patients.aggregate(pipeline,allowdiskuse=true) exception message operationfailure: command son([('aggregate', u'patients'), ('pipeline', [{'$match': {'birthday': {'$gte': datetime.datetime(1987, 1, 1, 0, 0)}}}]), ('allowdiskuse', true)]) on namespace tw_insurance_security_development.$cmd ...

html - Can a table run in a php while loop? -

i attempting create table pulls data database via query, can not table display whatsoever when put inside while loop need data. doing wrong code or not possible thing? post both css , html edit 2: calculations variables such $diff $str5npos = ($str5npos /100); $str5npos = $str5npos +12.015; $str5nposgraph = (($str5npos/40) *100); $str5spos = ($str5spos /100); $str5spos = $str5spos +12.015; $str5sposgraph = (($str5spos/40) *100); $total5= round($str5npos + $str5spos); $diff5 = round($str5npos - $str5spos); $direction5 = 'north'; if ($diff5 < 0) { $direction5 = 'south'; } edit: here query $result = mysql_query("select * p4updates db4primekey = 4"); // fetch live values data base while($row = mysql_fetch_array($result)) { $str1npos = $row['str1npos'];$str1spos = $row['str1spos'];$str2npos = $row['str2npos'];$str2spos = $row['str2spos'];$str3npos = $row['str3npos']; $str3spos = $row['str...

ios - Why keyboard hides when I apply custom push animation? -

i have 2 controllers uitextfields on them. need custom transition between them keyboard shown, alongside transition. when i'm using default push animation, good. if return transition class animationcontrollerforoperation , keyboard hiding before , showing after transition. so, suggest me solution or explanation, why keyboard hiding custom transition? transition duration = 0.4, i've set [textfield becomefirstresponder] in viewdidload . here video: https://www.youtube.com/watch?v=gs16tmsu4qy take @ uiviewcontrollertransitioncoordinator class. here answer similar issue: https://stackoverflow.com/a/21017900

Am I allowed to fire DoExpressCheckoutPayment automatically for PayPal Express Checkout? -

my client wants automatically return user paypal during express checkout process, clicking "confirm , pay" button @ review stage if transaction price has not changed during process. i can this, wondering if against paypal terms of service seems me used trick user paying more expecting. i have searched on paypal site , had google, found nothing saying against terms. else or know whether it's acceptable practise? you mean want change amount in express api call against amount specified in set express api call . yes can change amount in express api call because of time merchant needs shipping address information buyer's paypal account. , once shipping address via express checkout api call ,shipping fee added authorized amount , express api called .

xcode - How do I run a Cocoa app after building it from the command line with xcodebuild? -

i'm building mac os x cocoa application command line using xcode project this: xcodebuild -scheme myapp -configuration debug how run once it's done building? i wrote script this: #!/bin/bash x=$( xcodebuild -showbuildsettings -project myapp.xcodeproj | grep ' build_dir =' | sed -e 's/.*= *//' ) dyld_framework_path=$x/debug dyld_library_path=$x/debug $x/debug/myapp.app/contents/macos/myapp (i figured out running application xcode , ps -wwe -p on process see environment variables.)

c# - Embedding a Manifest File in Visual Studio 2012 -

my understanding can right click project , choose new item , application manifest file embed manifest file in application. i've done when go project properties , @ application tab , can see manifest greyed out. case whether manifest file i've created in project or not - it's greyed out. although being greyed out embed manifest default settings . says me 1 of 2 things - 1) greyed out because there not manifest in debug folder dll have rely on embedded 1 or 2) 1 have created not embedded in project. if 1), , embedded 1 being used it. other 1 i've created, cannot find more!! i've tried restarting visual studio, rebuilding etc. i've searched internet , consensus i've done should work. the other possibility has occurred manifest files not work dll plugins :-0 the other possibility has occurred manifest files not work dll plugins :-0 that's correct. manifests executables visual studio. if need embed manifest in dll, registra...

multithreading - C++ : std::atomic<bool> and volatile bool -

i'm reading c++ concurrency in action book anthony williams. , there classic example 2 threads, 1 produce data, other 1 consumes data , a.w. wrote code pretty clear : std::vector<int> data std::atomic<bool> data_ready(false) void reader_thread() { while(!data_ready.load()) { std::this_thread::sleep(std::milliseconds(1)); } std::cout << "the answer=" << data[0] << "\n"; } void writer_thread() { data.push_back(42); data_ready = true; } and don't understand why code differs 1 i'd use classic volatile bool instead of atomic one. if open mind on subject, i'd grateful. thanks. the big difference code correct, while version bool instead of atomic<bool> has undefined behavior. these 2 lines of code create race condition (formally, conflict ) because read , write same variable: reader while (!data_ready) and writer data_ready = true; and race condition...

javascript - Bootstrap Affix menu bouncing between upper and lower limits? -

i'm having problems using bootstrap affix feature on sidebar menu. want menu fix position scroll down long content page, stop when footer. have tried setting top , bottom offsets so: $('#sidebar-subnav').affix({ offset: { top: $('#sidebar-subnav').offset().top, bottom: $('footer').outerheight(true) } }); i set when scroll down, once side nav @ top of window locks in place should stop when hits footer. when view in browser though, keeps blinking bouncing between upper , lower bound. thinking didn't implement correctly, haven't had luck fixing it. can me out on this? see in action go http://www.thecafa.org/about/news/news-test thanks, brian

ios - Screen doesn't update when I change a UILabel's text -

my environment xcode 6.3, target ios8.3 ipad. i'm learning master-detail view using xcode's template. strange problem appears when try set label's text in detail view: if put statement changes label's text in p1 position, works. but if put statement in p2 position, doesn't work. under both circumstances, detaildescriptionlabel.text changed, p1 statement update screen.(i have checked function configureview() called both times) can helps me? lot. below code snippets: mastercontroller.m: #import "masterviewcontroller.h" #import "detailviewcontroller.h" @interface masterviewcontroller () @property (copy, nonatomic) nsmutablearray *objects; @end @implementation masterviewcontroller - (void)awakefromnib { [super awakefromnib]; self.clearsselectiononviewwillappear = no; self.preferredcontentsize = cgsizemake(320.0, 600.0); } - (void)viewdidload { [super viewdidload]; // additional setup after loading view, typ...

c# - Insert a csv file into Azure SQL from an Azure Blob -

i have asp.net (c#) site in azure , accompanying azure sql database. need upload 1gb+ csv files , them parsed , azure sql database. can csv files azure blob. have url blob (newguid.txt). either sql or web app, how parse csv , inserted azure sql database? (the csv has 36 columns if helps) i can't figure out how reference url use sqlblukcopy. thought bulk insert azure sql doesn't allow that. can't download files locally , use bcp each one. i agree old question, gets traction, here answer: you can use azure data factory move data blob storage (and many more data sources) azure sql database (and many other data sinks). there nothing simpler today achieve goal. here tutorials: move data using copy activity move data , azure blob move data , sql server running on-premises or on azure vm (iaas) you can configure data pipeline run once. or run on specific time, or run on schedule. can make copy single file, or using file pattern more files, etc. ...

JWplayer: Display image when no video detected -

i have website show stream visitors using jwplayer. i want know if there way replace video image in jwplayer when stream out instead of error message? absolutely. http://support.jwplayer.com/customer/portal/articles/1442607-example-a-custom-error-message jwplayer().onerror(function(){ ​jwplayer().load({file:"http://www.com/errorfile.mp4",image:"http://www.com/errorfile.jpg"}); jwplayer().play(); });

c++ - Visual Studio 2013 optimization flags (/O2 vs /Ox) -

this question has answer here: what difference between /ox , /o2 compiler options? 2 answers i've been trying read through msdn pages on various optimization flags. we have of our projects set /o2 optimizes "maximize speed". my confusion means. of following statements closer true regarding /o2 flag? optimize code both speed , size, if there contention prefer optimization speed optimize code only speed, not optimize size. i made argument should use /ox flag, when under impression option 2 true. i told "we're not going change /o2 /ox unless has solid evidence need so". so question /o2 still perform memory optimizations? e.g. return value optimization, copy elision, etc. gain switching /o2 /ox ? as arkanosis pointed out correctly, when going /o2 /ox, disable /gs, /gf, /gy . question which of these flags may i...

Insert new array to php json -

i tried push new array value json $var=array("code"=>"100"); $sql = select order orderid, pub ordercode cart while ($row = mysql_fetch_assoc ($sql) { $var[] = $row; } echo '{"status":'. json_encode($var).'}'; i want push string json array above $string = array("total"=>"3000"); and script displays this: { "status":{ "code":"100", "0":{ "total":"3000" }, "1":{ "orderid":"16", "ordercode":"14290290685322" }, "2":{ "total":"3000" } } } and want var total inside this: **////////blablabla "1":{ "orderid":"16", "ordercode":"14290290685322", "total":"3000" ...

Python - if statements involving numpy arrays -

i'm opening image , converting array of rgba values. here's code: img = image.open('17112013.png') imgarray = array(img) l = imgarray[:,1,1] m = imgarray[1,:,1] n = imgarray[1,1,:] bluecount = 0 redcount = 0 flag = 0 in range(0,len(l)): j in range(0,len(m)): if (imgarray[i,j] == [255,255,255,255]): pass if (imgarray[i,j] == [0,0,0,255] , flag == 0): pass if (imgarray[i,j] == [255,0,0,255] , flag == 0): pass if (imgarray[i,j] == [0,0,255,255]): flag = 1 bluecount = bluecount + 1 if (imgarray[i,j] == [255,0,0,255] , flag == 1): redcount = redcount + 1 if (imgarray[i,j] == [0,0,0,255] , flag == 1): flag = 0 if (imgarray[i,j] == [255,255,255,255] , flag == 1): flag = 0 if run such, receive following: valueerror: truth value of array more 1 element ambiguous. use a.any() or a.all() i understand need use thes...

python - Regular expression pattern questions? -

i having hard time understanding regular expression pattern. me regular expression pattern match words ending in s. , start , end (like ana). how write ending? word boundaries given \b following regex matches words ending ing or s: "\b(\w+?(?:ing|s))\b" \b word boundary, \w+ 1 or more "word character" , (?:ing|s) uncaptured group of either ing or s . as asked "how develop regex": first: don't use regex complex tasks. hard read, write , maintain. example there a regex validates email addresses - computer generated , nothing should use in practice. start simple , add edge cases. @ beginning plan characters need use: said need words ending s or ing . need represent word, endings of words , literal characters s , ing . word? might change case case, @ least every alphabetical character. looking in python documentation on regexes can find \w [a-za-z0-9_] , fits impression of word character. there can find \b word boundary. s...

wpf - How to press Alt+Tab programmatically in C# in win 8 -

i use code in vs 2013 in win8 simulate press alt+tab, nothing happen. test in win 7 , vs 2012 it's work fine. [system.runtime.interopservices.dllimport("user32.dll")] public static extern void keybd_event(byte bvk, byte bscan, int dwflags, int dwextrainfo); private const byte vk_menu = 0x12; private const byte vk_tab = 0x09; private const int keyeventf_extendedkey = 0x01; private const int keyeventf_keyup = 0x02; keybd_event(vk_menu, 0xb8, 0, 0); //alt press keybd_event(vk_tab, 0x8f, 0, 0); // tab press system.threading.thread.sleep(70); keybd_event(vk_tab, 0x8f, keyeventf_keyup, 0); // tab release keybd_event(vk_menu, 0xb8, keyeventf_keyup, 0); // alt releas how can solve problem in win8? thanks may late answer answered question may other in future. try send key combination using sendkeys may work you. sendkeys.send("%+{tab}");

c# - How to avoid reference comparison with self implemented value types -

i'm trying implement value type in general mimics behavior of type short. so far comparison , assignments between value type , short working out fine, when boxing jumps in problems starts. below can find unit tests illustrating problem source value type. the first assert method uses overriden equals method of value type, second assert result in reference comparison (runtimehelpers.equals(this, obj);) of course fails. the test: [testmethod] public void equalstest() { const short short_type = 1; myvaluetype valuetype = short_type; object shortobject = short_type; object valueobject = valuetype; assert.istrue(valueobject.equals(shortobject)); // success assert.istrue(shortobject.equals(valueobject)); // failed, comparing 2 references } the value type: [comvisible(true)] [serializable] [structlayout(layoutkind.sequential)] [debuggerdisplay("{_value}")] public struct myvaluetype : icomparable, iformattable, iconvertible, icomparable...

hive - Filtering null values in Scala -

i have hive table has null , empty values in columns. null values representation in table \n . trying select rows column not null in scala. have tried using a. if (a.equals("\\n")) b. if (!option(a).getorelse("").isempty) c. using length(trim(a)) none of these options worked code either filter not work or rows excluded. does has suggestions? according https://cwiki.apache.org/confluence/display/hive/languagemanual+transform , hive's \n string, "\n", in java , hence in scala that's represented "\n" can matched using {scala.predef.string = java.lang.string}.matches("\\n") in following test: val s = "\\n" println(s.matches("\\\\n")) // prints true if not work please provide information how accessing hive table , hive version can attempt replicate error.

python - Better approach to handling sqlalchemy disconnects -

we've been experimenting sqlalchemy's disconnect handling, , how integrates orm. we've studied docs, , advice seems to catch disconnect exception, issue rollback() , retry code. eg: import sqlalchemy sa retry = 2 while retry: retry -= 1 try: name in session.query(names): print name break except sa.exc.dbapierror exc: if retry , exc.connection_invalidated: session.rollback() else: raise i follow rationale -- have rollback active transactions , replay them ensure consistent ordering of actions. but -- means lot of code added every function wants work data. furthermore, in case of select , we're not modifying data , concept of rollback/re-request not unsightly, violation of principle of dry (don't repeat yourself). i wondering if others mind sharing how handle disconnects sqlalchemy. fyi: we're using sqlalchemy 0.9.8 , postgres 9.2.9 the way approach place da...

PHP write to file on external server -

i trying write file on external server php. have ftp details. here code $handle = fopen("ftp://usn:pass@domain/folder/file.html", "a"); fwrite($handle, "some text"); fclose($handle); upon execution "the connection reset. connection server reset while page loading." error in browser. doing wrong? it works in local server approach absolutely possible. guess 000webhost has set ini_set("allow_url_fopen ", 0); in php.ini

Restrict SSL protocols to TLS 1.2 on Vert.x -

i'd restrict ssl protocols tls 1.2 on vert.x 2.1.5 http server , client. i'm using jdk 7. have experience on how it? oracle says here ssl protocols should restricted on jre 7 explicitly setting enabled protocols on ssl engine: sslengine.setenabledprotocols(new string[] {"sslv2hello", "tlsv1", "tlsv1.1", "tlsv1.2"}); now check out tcpsslhelper.java class in vert.x v2.1.5. there constant containing list of enabled protocols, , it's used set enabled protocols on ssl engine: // make sure sslv3 not enabled due poodle issue private static final string[] enabled_protocols = {"sslv2hello", "tlsv1", "tlsv1.1", "tlsv1.2"}; change value {"tlsv1.2"}; limit support tlsv1.2. for quick test: create org.vertx.java.core.net.impl package in own project copy tcpsslhelper package , edit enabled protocols constant build , run. curl using specific protocol directives, ...

java - Build MOJO with Javafx 8 -

Image
i looking find example on building mojo application using javafx 8. have small application of mojo using swings , awt. trying replace usage of swing , awt using javafx. confused on how integrate mojo javafx. on providing examples should enough me further research on application. below mojo program using swing , awt. import javax.swing.jframe; import java.awt.event.*; import java.awt.*; import com.esri.mo2.ui.bean.map; import com.esri.mo2.ui.tb.zoompantoolbar; import com.esri.mo2.ui.bean.layer; import com.esri.mo2.ui.bean.toc; public class quickstart2 extends jframe { map map = new map(); layer layer = new layer(); layer layer2 = new layer(); toc toc = new toc(); string s1 = "c:\\esri\\moj20\\samples\\data\\usa\\states.shp"; string s2 = "c:\\esri\\moj20\\samples\\data\\usa\\capitals.shp"; zoompantoolbar zptb = new zoompantoolbar(); public quickstart2() { //add title window super("quick start"); //set size this.setsi...

python - Grouping and finding most frequent values -

i have df this: protein peptide aaa aaa aba b aaa b aba b aba but need filter data finding each value in column 1 top occurring value in column 2. so output like: protein peptide aaa b aba in reality need top 3 occuring values. don't know how solve using python , pandas? mode isn't groupby method, though series (and dataframe ) method, have pass apply : in [11]: df.groupby('protein')['peptide'].apply(lambda x: x.mode()[0]) out[11]: protein aaa b aba name: peptide, dtype: object to top three, use value_counts (in same way): in [12]: df.groupby('protein')['peptide'].apply(lambda x: x.value_counts()[:3]) out[12]: protein aaa 2 aba 1 b aba 2 aaa 1 dtype: int64

java - Stop IWizard for Warning Message -

i doing eclipse plug-in development... when user clicks finish, making service call return 3 options. 1. okay proceed 2. give user warning 3. stop finish so 1 , 3 easy. here doing 3: istatus status = new status(istatus.error, activator.plugin_id, istatus.ok, message, e); throw new coreexception(status); so throw exception , popup message dialog message passing it. i stuck on number 2... i have tried following: messagedialog dialog = new messagedialog(null, thetitle, dialog.getimage(dialog.dlg_img_warning), dialogmessage, messagedialog.warning, new string[]{"yes", "no"}, 0); int returncode = dialog.open(); if(returncode == 0){ //proceed finish } else if(returncode == 1){ //stop finsih return; } here message receiving when doing this: null argument:the dialog should created in ui thread is possible give user warning message after clicks finish? all ui code must created , run in ui thread. if want display dialog other thr...

linux - How to replicate yum command via rpm? -

i'd install rpms via 'rpm' command how 'yum install' accomplishes task. i've downloaded rpm , required dependencies via command yum install --downloadonly --downloaddir=. <package> however when issue command rpm -ivh *.rpm the rpms fail install citing fail dependencies such following: [18:45:05][root][~/test]$ rpm -ivh * warning: authconfig-6.1.12-13.22.amzn1.x86_64.rpm: header v3 rsa/sha256 signature, key id 21c0f39f: nokey error: failed dependencies: dbus-python <= 0.83.0-6.1.11.amzn1 obsoleted dbus-python26-0.83.0-6.1.13.amzn1.x86_64 yum-updatesd <= 1:0.9-13.14.amzn1 conflicts dbus-python27-0.83.0-6.1.13.amzn1.x86_64 dbus-python <= 0.83.0-6.1.11.amzn1 conflicts dbus-python27-0.83.0-6.1.13.amzn1.x86_64 yum-updatesd <= 1:0.9-13.14.amzn1 conflicts gamin-python-0.1.10-16.14.amzn1.x86_64 newt-python <= 0.52.11-3.7.amzn1 obsoleted newt-python26-0.52.11-3.11.amzn1.x86_64 yum-updates...

c# - OxyPlot Add points after axis drag -

i want add points dynamicall after axis drag, how can figgure out, axis dragged , where? can start point , end point of displayed axes(x )? using oxyplot; using system; using system.collections.generic; using system.linq; using system.text; using system.windows; using system.windows.controls; using system.windows.data; using system.windows.documents; using system.windows.input; using system.windows.media; using system.windows.media.imaging; using system.windows.navigation; using system.windows.shapes; namespace wpfapplication15 { /// <summary> /// interaction logic mainwindow.xaml /// </summary> /// public class dataloading { public plotmodel plotmodel { get; set; } oxyplot.axes.linearaxis x; oxyplot.axes.linearaxis y; private oxyplot.series.lineseries firstseries; private oxyplot.series.lineseries secondseries; public dataloading() { plotmodel = new plotmodel(); x = new oxyplot.axes.linearaxis() { posi...

arrays - Loop Iteration avoid same indexes javascript -

i've scenario want walk in array in javascript, , checking if index matches option push or print once. ive following array: ["item1", "dummydata1", "dummydata2", "item2", "dummydata1", "dummydata2", "item3", "dummydata1", "dummydata2", "item4", "dummydata1", "dummydata2", "item4", "dummydata1", "dummydata2", "item4", "dummydata1", "dummydata2", "item4", "dummydata1", "dummydata2", "item5", "dummydata1", "dummydata2", "item5", "dummydata1", "dummydata2", "item6", "dummydata1", "dummydata2", "item7", "dummydata1", "dummydata2", "item7", "dummydata1", "dummydata2"] i want iterate array on every thing , if thing index matc...

PDO multiple queries in php /sql -

i have following code. grabbing values form, , using values try update "customers" , "workorder". "name" value duplicate across customers , workorder table. keep on getting error "number of bound variables not match number of tokens". totally new using pdo, , unsure on how proceed. ideas? $pdo = database::connect(); $pdo->setattribute(pdo::attr_errmode, pdo::errmode_exception); $sql = "update customers set name = ?, email = ?, mobile =? id = ?; update workorder set name = ?;"; $q = $pdo->prepare($sql); $q->execute(array($name,$email,$mobile,$id)); database::disconnect(); header("location: index.php"); you have 4 variables here: $q->execute(array($name,$email,$mobile,$id)); should 5: $q->execute(array($name,$email,$mobile,$id, $name));

c# - Replicate IO Exception Error -

i able reproduce following error: ioexception: unable read data transport connection: existing connection forcibly closed remote host. any ideas on how can making web request , causing error occur? i've tried making web request , unplugging network cable didn't reproduce error, i'm intrigued how can make happen. the last line produce exception. the idea is: creating tcp listener (or http listener) , closing connection without sending valid http response. taskcompletionsource<object> tcs = new taskcompletionsource<object>(); task.run(() => { tcplistener listener = new tcplistener(8080); listener.start(); tcs.trysetresult(null); while (true) { listener.accepttcpclient().close(); } }); await tcs.task; //wait till tcplistener ready webclient wc = new webclient(); var str = await wc.downloadstringtaskasync("http://localhost:8080");

Android: parse the JSON file in the raw folder with gson? -

i trying parse json file"ssid-number" in raw folder gson. parse_ssid method parses json file , finds mapping passed ssid string. getting @ momenat error: the method getwifilist() undefined type wifijson @ line list<wifijson> wifijson = obj.getwifilist(); . approach correct? json file: { "data": [ { "ssid": "kd privat", "route_number": 1 }, { "ssid": "kd wlan hotspot", "route_number": 4 }, { "ssid": "fr wlan", "route_number": 6 } ] } parse_ssid method in mainactivity: private int parse_ssid(string ssid) { inputstream raw = getresources().openrawresource(r.raw.ssid_number); reader rd = new bufferedreader(new inputstreamreader(raw)); gson gson = new gson(); wifijs...

java - Microservices communication -

i'm studying microservices , i'm facing problem. context i m developing 2 microservices : user management, spring based, mysql database planning management, asp.net based sql server database. access point of service api listing restful endpoints /planning/{day}/{userid} or /planning/{startdate}/{enddate}/{iduser} billing management, node.js based mongodb. problems what can permit accessing planning information through user service without couple 2 services ? knowing planning service accessed later somewhere else, not now. how can access billing information billing service corresponding user mysql database? know microservices not coupled, , point killing me, cause has coupled in way no? referencing iduser in billing? else, how can know billing api should expose? more precisely, how microservices communicate between them, without coupled? how create authentication without duplicating authentication requests authentication service, other services? t...

Tinkerpop Frames: Query vertices based on interface type -

i'm using tinkerpop frames create set of vertices , edges. adding new vertex simple retreiving vertices based on type seems bit difficult. assume have class a , b , want add new 1 so: framedgraph.addvertex(null, a.class); framedgraph.addvertex(null, b.class); that's straight forward. if want retrieve vertices type a ? doing failed, because returned vertices (both a , b ). framedgraph.query().vertices(a.class); is there possible way this. tried check documentations , test cases no luck. how can retreive list of vertices of type a only this question looks it's duplicate of - how find vertices of specific class tinkerpop frames (also asked today). as far understand, tinkerpop frame framework acts wrapper class around vertex. vertex isn't stored interface class. such, need way identify vertex being of particular type . my solution, added @typefield , @typevalue annotations frame classes. use these values query framedgraph . the documen...

Package registration in Python versus IPython? -

i manually installed ibpy using "python setup.py install" under windows , winpython. packages seem appear in right dirs; c:\winpython-32bit-3.4.3.2\python-3.4.3\lib\site-packages\ib\ext c:\winpython-32bit-3.4.3.2\python-3.4.3\lib\site-packages\ib\lib etc. running: from ib.ext.contract import contract ib.ext.order import order ib.opt import ibconnection, message works fine in ipython, in python , eclipse get: importerror: no module named 'ib.ext'; 'ib' not package in eclipse can see ib , subdirs packages. any suggestions? thx

javascript - On click function parameters Knockout -

i trying pass 1 parameter function knockout click binding. if try sending without binding, works. here fiddle of working code without binding: https://jsfiddle.net/obviously/ev0lcx7q/4/ but if try binding this, not works: <input class="sometextbox"> <button type="button" data-bind="click: $root.somefunction.bind($root,$(this).siblings('input').val())"> search! </button> i error @ $(this), javascript runtime error: object doesn't support property or method 'siblings' $element gives access current element in knockout binding. <input class="sometextbox"> <button type="button" data-bind="click: $root.somefunction.bind($root, $($element).siblings('input').val())"> search! </button> note using jquery in knockout binding not common approach.

swift - Fetching nearby places using google maps -

am trying implement find nearby places of current location using google maps. have created project in google developer console , got 'ios apikey' , 'server apikey'. enabled google places api , google maps sdk ios. below code find out near places. func fetchplacesnearcoordinate(coordinate: cllocationcoordinate2d, radius: double, name : string){ var urlstring = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=\(apiserverkey)&location=\(coordinate.latitude),\(coordinate.longitude)&radius=\(radius)&rankby=prominence&sensor=true" urlstring += "&name=\(name)" urlstring = urlstring.stringbyaddingpercentescapesusingencoding(nsutf8stringencoding)! println(urlstring) if placestask.taskidentifier > 0 && placestask.state == .running { placestask.cancel() } uiapplication.sharedapplication().networkactivityindicatorvisible = true placestask = session.datataskwithurl(nsu...

java - Spring RequestMapping to read encoded &amp -

i'm trying requestmapping pick following url pathname. action?param1=6&amp;param2=b&amp;param3=true&amp;param4=50652&amp;param5=2 i'm able path below work. when converting & '& amp;' unable read parameters. action?param1=6&param2=b&param3=true&param4=50652&param5=2 method action @requestmapping(value = "/action", method = requestmethod.get) public modelandview doaction(httpservletrequest httprequest, httpservletresponse httpresponse) throws exception { log.info(httprequest.getparameter("param1")); } fyi want steer clear of string manipulations

php - Observer design pattern in Yii 1.1.16, attaching event handlers and rising events -

in yii 1.1.16 observer design pattern implemented using events & behaivours (events can shared between components extends ccomponents ). have following models: user.php (see below) work.php (see below) activity.php what want accomplish following: lets in defaultcontroller: <?php public function actionexamplework() { $work = new work(); $work->description = 'some random description'; $work->created_at = new cdbexception('now()'); $work->user_id = 1; //$work->attach() invoke event handled models listen event $work->save(); } public function actionexampleuser() { $user = new user(); $user->email = 'foo@example.com'; $user->username = 'example'; $user->password = '123'; //$user->attach( ) invoke event should handled activity model $user-> save(); } ?> actually have saw lot of examples yii doing related things, far no ...

How to perform a full text search in MongoDb with C#? -

i'm using latest mongodb api. i have entity class entity { objectid id {get;set;} string text {get;set;} } //create text index entitycollection.indexes.createoneasync(indexkeys<entity>.textall().tobsondocument()); i can see index presents in db, when i'm trying perform search in mongovue query { $text: {$search: '<existent-word>'}} so receive nothing. maybe need rebuild index in way? how c#? how perform full text search functionality sorting relevance (score) in c#? update. ind [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "db.entities" }, { "v" : 1, "key" : { "_fts" : "text", "_ftsx" : ...