Posts

Showing posts from January, 2014

Output shell command in python -

def run_command(command): p = subprocess.popen(command, stdout=subprocess.pipe, stderr=subprocess.stdout) return p.communicate() on running : command = ("git clone " + repo).split() run_command(commmnd) everything working.but when try run multiple commands got error. command = ("git clone www.myrepo.com/etc:etc && cd etc && git stash && git pull).split() run_command(command) use subprocess.check_output() shell=true option, heed security warning re untrusted inputs if applies you. import subprocess command = 'git clone www.myrepo.com/etc:etc && cd etc && git stash && git pull' try: output = subprocess.check_output(command, shell=true) except subprocess.calledprocesserror exc: print("subprocess failed return code {}".format(exc.returncode)) print("message: {}".format(exc.message)) after output ...

DAPL errors on Azure RDMA-enabled SLES cluster -

i set 2 azure a8 vms in availability set running sles-hpc 12 (following tutorial here: https://azure.microsoft.com/en-us/documentation/articles/virtual-machines-linux-cluster-rdma/ ). when run intel mpi pingpong test, getting dapl errors: azureuser@sshvm0:~> /opt/intel/impi/5.0.3.048/bin64/mpirun -hosts 10.0.0.4,10.0.0.5 -ppn 1 -n 2 -env i_mpi_fabrics=shm:dapl -env i_mpi_dynamic_connection=0 -env i_mpi_dapl_provider=ofa-v2-ib0 /opt/intel/impi/5.0.3.048/bin64/imb-mpi1 pingpong sshvm1:d28:bef0eb40: 12930 us(12930 us): dapl_rdma_accept: err -1 input/output error sshvm1:d28:bef0eb40: 12946 us(16 us): dapl err accept input/output error [1:10.0.0.5][../../src/mpid/ch3/channels/nemesis/netmod/dapl/dapl_conn_rc.c:622] error(0x40000): ofa-v2-ib0: not accept dapl connection request: dat_internal_error() assertion failed in file ../../src/mpid/ch3/channels/nemesis/netmod/dapl/dapl_conn_rc.c @ line 622: 0 internal abort - process 0 similar errors when running 1 of osu mpi microbench...

php - Twitch API Live Callback Service -

i integrating twitch user account api platform , had through api see if there callback section of sort send update server when user starts streaming, can't seem find reference one. is there services offer sort of thing? if not, best way of running regular checks on of users in database see when streaming, of course doing alone kill server database queries, i'm stuck go now. what looking receive callback , create post in social feed user has started streaming. based on discussions @ links below, api doesn't support webhooks , won't anytime soon. instead, expect use polling. set worker process makes requests periodically, such every 5 minutes, creates appropriate social feed posts, etc. can batch them if have bunch of channels check (exaple from github issue): https://api.twitch.tv/kraken/streams?channel=riotgames,dota2ti,machinima,esltv_hearthstone https://github.com/justintv/twitch-api/issues/211 https://discuss.dev.twitch.tv/t/notifications-using...

Superimposing Multiple HTML Canvases with unique CSS Styles on top of Eachother -

i'm new stackoverflow , programming. i'm designing website right , wondering if me figure out how stack multiple html canvases on top of eachother, each own css style attached. right have square in middle of page css style attached establishes it's size, animates growth, etc. want top layer of several, larger squares have same effect (i.e. series of concentric squares expand when moused over.) here's html code: <html> <head> <meta charset="utf-8"/> <link href="hvr-grow.css" rel="stylesheet" type="text/css"> <link href="hvr-grow2.css" rel="stylesheet" type="text/css"> </head> <body onload="draw();"> <div> <canvas class="hvr-grow" id="magazine 1"></canvas> </div> <div> <canvas class="hvr-grow2" id="magazine 2"></canvas...

java - Debugging a Unity Android "Unable to convert classes into dex format" error on build -

i've been having trouble doing unity android build because of these dex format errors. i've looked @ similar errors people have had involving duplicate .jar files in unity project, i've removed culprits can find , still happening. updated unity facebook plugin , there several other plugins in project well, know prone have duplicate files. i can see there lot of "illegal argument exception" added translations errors, i'm assuming getting referenced twice, can't figure out these "accessibility service" files are. i'll admit rest of error i'm still trying figure out. i'm not super experienced java/android developer yet. does know might wrong? or have ideas of how might go debugging error further? error building player: commandinvokationfailure: unable convert classes dex format. see console details. /library/java/javavirtualmachines/jdk1.7.0_45.jdk/contents/home/bin/java -xmx2048m -dcom.android.sdkmanager.toolsdir=...

Is it possible to create a Windows exe on Linux using C++ with CMake? -

i'm working home windows pc on code, compile on linux pc on ssh connection. since resulting program creates gui, can't test it. possible create, besides linux program, windows exe can run on home computer? here cmakelists (using qt5): cmake_minimum_required(version 2.8.11) project(p3) set(cmake_prefix_path $env{qt5_qmake_dir}) message(status "qt5_qmake_dir: " ${cmake_prefix_path}) set(executable_output_path ${project_source_dir}/bin) set(library_output_path ${project_source_dir}/lib) set(cmake_include_current_dir on) set(cmake_verbose_makefile on) set(cmake_automoc on) # possibly set debug testing set(cmake_build_type release) include_directories(${cmake_current_binary_dir}) #project source directories find_package(qt5widgets required) find_package(qt5core required) find_package(qt5gui required) find_package(openmp) if (openmp_found) message("openmp found") set(cmake_c_flags "${cmake_c_flags} ${openmp_c_flags}") set(cmake_cxx_f...

c++ - Can i check if a chunk of memory (e.g., allocated using malloc) stays in the cache? -

assume allocate space using malloc. can check whether continuous memory remains within cpu's cache (or better within cache levels l1, l2, l3 etc.) in run-time ? determining content of cpu cache low level , beyond c can do. in fact, caching transparent code may writing cpu pretty decides cache , cannot afford waste timein convoluted logic on how so. quick googling on specific tools effect came intel tuning guide , performance analysis papers: https://software.intel.com/en-us/articles/processor-specific-performance-analysis-papers . obviously, vendor specific. amd have specific tools.

clojurescript - Checking if a Clojure(Script) Channel is Full -

suppose c channel of size n . trying write function in clojure(script) checks see if c full and, if so, closes channel. but how 1 check see whether channel full? core.async offers pair of functions this: offer ! put on channel if space available, , let know if full. poll ! gets if it's available , lets know if channel has nothing offer @ moment. so write like: (if-not (offer! my-chan 42) (close! my-chan)) which accomplish when putting on channel. safer trying have process watch moment get's full , close it. if want check if it's full can extract buffer , ask it: user> (->> (async/chan (async/buffer 1)) (.buf) (.full?)) false though think 1 through first.

json - What am I doing wrong with this Service Stack Web Service or jQuery call? -

i able service stack's hello world example working, i'm trying expand little return custom site object. made simple test html file uses jquery pull result back, i'm not getting site object returned (i think). here's web service: using funq; using servicestack.serviceinterface; using servicestack.webhost.endpoints; using system; namespace my.webservice { public class siterepository { } public class site { public string name { get; set; } public string uri { get; set; } //switch real uri class if find useful } public class siteservice : service //: restservicebase<site> { public siterepository repository { get; set; } //injected ioc public object get(site request) { //return new site { name = "google", uri = "http://www.google.com" }; return new siteresponse {result = new site {name = "google", uri = "http://www.google.c...

Unique array of random numbers using functional programming -

i'm trying write code in functional paradigm practice. there 1 case i'm having problems wrapping head around. trying create array of 5 unique integers 1, 100. have been able solve without using functional programming: let uniquearray = []; while (uniquearray.length< 5) { const newnumber = getrandom1to100(); if (uniquearray.indexof(newnumber) < 0) { uniquearray.push(newnumber) } } i have access lodash can use that. thinking along lines of: const uniquearray = [ getrandom1to100(), getrandom1to100(), getrandom1to100(), getrandom1to100(), getrandom1to100() ].map((currentval, index, array) => { return array.indexof(currentval) > -1 ? getrandom1to100 : currentval; }); but wouldn't work because return true because index going in array (with more work remove defect) more importantly doesn't check second time values unique. however, i'm not quite sure how functionaly mimic while loop. how's this: cons...

How to merge two arrays of objects, and sum the values of duplicate object keys in JavaScript? -

so, have indeterminate amount of arrays in object, , need merge objects in them. arrays guaranteed same length, , objects guaranteed have same keys. i've tried iterating through it, though reason, sums objects in every key in array. example: var demo = { "key1": [{"a": 4, "b": 3, "c": 2, "d": 1}, {"a": 2, "b": 3, "c": 4, "d": 5}, {"a": 1, "b": 4, "c": 2, "d": 9}] "key2": [{"a": 3, "b": 5, "c": 3, "d": 4}, {"a": 2, "b": 9, "c": 1, "d": 3}, {"a": 2, "b": 2, "c": 2, "d": 3}] }; mergearrays(demo); /* returns: { "arbitraryname": [{"a": 7, "b": 8, "c": 5, "d": 5}, {"a": 4, "b": 12, "c": 5, "d": 8}, {"a": 3, ...

javascript - Implementing brush thickness variation in HTML5 canvas (example want to emulate inside) -

Image
i pointed in right direction in terms of algorithm in demo below here http://sta.sh/muro /. canvas tools using - i.e. drawing lines or drawing many arcs, etc specifically want emulate brush turning cause entire "brush stroke" thicker. see image brush settings want emulate. ultimately, create paint brush vary in thickness when turned, behaviour below. to need record mouse points when button down. need check each line segment find direction, length of line , normalised vector of line segment can on sample mouse samples. so if have set of points taken mouse following required details. for(var = 0; < len-1; i++){ var p1 = line[i]; var p2 = line[i+1]; var nx = p2.x - p1.x; var ny = p2.y - p1.y; p1.dir = ((math.atan2(ny,nx)%pi2)+pi2)%pi2; // direction p1.len = math.hypot(nx,ny); // length p1.nx = nx/p1.len; // normalised vector p1.ny = ny/p1.len; } once have details of each line ...

How to fetch last entered entry for a id from table MYSQL -

i have 3 tables: a order goes through multiple states. each state have entry in table_orderstatus. statusdate there, not shown in example. example table_orders - orderid, ordervalue; 1- 500 2- 1000 3- 8000 4- 10000 table_orderstatus - orderid, statusid, statusdate; (orderid, statusid) 1- 1 1- 2 2- 1 2- 3 3- 1 3- 3 3- 4 4- 1 4- 3 4- 4 4- 5 5- 1 table_statusvalues - statusid, statusvalue; 1- new 2- cancel 3- confirm 4- dispatched 5- delivered i want fetch order_id, , last status value (not id) orders. 1- cancel 2- confirm 3- dispatched 4- delivered 5- new i tried multiple ways achieve same. coudn't got expected result. can me on this? last according value: select orderid, statusvalue ( select orderid, max(statusid) laststatus table_orders o inner join table_orderstatus s on s.orderid = o.orderid group o.orderid ) l inner join table_statusvalues on statusid = laststatus

javascript - Show loading image when video buffer next frames -

i' using html5 video . need show loading image when video buffering next frame youtube when video stop , downloading next frames youtube show loading image circle gif image , when video download enough frame start loading image disappear. i'm not asking first time video start. know can use poster while video not starting or can use event loadstart , canplay . these things work fine when video starting first time. problem want loading image when video stop while playing due buffering next frame. so, event use or how can this. thanks. to achieve this, may want listen corresponding events video element. list of available events can found @ w3schools.com . the 2 events of interest goal stalled , waiting , once fired can display loading animation.

android - send and fetch data from server not working -

my android project want send json data (as arraylist),with header.. and read server response string.. defaulthttpclient deprecated..so,i using httpurlconnection .. here code:- @override public string signup(string name, string phno) throws exception { string url="http://address/androidproject/usersignup"; // instantiate , initialise signupform form suf = new form(name, phno); // store suf in list list<namevaluepair> pairs = new arraylist<namevaluepair>(1); // create k,v sent pairs.add(new basicnamevaluepair("suf", new gson().tojson(suf))); try { url url1 = new url(url); httpurlconnection connection = (httpurlconnection) url1.openconnection(); //encoded pairs httpentity requestentity = new urlencodedformentity(pairs); connection.setrequestmethod("post"); //add header connection.setrequestproperty("id", myid); connection.setdooutput(true); //send data outputstreamwriter writer = new outpu...

javascript - Color doesn't change at active dot in vertical dot navigation -

Image
i implemented vertical dot navigation. (1)the problem active dot's color not changed white. first 1 kept white color though not active shown in figure . (2)how can bring down dot positions? tried @ position, right , top properties, not changed. .vnav { position:absolute; right:7px; top:200px; width: 50px; z-index: 9999; list-style-type: none; } my html is <form class="summarybackground" name="summary" id="summary" style="height:500px;width:920px;overflow-y:hidden;" method="post"> <div class="mybox" id="section"> <div class="vnav"> <ul class="vnav"> <li> <a href="#section1"><div class="label">landed</div></a> </li> <li> <a href="#section2"><div class="label">apartment</div></a> ...

Compare a bidimensional array to 0 (c++) -

i made loop do.while, trying make change turns of game. now, want stop when of both array comes 0, , show winner. battleship game. do{ for(int k;toc=1;k++){ objec1(); if(toc!=1) break; } for(int k;toc2=1;k++){ objec2(); if(toc2!=1){ break; } } if(jug1[i][j]==0){ //here loop must stop correct1=true; cout<<"\n\tel player 2 winner\n"; } if(jug2[i][j]==0){ correct1=true; cout<<"\n\tplayer 1 winner \n"; } } while(!correct1); in way have code, not stop loop when must. now, want check if when array full of 0, stop loop, change flag , show winner. original code more extense. consider correctly initialized. firstly, think you'll have easier time problem if fix formatting, break things functions, , use better variable names. pretty hard read , understand. secondly, operation talking pretty expensive. if can avoid doing check way, that...

php - Handling two different pages with the same URL -

i'm working on program automatically logs site using selenium. in situations, if site doesn't remember browser, ask answer secret question before takes password page. thought handle if statement checks current url against specific url knew produced when directed secret question page. issue i'm running into, url secret question page, , url password page same. there way differentiate these 2 pages url in situation, or need find alternative method? if urls same, won't have differences compare, won't able tell page content based on url. it's common have 1 page, 1 url, shows different content, determined backend code selenium can't see. need compare different between 2 pages, such element appears on 1 page. presuming don't care whether password or secret question shown, want selenium through login process, easy solution use if / else statement check form appears , attempt fill out form present. if ($this->iselementpresent($password_form...

node.js - JavaScript/Node match returns null -

i want out of string containing html code, 1 value. therefore trying following: var test = '<div class="market_listing_largeimage"><img src="someurlhere" alt="" /></div>'; var test2 = test.match('<div class="market_listing_largeimage"><img src="' + '(.*)' + '" alt="" /><</div>'); my problem returns null. googling last hour, trying different examples, worked string provided in example, somehow, doesn't work me. doing wrong? you have additional < in code. this should work: var test = '<div class="market_listing_largeimage"><img src="someurlhere" alt="" /></div>'; var test2 = test.match('<div class="market_listing_largeimage"><img src="' + '(.*)' + '" alt="" /></div>');

shell - how to find the last modified file and then extract it -

say have 3 archrive file: a.7z b.7z c.7z what want find last modified archrive file , extract it 1st: find last modified 2nd: extract it 1st: ls -t | head -1 my question how approach 2nd using "|" @ end of 1st command you can that: 7z e `ls -t | head -1` use `` embed first command.

android - setOnCheckedChangeListener(this) error -

i'm beginner in android. read books. create checkbox import android.os.bundle; import android.support.design.widget.floatingactionbutton; import android.support.design.widget.snackbar; import android.support.v7.app.appcompatactivity; import android.support.v7.widget.toolbar; import android.view.view; import android.view.menu; import android.view.menuitem; import android.widget.checkbox; import android.widget.compoundbutton; import android.widget.compoundbutton.oncheckedchangelistener; public class mainactivity extends appcompatactivity implements oncheckedchangelistener { checkbox cb; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); toolbar toolbar = (toolbar) findviewbyid(r.id.toolbar); setsupportactionbar(toolbar); floatingactionbutton fab = (floatingactionbutton) findviewbyid(r.id.fab); fab.setonclicklistener(new view.onclicklistener() { @override ...

ios - UIPageControl customization -

i'm trying make uipageviewcontroller can swipe between different vc's. instead of custom dot control need have custom buttons. either user can select different vc button click or can swipe. right i'm using uiscrollview make this. don't know how proceed buttons need that. is there custom control that'll useful this? you can in different ways. if have 3 pages, can create ui 3 buttons(or tab bar) , in action can call: [self.pageviewcontroller setviewcontrollers:@[[self viewcontrolleratindex:yourpageindex] direction:uipageviewcontrollernavigationdirectionreverse animated:yes completion:nil]; uipageviewcontrollernavigationdirectionreverse or uipageviewcontrollernavigationdirectionforward can used required. this how it. or can use custom libraries: carbon kit working library. here can find many of them. or try this( a simpler example on ca...

c++ - Delete a random value from repeated string ( list ) in Google Protocol buffer -

i want delete item repeated field for have message defination: message foo { repeated string temp1 ; repeated string temp2 ; } i want remove item temp1 @ random index; as per knowledge can delete swapping last element , using removelast; dont know how use that. code snapshot in c++ ? here 1 reason why there no remove() in protocol buffer . i didn't want provide remove(int) because o(n) . version 1 of protocol buffers had such function, , saw people writing loops like: (int = 0; < field.size(); i++) { if (shouldfilter(field[i])) { field.remove(i); --i; } } this loop o(n^2) , bad, it's hard tell o(n^2) . idea behind providing removelast() force either clever (like swapping element last element first, documentation suggests) or write own loop makes time complexity of code obvious. two options here: copy item end of list space formerly occupied item want delete, call removelast() . by using iterator erase(const_iter...

java - How to filter data on DATE field in google sheet using ListQuery -

i have google sheet, there column date stores date in dd-mm-yyyy format. using java trying fetch records specific date example want records of 14/01/2016 . have tried below code. url listfeedurl = new url(worksheet.getlistfeedurl().tostring()); listquery listquery = new listquery(listfeedurl); listquery.setspreadsheetquery("date==\"14/01/2016\""); // not working. //listquery.setspreadsheetquery("broadcastsubject==\"3-minute belly tightening trick\""); //working fine. system.out.println(listquery.getspreadsheetquery()); listfeed listfeed = googleservice.getfeed(listquery, listfeed.class); system.out.println(listfeed.getstartindex()); system.out.println(listfeed.gettotalresults()); (listentry row : listfeed.getentries()) { system.out.println(row.getcustomelements().getvalue("date")+"=================="+report.getdate()); system.out.println(row.getcustomelements().getvalue("broadcastsubject"))...

jquery - AJAX: PHP query doesn't refresh when called -

i got page table supposed reload when click link. script works, , variable updated (i've tested that, see code), table doesn't reload new data sql query. page <!-- script start --> <script type='text/javascript'> function getresultat(str) { if (str == "") { document.getelementbyid("txthint").innerhtml = ""; return; } else { if (window.xmlhttprequest) { // code ie7+, firefox, chrome, opera, safari xmlhttp = new xmlhttprequest(); } else { // code ie6, ie5 xmlhttp = new activexobject("microsoft.xmlhttp"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readystate == 4 && xmlhttp.status == 200) { document.getelementbyid("txthint").innerhtml = xmlhttp.responsetext; } } xmlhttp.open("get","getresultat.php?klasse2="+str,true); xmlhttp.send(); } } </script> <!-- script end --> <!-- link --> <a style="cursor:point...

countdown timer from current date to specific date in javascript -

// thought of .. guess current date format , specified date format different. please. `<script> var oneday = 24*60*60*1000; // hours*minutes*seconds*milliseconds var firstdate = new date(); var seconddate = new date(2016,02,20); var diffdays = math.round(math.abs((firstdate.gettime() - seconddate.gettime())/(oneday))); document.getelementbyid("demo").innerhtml =diffdays; </script>` you can - <script> var oneday = 24*60*60*1000; // hours*minutes*seconds*milliseconds var firstdate = new date(); var seconddate = new date(2016,02,20); var diffdays = 'expired'; if(seconddate>=firstdate){ diffdays = parseint((seconddate - firstdate)/oneday) + ' days left'; } document.getelementbyid("demo").innerhtml =diffdays; </script> here fiddle fiddle

python removing ' ' in string? -

this question has answer here: remove specific characters string in python 18 answers i trying longtitude, latitude , altitude gps module on raspberry pi b+. currently running code here: ## prints latitude , longitude every second. import time import microstacknode.hardware.gps.l80gps if __name__ == '__main__': gps = microstacknode.hardware.gps.l80gps.l80gps() while true: try: data = gps.get_gpgga() except microstacknode.hardware.gps.l80gps.nmeapacketnotfounderror: continue list = [list(data.values())[x] x in [7, 9, 12]] string=str(list) string = string[1:-1] text_file = open("/home/pi/fyp/gps.txt","a") text_file.write(string + "\n") time.sleep(1) this output of said code: 0.0, 0.0, '10.2' 0.0, 0.0, '3.2' 0.0, ...

c# - Where to keep an object instance that I want to share across multiple ViewModels -

i'm architecturing game in c# & xaml using mvvm. game consists of main menu new game option. new game button takes player select page can type names of 2 players , select if it's player vs player game or player vs computer game. arrive @ game screen , play game. my question is, keeping persistent info in game object contains properties such player player1 , player player 2 , reactivecollection<tile> tiles , etc. should make game instance static , done or there better way this? i use game service. public interface igameservice { player playerone { get; set; } player playertwo { get; set; } tiles reactivecollection { get; set; } } then service can resolved class using ioc / dependency injection when viewmodels/app created. way can create singleton of service class can used viewmodel, sitll decoupled , testable. class implements igameservice can information/data game wants makes flexible. can change way information delivered without ...

php - Logging out facebook user without access token -

i have created application users authenticate facebook post photos on timelines. application run on single system user come authenticate , post photos. my problem logout each user when done. logging out using $loginurl = $helper->getloginurl(callback_uri, $permissions); logout use when new user go authentication. why not logging out user done? because using share dialog popup closes automatically user done sharing. i looking way logout user without use of access token. because if user uninstall or change password access_token becomes invalid , when logging them out redirects facebook.com/home.php i looking way logout user without use of access token. that not possible. if was, include call logout url website (for example src of image), , thereby log out person visiting site facebook, without agreement or knowing. having application on single system multitude of users login facebook not idea – trigger facebook’s security systems thinking shady g...

java - Create a List with next and previous in Android Sutdio -

i have class person 2 attributes : string firstname string lastname i have arraylist of person , want display in list custom adapter. but don't want use listview, want display 5 item in each page possibility of link button previous , next. when click on next 5 person of arraylist appear. etc... tried make fragments didn't go well. how can it? thanks help here solution listview activity_navigation_list.xml <?xml version="1.0" encoding="utf-8"?> <framelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <linearlayout android:id="@+id/data_list" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginbottom="48dp" android:orientation="vertical"/> <button ...

redirect - How to set a default page for wrong action requests in struts2? -

i have followed apache tutorial following code runs error. error>>>> caused by: org.xml.sax.saxparseexception; systemid: file:/c:/users/target/project-1.0/web- inf/classes/struts.xml; linenumber: 53; columnnumber: 15; content of element type "package" must match "(result-types?,interceptors?,default-interceptor-ref?,default-action-ref?,default- class-ref?,global-results?,global-exception-mappings?,action*)". please note actions , packages correctly defined once copy redirect code runs error. code <package name="default" namespace="/" extends="struts-default"> <default-action-ref name="underconstruction"></default-action-ref> <action name="underconstruction"> <result>notfound.jsp</result> </action> <result-types> <result-type name="tiles" cla...

How can I create a new table in SQL Server CE for Windows phone 8 c# -

i want create new table @ runtime don't know how this. when want insert database when haven't example person table i've got error the specified table not exist it's logical table doesn't exist, have create table @ runtime , don't know how? you must use databaseschemaupdater class, described here: https://msdn.microsoft.com/en-us/library/windows/apps/hh394018(v=vs.105).aspx

python - Compare protocol type -

def main(): pkt = sniff(filter = server_ip_filter, lfilter= check_protocol, count = 1) print pkt[0].summary() black_list = open ("black_list" ,"r") list_lines = black_list.readlines() black_list.close() black_list_lines = [(i.split(',')) in list_lines] layer = pkt[0].getlayer(2).name line in black_list_lines: if line[0] == pkt[0][ip].src: if str(line[2]) == str(layer[0]): print "block ! " i trying create simple firewall, have file called black_list has ip, port, protocol. when try compare protocol type in order know if packet should block, says line[2] , protocol doesn't match. i check type , both of them <str> .

Chrominance similarity inof images in matlab -

i doing project on image quality assessment , implementing following paper a new method color image quality assessment - niveditta thakur , swapna devi, international journal of computer applications, february 2011 i have implemented of code struggling understand how calculate color similarity. converted rgb image hsi , , want extract chrominance information in single plane , similarity measure. here did: hsi=rgb2hsi(i); h = hsi(:,:,1); % seperate saturation & intensity give hue of image s = hsi(:,:,2); % seperate hue & intensity give saturation of image = hsi(:,:,3); % seperate hue & saturation give intensity/grayscale image h_n=cat(3,h,s,x_z); g_n=rgb2gray(h_n); k=1; x=1:factor:s1-2 y=1:factor:s2-2 i=0:factor-1 j=0:factor-1 n1((i+1),(j+1),k)=g_n((x+i),(y+j),1); end end k=k+1; end end p=1:3072 mh1(p)=mean2(n1(:,:,p)); end i ran on both distorted , test image. similarity measure comp...

java - JFrame setsize with x by x input is not square -

i playing around jframe , when this: public class ui extends jframe { public ui() { pack(); setsize(50, 50); setlocationrelativeto(null); setvisible(true); } public static void main(string[] args) { ui test =new ui(); } } the frame not square, when change (50,50) larger (500,500) square. can tell why is? setsize(50,50) small size jframe, jframe root component @ least use proper size it. contains title control box , because of it, square small size difficult. alternative can use jwindow small square size.

Get sum of some arrays' elements C++ -

how possibly sum of elements between 2 given points in array if given: n - array length m - number of questions array a[n] - array numbers m questions in format x y example input 3 3 -1 2 0 3 3 1 3 1 2 output 0 1 1 here code #include <iostream> #include <numeric> using namespace std; int main() { int n,m,x,y; cin>>n>>m; int [n]; int s [m]; (int = 0; < n; i++){ cin>>a[i]; } (int = 0; < m ; i++){ cin>>x>>y; if(x == y){ s[i] = a[x-1]; continue; } s[i] = accumulate(a + x - 1, + y,0); } (int = 0; < m; i++){ cout<<s[i]<<endl; } return 0; } this not school homework, task internet - run on test server using standard streams input , result check. i need program run in less 0.2 seconds with: 0 < n,m <= 50000 -1000 <= a[i...

ios - Swift: Factory Pattern, Subclass methods are not visible -

i new programming in swift , have reached blocker in constructing factory design pattern. below code: protocol iinterface { func interfacemethod() -> void } public class subclass: iinterface { init() {} func interfacemethod() { } public func subclassmethod() { } } public class factory() { class func createfactory() -> iinterface { return subclass() } } finally, trying access below let mgr = factory.createfactory() //calling interface method mgr.interfacemethod() -- works, when keep dot (mgr.) shows method name //calling subclass method mgr.subclassmethod() -- doesn't work, when keep dot (mgr.) doesnt show subclass method name even if use mgr.subclassmethod , throws error saying value of type iinterface has no member subclassmethod i believe getting exposed protocol methods though subclass object returned via factory all examples browsed , have seen shows how consume methods specified protocol, haven't seen example sh...

java - SolrJ version mismatch while merging 2 projects -

i have 2 java projects developed using solrj. project 1 -> using solrj 4.10.1 project 2 -> using solrj 5.2.1 now, trying merge both projects single project. i tried including both version of jars in maven, still same issue. if try including major version, i'm getting of classes(4.10.1) deprecated , interfaces unavailable in it. <dependency> <groupid>org.apache.solr</groupid> <artifactid>solr-solrj</artifactid> <version>4.10.1</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupid>org.apache.solr</groupid> <artifactid>solr-solrj</artifactid> <version>5.2.1</version> </dependency> in simple:few packages of same project uses different jars. example: package1/module1 uses : solrj jar version 4.10.1 package2 uses : solrj jar version 5.2.1...

javascript - Property touch-action doesn't exist : none -

using css code: .ui-resizable{position:relative}.ui-resizable-handle{position:absolute;font-size:.1px;display:block;-ms-touch-action:none;touch-action:none}.ui-resizable-autohide getting error in wc3 validation: property touch-action doesn't exist : none

javascript - Allow float element to overflow horizontally -

i have following structure: <div id="hold"> <div id="hold-left">content</div> <div id="hold-right">content</div> </div> hold-left floats left , hold-right floats right. widths 40% , 55% when page loaded. thing is, hold-right sort of preview of , user needs able resize it. this done using javascript (the user selects zoom level radio button), issue facing that, if enlarged, drops down beneath hold-left . i'd float on freely outside of parent div. how go this? can done through css @ all, or need dynamically resize parent every time resize hold-right ? have considered using left margin on .hold-right ? .hold-left{ float:left; width:40%; } .hold-right{ margin-left:45%; } also, should use classes, not ids.

SQL Server 2008 pagination with total rows -

i see there similar questions, unable find answer understood not sql query expert. this works page of records: with page ( select row_number() on (order sequence_no asc) _row_, * mytable ) select * page _row_ between 0 , 25 but how can modify returns total number of records matched first query ? with page ( select row_number(), count(*) on (order sequence_no asc) _row_, _total_, * mytable ) select * page _row_ between 0 , 25 i following error: incorrect syntax near 'row_number', expected 'over' that not right syntax, need use over clause count try this ;with page ( select row_number() over(order sequence_no asc) _row_, count(*) over() _total_, * mytable ) select * page _row_ between 0 , 25

php - How to create sqlite file in Laravel 5.2 framework? -

i want create sqlite file manually whenever user registered. use new sqlite3($file_path) but laravel keep tell me class 'app\http\controllers\sqlite3' not found please me this. thank very help. you should use: new \sqlite3($file_path) or put use sqllite3; below namespace app\http\controllers; now trying use sqlite3 current namespace. you might interested in looking @ how use objects other namespaces , how import namespaces in php

How to get array from serialized string in php? -

as result wordpress option got following details results. don't know how meaningful result following. can possible string parsing? a:6:{s:14:"street_address";s:9:"add_line1";s:15:"street_address2";s:10:"add_line_2";s:9:"city_name";s:5:"cityname";s:5:"state";s:7:"statename";s:3:"zip";s:6:"999999";s:14:"country_select";s:2:"in";} usually can use unserialize() function. $result = unserialize($your_serialized_string); however there error in seralized string function return false error on log. php notice: unserialize(): error @ offset 110 of 198 bytes in [...] i've faced issue when string stored in database directly modified without using functions unserialize() , serialize() , because serialize function prepend length of value in array 's:14:"street_address"', 14 length of 'street_address', editing directly m...

python - Changing the order of operation for __add__, __mul__, etc. methods in a custom class -

i have vector class: class vector: def __init__(self, x, y): self.x, self.y = x, y def __str__(self): return '(%s,%s)' % (self.x, self.y) def __add__(self, n): if isinstance(n, (int, long, float)): return vector(self.x+n, self.y+n) elif isinstance(n, vector): return vector(self.x+n.x, self.y+n.y) which works fine, i.e. can write: a = vector(1,2) print(a + 1) # prints (2,3) however if order of operation reversed, fails: a = vector(1,2) print(1 + a) # raises typeerror: unsupported operand type(s) # +: 'int' , 'instance' i understand error: addition of int object vector object undefined because haven't defined in int class. there way work around without defining in int (or parent of int ) class? you need define __radd__ some operations not evaluate + b == b + , that's why python defines add , radd methods. explaining myself b...

javascript - THREE.js object removing -

i have trouble dealing three.js . the task is, make car stops @ red light. have scene, , car moving, cant change light, no matter try. created sphere represents light, , button should change color. want call function, hides red light , shows green one. however, when call function: function removesphere() { scene.remove(sphere2); render();} nothing happens. tried different variants, cant edit sphere in way. could me this? full code below: <head> <title>#16 three.js - colladaloader</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <script type="text/javascript"> var kamera ="a"; var delta = 0.01; var deltatmp = 0.01; function kameraa() { kamera ="a";} function kamerab() { kamera ="b";} function kamerastartstop() { if(delta == 0.0) {delta = deltatmp;} else {delta = 0.0;}} ...