Posts

Showing posts from July, 2011

Get the last data filled excel row number in C# -

i have been trying row number effectively. fails data cleared , cells not explicitly deleted. i guess because of "used range". what did using epplus using (var excel = new excelpackage(hpf.inputstream)) { var ws = excel.workbook.worksheets["sheet1"]; if(ws.dimension.end.row > 2003) { var result = new jsonresult(); result.data = "filelimitexceeded" ; but gives me incorrect data. how last count effectively. i found var lastrow = cells.find("*", [a1], , , xlbyrows, xlprevious).row; but namespaces not comprehend. me complete , correct answer ? i have come senario few days before, did read data , put in data table, , filter data show records when data not null. can go same approach.

excel - Display data from certain date, from large data set -

i've got set of data @ work, need analyze , summarize based on daily values. have 48 values each date; 1 each half hour. i've set sumif , countif-system calcuate average values, need solution display data 1 date, can assess whether data complete (the supplier known have missing data in sensors) as example, data looks like. have 6000 lines of time. come in chunks time time, never know how big data set get. last 1 2200 lines 11-03-2016 11:30:00:000 13,3 51,6 7,85 11-03-2016 12:00:00:000 14,9 51,6 7,85 11-03-2016 12:30:00:000 13,9 51,6 7,86 11-03-2016 13:00:00:000 14,9 51,7 7,87 11-03-2016 13:30:00:000 14,7 52 7,87 11-03-2016 14:00:00:000 14,7 52 7,88 11-03-2016 14:30:00:000 0,1 52,1 7,89 11-03-2016 15:00:00:000 0,1 52,2 7,89 11-03-2016 15:30:00:000 14,8 52,1 7,9 11-03-2016 16:00:00:000 14,8 52 7,9 11-03-2016 16:30:00:000 13,3 52 7,91 11-03-2016 17:00:0

How to merge audio files in one on top of each other android -

sup! trying merge list of audio files on top of each other 1 audio file. followed answer on this question, doesn't work. tried this(the code below) doesn't work either(probably because javax not compatible android) even if know how usage of other libraries android, please, show it. thing ask should done locally, without using servers. thank you! public class joinwavs{ public static void main(string[] args) { string wavfile1 = "d:\\wav1.wav"; string wavfile2 = "d:\\wav2.wav"; try { audioinputstream clip1 = audiosystem.getaudioinputstream(new file(wavfile1)); audioinputstream clip2 = audiosystem.getaudioinputstream(new file(wavfile2)); audioinputstream appendedfiles = new audioinputstream( new sequenceinputstream(clip1, clip2), clip1.getformat(), clip

jquery - Javascript select element that has class with max value -

i know there many topics jquery selector regex, need this i have div : <div class="some random things rank0">hello</div> <div class="some things rank1">hello</div> <div class="things rank1">hello</div> <div class="some random rank2 things">hello</div> <div class="random rank2 some">hello</div> <div class="some things rank3">hello</div> <div class="some random rank4">hello</div> i selector select every div rank > specific_value can't modify html. know should use filter function, i'm not in jquery/regex. there start : var specific_value = 2; $.each($("div").filter(function() { // need // return rank > specific_value }), function() { $(this).html("test"); }) expected result : <div class="some random things rank0">hello</div> <div class="some th

jquery - Autocomplete show entire list on down arrow key -

i have applied autocomplete plugin on textbox this. var model = []; (var = 0; < data.length; ++i) { model.push({ label: data[i].modelname, value: data[i].codemodel }); } var modeldata = model; $('#tbmodele').autocomplete({ source: function (request, response) { response($.map(modeldata, function (value) { if (value.label.tolowercase().startswith(request.term.tolowercase())) { return { label: value.label, vvalue: value.value }; } })); }, select: function (e, i) { populateotherfields(i.item.label); return false; }, open: function () { $scope.ismodeldropdownopen = true; },

bash - What does -1 in "ls -1 path" mean? -

i looking @ shell code meant count of number of files in directory. reads: count=$(ls -1 ${dirname} | wc -l) what -1 part mean? can't find in other questions, passing references iterating on files in directory isn't looking at. also, removing command seems have no effect. count=$(ls -1 ${dirname} | wc -l) ...is buggy way count files in directory: ls -1 tells ls not put multiple files on single line; making sure wc -l then, counting lines, count files. now, let's speak "buggy": filenames can contain literal newlines. how version of ls handles implementation-defined; versions double-count such files (gnu systems won't, wouldn't want place bets about, say, random releases of busybox floating around on embedded routers). unquoted expansion of ${dirname} allows directory name string-split , glob-expanded before being passed ls , if name contains whitespace, can become multiple arguments. should "$dirname" or "${di

android - App Crashes when clicking in different TextViews very fast -

i new android , have fragment container view (a framelayout). there 2 textviews on top of it, tabs. each textview ie txt1,txt2 adds 2 fragments ie frgmnt1,frgmnt2 respectively. when textview clicked, corresponding fragment added. if clicked again, fragment removed. that part working fine. however, when click in textview rapidly, app crashes , shows "no host" exception. can me understand why happens? (side note, tab layout implementation not required here). here stack trace: 07-04 18:22:25.600 10971-10971/integral.com.sellfie e/androidruntime: fatal exception: main process: integral.com.sellfie, pid: 10971 java.lang.illegalstateexception: no host @ android.support.v4.app.fragmentmanagerimpl.movetostate(fragmentmanager.java:1239) @ android.support.v4.app.fragmentmanagerimpl.movetostate(fragmentmanager.java:1234) @ android.support.v4.app.fragmentmanagerimpl.dispatchactivitycreated(fragmentmanager.java:2046) @ android.support.v4.app.fragment.perform

c# - 3D rotation, given two specified directions -

i have 2 perpendicular unit vectors, p , q; think of being embedded in rigid object in 3d space. wish rotate object p points along positive x-axis , q points along positive y-axis. i programming in c# , using quaternions compute rotations. how create quaternion perform desired rotation? if imagine inverse operation of quaternion, know point (1,0,0) goes p, , (0,1,0) goes q. similarly, point (0,0,1) go point z equal cross product of p , q. therefore have matrix representation of inverse rotation. first column p, second q, third p cross q. so matrix rotation want given transpose of matrix, i.e. first row p, second row q, third row p cross q. so recommend call library routine convert matrix quaternion form. you may interested in document doom3 explaining algorithm id software used converting matrix quaternion - including optimised x86 assembler code. orthogonal matrices if have matrix m columns (a,b,c) forming orthonormal set, know a'a = b'b = c'c

SSL error: invalid or self signed certificate in Magento 1.9 while uploading a particular file -

i've had look, can't find answer problem already. i trying upload downloadable product in magento 1.9. getting: ssl error: invalid or self signed certificate this problem happening 1 file. no problem images , other files. the size of file 2mb, can upload different file 3mb, same format in same place , works fine. think problem not size or format of file. i have uploaded around 45 images , 45 pdf files without error, particular file i've had error 50 times. i have cleared magento's cached , tried logging out , in again - no positive result. i've tried renaming file - no joy.

sql server - MS SQL - JOIN only if parameter exists in stored proc -

i have stored proc has following (simplified example): declare @id int = null select * table1 t1 inner join table2 t2 on ((@id not null) , (t2.id = @id)) the purpose of return rows if @id not provided, else return rows matching @id. works expected long @id provided. returns no rows @id null. i thought, maybe inner join table t2 on (@id null or ((@id not null) , (t2.id = @id))) might work, if @id null, seems return unending rows (i waited 30 seconds, , past 1m rows. (there 150 rows in table1) i've read around, , other examples accomplish seem use dynamic sql (which i'd rather not do), or possibility of creating temp table, seems little extreme kind of thing. what options? thank you. i doubtful on table joining, tried simplified sql query declare @id int = null select * table1 t1 inner join table2 t2 on t1.id=t2.id @id null or t2.id = @id

java - Multiselect Recyclerview List -

good day all, i have list of items want user able select 5 out of 10 items , 5 able send data off webservice. i found this , this but neither of them worked or github repo non existent (the second one). does have other tuts on how this? thank you what going on proplem? video ( https://www.youtube.com/watch?v=7du30yal6ri ) expectation? in example, create empty class , simple recyclerview. the view item handle user click behaviour. if user selected item click again item not select , otherwise. when action happening, have listener send mainactivity (implemented onitemchangelistener method of interface defined in adapter ) in mainactivity, create layout recyclerview, delete button, , no items labels. delete button process delete , update list data. the source code at: https://github.com/liemvo/example_recyclemultiselected

javascript - JVectorMap Drill-Down doesn't color regions when scale or values change after clicking on a country -

i using jvectormap display visits data on map. code. var euromap = new jvm.multimap({ container: $('#map'), regionsselectable: true, regionsselectableone: true, maxlevel: 1, main: { map: 'europe_mill', backgroundcolor: 'transparent', regionstyle: { initial: { fill: 'white', "fill-opacity": 1, stroke: '#000', "stroke-width": 0.3, "stroke-opacity": 1 }, }, series: { regions: [{ scale: ['#ffffff', '#db715c'], values: gon.map_data['ptps'], normalizefunction: 'polynomial' }] }, onregiontipshow: function(event, label, index){ label.html( '<b>'+label.html()+'</b></br>'+ &

JAVA: What's the difference between byte code and binary? -

what's difference between java byte code ( compiled language , otherwise known object code ) , machine code ( code native current computer ). have read in books refer byte code binary instructions , don't know why. bytecode platform-independent, bytecodes compiled compiler running in windows still run in linux/unix/mac. machine code platform-specific, if compiled in windows x86, run in windows x86. continue reading books =)

unix - Possible to return number of matches per line of a regex file using `grep -f regexfile queryfile`? -

i'm wondering if there simple way transform grep command such as grep -c -f regex.txt file.txt to return total number of matched lines in file.txt each line of regex.txt , instead of sum of matched lines found patterns in regex.txt above command does. my current method of handling use xargs (or gnu parallel interchangeably): cat regex.txt | xargs -i{} grep -c {} file.txt can grep in 1 fell swoop? grep -o -f regex.txt | sort | uniq -c

mainframe - Need to compare the same field in different records with JCL SORT -

i have input file, 3rd field in file number. number repeated in same field 30-40 records, when record read has different value in field need number '1' print in first position of following record. e.g. 7226184019519 317786762 0000000000001pop160 7226184019522 317786762 0000000000001pop160 1 7226139045234 326446460 0000000000001pop160 7226139045242 326446460 0000000000001pop160 7226139045274 326446460 0000000000001pop160 7226139045277 326446460 0000000000001pop160 7226139045280 326446460 0000000000001pop160 i've tried using 'sections' like: sort fields=copy outfil fnames=sortout, sections=(26,9,header3= (1:'1')) but print number '1' on separate line: 7226184019519 317786762 0000000000001pop160 7226184019522 317786762 0000000000001pop160 1 7226139045234

interop - Calling a dll created in VB6 from F# -

i trying call dll file created in vb6 f#. have written following dll. public function addtwonumbers(byval integer, byval b integer) addtwonumbers = + b end function now want call in f# program, wrote code open system.runtime.interopservices module interopwithnative = [<dllimport(@"c:\add", callingconvention = callingconvention.cdecl)>] void addtwonumbers(int, int) interopwithnative.addtwonumbers(3,4) let result = addtwonumbers_ 2.0 3.0 it gives me errors , doesn't recognize function. a working interop example entrypoint open system.runtime.interopservices // dllimport module kernelinterop = [<dllimport("kernel32.dll", entrypoint="beep")>] extern void beep( int frequency, int duration ) kernelinterop.beep // val beep : int * int -> unit kernelinterop.beep(440, 1000)

javascript - Allow web requests based on document URL -

within extension, i'm trying identify requests loaded part of specifc pages. examples, if page: https://www.arandomwebsite.com loads following resources: https://www.arandomwebsite.com/js/app.js https://www.arandomwebsite.com/css/style.css and makes few api requests to: https://www.arandomwebsite.com/api/users using chrome.webrequest.onbeforerequest, want know www.arandomwebsite.com/js/app.js loaded resource www.arandomwebsite.com . i've tried using chrome.tabs tab url. chrome.tabs asynchronous i've used onupdated , onremoved track tab changes. however, chrome.webrequest.onbeforerequest can fire before chrome.tabs.onupdated , doesn't work. var allowedurl = "https://www.arandomwebsite.com/" var tabs = {}; chrome.tabs.query({}, function(tabs) { tabs.foreach(function(tab) { tabs[tab.id] = tab; }); }); chrome.tabs.onupdated.addlistener(function(tabid, changeinfo, tab) { tabs[tab.id] = tab; }); chrome.tabs.onremoved

How do I get this text using PHP Simple HTML dom? -

assuming have html code in html source: <div class="info"> <p><span class="strong">score</span>4.32/5</p> <p><span class="strong">type</span>tv</p> <p><span class="strong">episodes</span>13</p> <p><span class="strong">status</span>ongoing</p> <p><span class="strong">aired</span>oct 3, 2015 - dec 26, 2015</p> <p><span class="strong">age</span>pg-13 - teens 13 or older</p> </div> how use php simple html dom text 4.32 above? tried foreach($info_html->find('.strong') $library) { $rating = $library->innertext; var_dump($rating); } but gives me text "score", want 4.32. maybe give result looking for: foreach($info_html->find('div.info p') $library) { $rating = $library->find(

c# - XsltCompiledTransform is slow on first Transform - Undocumented behaviour -

we have relatively complex xslt file. .net version 3.5 - mvc 2 app running in iis7.5 when xsltcompiledtransform.transform, first time takes 1 minute. subsequent times takes less second regardless of input xml looks like. the initial transform stackoverflowexception if don't put in new thread, in new thread. xsltcompiledtransform object static object, don't recreate every time transform. this behaviour not documented anywhere in msdn far know. documentation states compile xslt using xsltc.exe (we did this) doesn't spend lot of time compiling xslt when call load method it's compiled. unfortunately, didn't increase performance when called load, , regardless of if load xslt text or assembly, first transform takes 1 minute, , subsequent transforms lightning fast. unfortunately, requiring "dummy" transform on simple piece of xml text @ startup, first user not experience 1 minute delay transformation. the transformations large pieces of xml, d

The top bar color when app is inactive. (Cordova) -

Image
i developing mobile app hybrid based on cord, until i'm doing well, can not change color of top bar when application inactive! android 5.1 cordova 5.3.3 i'm using plugin (cordova_plugin-statusbar 1.0.1): https://www.npmjs.com/package/cordova-plugin-statusbar

php - Check if information from database is blank -

i need check if status , b blank or 0, blank doesnt work, suggestions? $sta = db2_result($queryexe, 'statusa'); $stb = db2_result($queryexe, 'statusb'); if ($sta=="0" or $sta=="" , $stb=="0" or $stb=="") you should use empty function consider 0, "0", null... empty values : if (empty($sta) && empty($stb)) { if want stick logic, consider separate if statements in 2 parts : if ( ($sta=="0" or $sta=="") , ($stb=="0" or $stb=="") ) {

math - Precision of reciprocal in floating point arithmetics -

for fun, i'm trying implement chudnovsky algorithm calculate pi in java using arbitrary precision floating point library. 1 thing strikes me need calculate reciprocal of number 1/n, since formula described 1/pi = sum(...) how many significant digits/digits of precision 1 need of floating point number n, in order 1/n have desired precision? there easy answer this? tried doing calculations 1/0.100009999999 = 9.99900010009 determine reciprocal of 0.1 5 correct digits after decimal point. see if take first 3 digits after decimal point, , round result correct value 10, there general rule how many digits correct after 1/n operation? interested in same result in binary , hexadecimal bases. tried googling , fast search on stackoverflow, didnt find previous answer this. apologies if duplicate exists. you want compute 1/x, computing 1/(x+d) d=delta x truncation error. binomial theorems, 1/(x+d) = (x-d)/(x²-d²) and since can assume d² far below floating point error, error

Python's super() , what exactly happens? -

this question has answer here: understanding python super() __init__() methods [duplicate] 7 answers i trying understand objects created when instantiate child class in python, example: class car(): def __init__(self, make, model, year): self.make = make self.model = model self.year = year class electriccar(car): def __init__(self, make, model, year): super().__init__(make, model, year) my_tesla = electriccar('tesla', 'model s', 2016) when create object my_tesla, instantiate class electriccar calling constructor of class, in turn calls constructor of parent. how happen? right have 2 guesses: 1) super() reference parent class, call constructor of parent "super(). init (make, model, year)" instantiating our child class. result have one object of our class electriccar(). 2) super(), calls c

regex - how modify my string for each ocurrence C#? -

i read replace not modify string, creates new 1 requested modifications. else implementation detail, should not care about. if don't trust regex library, don't use it. if behaves want to, might change in future without further notice. how use variable modification ? regex.replace , string immutability string immutable. means cannot modify existing string , can create new one. however, can modify reference string . for example: var = "hello"; var b = a; b = "world"; console.writeline(a); console.writeline(b); output: hello world this because when b = "world" called change reference b point "world" , a still points "hello" .

Java Eclipse Issue; having a subfolder in an existing java project -

so i'm learning java, i'm novice. book provide source code, play around with. i create java project , move source code according folder. programs under main folder work perfect! when have seperate folders(subfolders main), guess project technically, programs not compile or run. they work if move take them out subfolder, not want that. lot of subfolders similar each other, don't want overwrite,etc. how go fixing without having create individual projects each of these? example. create new project -> chp10 under chp10 store source code give me. some of source code contain own folders, such rectangle 1, rectangle 2. everything under chp10 runs/compiles fine. if try use under rectangle folders not work. i believe error file not being resolved because references different class files. i had same issue way when. use import statement @ top of page you're implementing subfolder. example - @ top of java class file: package rectangle1; package

python - Plotting a curve from numpy array with large values -

Image
i trying plot curve molecular dynamics potential energies data stored in numpy array. can see figure attached, on top left of figure, large number appears related label on y-axis. @ it. if rescale data, still number appears there. not want it. please can suggest me howto sort out issue? thank much.. this happening because data small value offset large one. that's - sign means @ front of number, "take plotted y-values , subtract number actual values". can remove plotting mean subtracted. here's example: import numpy np import matplotlib.pyplot plt y = -1.5*1e7 + np.random.random(100) plt.plot(y) plt.ylabel("units") gives form don't like: but subtracting mean (or other number close that, min or max , etc) remove large offset: plt.figure() plt.plot(y - np.mean(y)) plt.ylabel("offset units") plt.show()

order - Opengl front to back blending issue (black screen) -

i'm implementing renderer shading requires front-to-back rendering. i'm having issues figuring out how initialize blending function. here's tried. glenable(gl_depth_test); gldepthfunc(gl_less); glenable(gl_blend); glblendfunc(gl_one_minus_dst_alpha, gl_one); glclearcolor(0.0f, 0.0f, 0.0f, 0.0f); this results in black screen. the blog post says use gl_one_minus_dst_alpha, gl_one , initialize background black translucent, think i'm doing. post cites an nvidia whitepaper looked well. looked through code there , seem same me. wrong isn't working. if don't use blending or use other blending functions things seem work. edit: glutinit(&argc, argv); glutinitdisplaymode(glut_double | glut_rgba); glutcreatewindow("window"); you need request alpha planes during glut initialization if use blending involves destination alpha. change call to: glutinitdisplaymode(glut_double | glut_rgba | glut_alpha); you might think specifying gl_

python - discriminate basic and advanced slicing of numpy array -

i'm reading doc numpy array indexing , still unclear how discriminate basic , advanced slicing. thanks if explain bit. x[(1,2,3),] fundamentally different x[(1,2,3)] . latter equivalent x[1,2,3] trigger basic selection while former trigger advanced indexing. sure understand why occurs. also recognize x[[1,2,3]] trigger advanced indexing, whereas x[[1,2,slice(none)]]` trigger basic slicing. start simple 1d array: in [326]: x=np.arange(10) these 2 expressions same thing - select 3 elements array. verify return copy, x[1:4] returns view. in [327]: x[(1,2,3),] out[327]: array([1, 2, 3]) in [328]: x[[1,2,3]] out[328]: array([1, 2, 3]) but without command, tuple raises error: in [329]: x[(1,2,3)] ... indexerror: many indices array same as: in [330]: x[1,2,3] indexerror: many indices array x[1,2,3] converted python interpreter call x.__getitem__((1,2,3)) . is, input values passed tuple method. () in x[(1,2,3)] make no differen

javascript - Earliest preload for an image in an HTML page -

what earliest possible time in html page load sequence image request can issued? a site involved switching using sprite pages. sprite page potentially large, , overall page load time of first page benefits request being issued browser. pages include heavy css , js loads , terrible initiate sprite-page load after these complete. the quickest overall load time i've found create ultra-short css file, referred in html head section, references image in class. typically initiates image request before other css , js have finished loading (number of connections permitting) in modern browsers. other techniques seem delay @ least until css loaded before initiating image request. i dislike technique, however, introduces 1 more round-trip , 1 more file seems necessary, might add 50ms-100ms or load time compared technique initiates image request direct html. however, referring image in html body, etc, seem cause request wait until head css loaded. , more obvious solutions -- not sweat

- Binary Tree Puzzle - Draw tree from these traversals: -

Image
inorder: s e u y q r p d f k l m preorder: f s q y e u p r d k l m i'm pretty confused middle part. no combination seems work, help? have tricks? how approach this? i've been smacking head on 2 hours. i must restore tree. the correct result is i try provide general explanation instead of concrete 1 example. think more useful , after test algorithm concrete case, see algorithm works , understand better. you think problem in recursive way. in order facilitate problem, agree on variables preorder : array containing preorder traversal inorder : array containing inorder traversal l_p : left index in preorder array r_p : right index in preorder array l_i : left index in inorder array r_i : right index in inorder array in concrete example, first instance l_p = l_i = 0 , r_p = r_i = 12 . this facilitate explanation: index 0 1 2 3 4 5 6 7 8 9 10 11 12 preorder: f s q y e u p r d k l m inorder: s e u y q r p d f k l m

python - Syntax Error on line 36 -

i keep getting syntax error on line 36 of text based adventure. i've added #line 36 @ end of line tell is. have tried can think of fix this. missing? #adventure #setting print ("*you wake in dark room on mattress on floor*") #wait before running next command make seem more real , more real thought. import time time.sleep(1) #introduce map print ("*you left , there wall, right , find short table map on it*") import time time.sleep(1) print("*you pick map*") map = """ |---------------------| | | | start | | | | | |---------------------|""" print (map) def goto(linenum): global line line = linenum line = 1 while true: if line == 1: response = raw_input("would explore around room

javascript - Keeping a user-defined JScript variable after reload? -

in html document, button displayed, , it's onclick event alert variable countervar. button can used bring countervar using countervar++. countervar never defined in jscript document, because want countervar stay how last defined user. expected, countervar nil after each reload. saving browser cookies not work, because same variable has displayed each user views document. i'm looking "global variables" answer, no luck. help? as suggested in comments, can use localstorage achieve part of want: var counter; // save local storage window.localstorage.setitem("counter", counter); // can call whenever make changes counter variable // load local storage // call when page loads if( window.localstorage.getitem("counter") === null){ counter = 0; } else{ counter = parseint(localstorage.getitem("counter")); } this allow save variable 1 user. if want share between users, can't done using client side scripting. you'll

logging - Golang: How to capture panic and log this error to original log file? -

i tried capture panic , log error: func (s *server) sayhello(ctx context.context, in *pb.hellorequest) (*pb.helloreply, error) { defer func() { if err := recover(); err != nil { glog.errorf("recovered err: %v", err) } }() panic("tish panic") return &pb.helloreply{message: "hello " + in.name}, nil } but surprise, "recovered err: " never occurs in log file, instead, occurs in /var/log/messages . how can log error in original log file? [updated] if there no panic, glog.errorf log correctly log dir; when there panic, can't: // glog log correctly, unless uncomment panic below glog.errorf("this normal log: %v", err) // panic("tish panic") maybe impossible, since that's crash means? you need call glog.flush() in deferred function. documentation of glog: log output buffered , written periodically using flush. programs should call flush bef

excel - Using advanced filter with criteria -

i trying copy distinct values excel table vba, running in trouble when want assing criteria it. i trying filter values bigger 0 in column ci this code work dim keycells range set keycells = range("h1") if not application.intersect(keycells, range(target.address)) _ nothing dim lastrow long lastrow = activesheet.range("h1").value application.enableevents = false sheets("fond16").range("c4:c31").clear sheets("plnenioperatoru_2016").range("b" & lastrow - 1 & "11:b" & lastrow & "11").advancedfilter _ action:=xlfiltercopy, _ copytorange:=sheets("fond16").range("c4"), _ unique:=true but not work (will throw 1004: application-defined or object-defined error) sheets("plnenioperatoru_2016").range("b" & lastrow - 1 & "11:b" & lastrow & "11").advancedfilter _ act

python: using raw socket with OSX -

i found code online , found doesn't work on osx. know correct method without using third party library? import socket import struct import binascii rawsocket = socket.socket(socket.af_packet, socket.sock_raw, socket.htons(0x0003)) while true: packet = rawsocket.recvfrom(2048) ethernet_header = packet[0][0:14] ethernet_detailed = struct.unpack(“!6s6s2s”, ethernet_header) arp_header = packet[0][14:42] arp_detailed = struct.unpack(“2s2s1s1s2s6s4s6s4s”, arp_header) # skip non-arp packets ethertype = ethernet_detailed[2] if ethertype != ‘\x08\x06’: continue source_mac = binascii.hexlify(arp_detailed[5]) dest_ip = socket.inet_ntoa(arp_detailed[8]) if source_mac == ‘74c24671971c’: print “tide button pressed!, ip = “ + dest_ip apparantly osx not have af_packet or pf_packet , af_inet high level think, or @ least requires more recoding drop in replacement. thanks ok figured 1 out, on mac have use pcap library. her

web scraping - Django Beautiful Soup Changing User Agent - No Effect -

i trying run webscrapping application. however, code working sites though set user agent (have tried several different ones). code work on dev site (which hosted on subdomain of pythonanywhere), not on production site. seems if blocked sites (even though have not been accessing them @ if ever). ideas? email websites , see if can granted access not doing malicious. url = request.get['url'] import requests bs4 import beautifulsoup r = requests.get(url) soup = beautifulsoup(r.content) soup = beautifulsoup(r.content, "html.parser") if not soup.find('meta', property="og:title"): title = soup.title.string else: title = soup.find('meta', property="og:title")['content'] if "403" in title or not title: import urllib2 opener = urllib2.build_opener() opener.addheaders = [('user-agent', 'mozilla/5.0')] response = opener.open

discrete mathematics - How to write psuedocode to compute n!!(double factorial) recursively? -

n!!= 1*3*...*n, if n odd. n!!= 2*4*...*n, if n even. i've been trying, i'm having tough time starting problem. if n = 1, n!! = 1 if n = 2, n!! = 2 else n!! = n * (n-2)!!

node.js - How to find payload in hapi -

i have following route in hapijs server. , trying create new file using ajax. { method: 'post', path: '/create', config : { payload:{ maxbytes: 10*1024*1024, output:'stream', parse: true, allow: 'multipart/form-data' }, handler: function (request, reply) { var data = request.payload; if (data.file) { // undefined var name = data.file.hapi.filename; var path = writepath + '/' + name; var file = fs.createwritestream(path); file.on('error', reply); data.file.pipe(file); data.file.on('end', function (err) { reply({ filename: data.file.hapi.filename, headers: data.file.hapi.hea

How to get parameter from routing-url Google App Engine using Java JSP -

i write app engine application using java. want make url better url routing on asp.net. web.xml <servlet> <servlet-name>test</servlet-name> <jsp-file>/test.jsp</jsp-file> </servlet> <servlet-mapping> <servlet-name>test</servlet-name> <url-pattern>/test/*</url-pattern> </servlet-mapping> when type http://localhost:8888/test/123 work me, , use request.getpathinfo() value of * it return /123 , have remove / replace blank char. if type http://localhost:8888/test/abc/123 return /abc/123, value want abc are there better ways or pattern or library solve problem? it return /123, have remove / replace blank char. if type http://localhost:8888/test/abc/123 return /abc/123, value want abc you split string array.

JPG sequence in PHP -

sorry elementary question not proficient in php. have php script puts photo in folder on website gets sent iphone. problem script overwrites previous jpg each time new photo uploaded. file name image.jpg. how can make php script force sequence each time new photo uploaded app (i.e. image_1.jpg, image_2.jpg, etc). <?php $name = "image"; $path = "uploaded/".$name.".jpg"; $output = "{\"response\":\"false\"}"; if(move_uploaded_file($_files['image']['tmp_name'], $path)) { $output = "{\"response\":\"true\"}"; } echo $output; ?> you're setting path , name on lines 2 , 3, use check if file exists, , if set $name image_$i , increment $i <?php $i = 0; { $name = 'image' . (($i > 0) ? '_' . $i : ''); $path = 'uploaded/' . $name . '.jpg'; $i++; } while (file_exists($path)); $output = "{\"respo

android - how can i point the shell go execute an activity that is stored in an rList? -

i trying lauch application in android terminal emulator (on device) command work. am start -n com.hcg.cok.gp/com.hcg.cok.gp.com.clash.of.kings.empireactivity the problem having developer decided nest activity in rlist, took forever find stupid thing after changing directories enough times , using the ls ls -a commands enough times found dumb thing in directory planted this /data/data/com.hcg.cok.gp/files/rlist-com.clash.of.kings.empireactivity is there way am start -n command call dumb thing i have tried am start -n /data/data/com.hcg.cok.gp/com.hcg.com.gp/files/rlist-com.clash.of.kings.empireactivity but terminal still gives me error: error type 3 error: activity class {/data/data/com.hcg.cok.gp/com.hcg.com.gp/files/rlist-com.clash.of.kings.empireactivity} not exist. the package name of empireactivity com.clash.of.kings , correct intent is: am start -n com.hcg.cok.gp/com.clash.of.kings.empireactivity

javascript - How do I delete and move later function arguments to the left if an object type is excluded? -

i apologize if has been answered. don't know better technical term method , can't seem find here or google searches. basically want able make function how jquery handles ajax function arguments. example: $.get(url, callback); , $.post(url, data, callback); basically if data excluded function move callback left in place. since when function runs uses variable names input order. presuming method involve checking arguments[1] , arguments[2] want make sure if correct way since have code clean possible. instead of checking arguments[1] , arguments[2] , should check $.post(url, data, callback) whether url string, data object , callback function

php - How to get reference table data in Laravel 5.1 -

i created model account accountgroup_id refer account_group model. call route this route::get('test', function () { return \app\account::get()->account_group; }); account model has belogsto relationship account_group class account extends model { protected $fillable = ['accountgroup_id', 'accountno', 'accountname','address','contactno']; public function account_group() { return $this->belongsto('app\account_group'); } } account_group model has hasmany relationship account class account_group extends model { protected $fillable =['name','under']; public function account() { return $this->hasmany('app\account','accountgroup_id'); } } but after calling route; got following error. undefined property: illuminate\database\eloquent\collection::$account_group first, second class should named accountgroup .

node.js - NodeJs website TTFB is very high and site is running very slow -

Image
i have created website in nodejs express & jade. when load simple login page less content, taking time load. it's ttfb high (ref screenshot attached.) below app.js code. not sure i'm doing wrong. app.js // packages var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieparser = require('cookie-parser'); var bodyparser = require('body-parser'); var dbhelper = require('./routes/dbhelper.js') var common = require('./routes/common.js') var session = require('express-session') var http = require('http'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(session({ secret: 'keyboard cat', resave: false, saveuninitialized: true, cookie: { secure: true } })) // uncomment

botframework - How do I embed a Web Chat to my Bot? -

i have registered , deployed functional (enough) bot via bot framework management portal. when test via textboxes in admin portal, works great. i'm trying add web chat in web page. i have gone in , configured web chat , now, i'm using iframe gives me hardcoded secret token. additionally, select "enable bot on web chat" checkbox in there. , clear, have redeployed bot after adding iframe & secret. when i'm done, "web chat" displays above independent of of other channels, however, published slider slid off. when deploy bot web chat iframe & secret, web chat control can type in never responds me. still, if test bot in admin panel, works great. other pieces of info: i'm hosting in azure custom domain , commercial ssl my custom domain third-level domain (i.e. https://bot.mydomain.com ) the web chat neither works in local debug nor online the bot emulator works great locally the bot emulator works great if point online-deployed

javascript - Re-sizing a div should re-size other div's proportionately -

i have pasted js code, css , html respectively below. var hgt=0,newhgt=0,bsh=0,diff=0; $('#foots').resizable({ alsoresize:"#footc", handles:"n", start: function(event,ui){ oldhgt = ui.size.height; bsh = $('#bodys').height(); }, resize:function(event,ui){ diff = oldhgt - ui.size.height; if(diff<0) newhgt = bsh - math.abs(diff); else newhgt = bsh + diff; $('#bodys').height(newhgt); }, stop:function(event,ui){ newhgt = bsh - math.abs(oldhgt - ui.size.height); $('#bodys').css("height",newhgt+"px"); $('#bodyc').css("height",newhgt+"px"); $('#foots').css("height",ui.size.height+"px"); } }); #vscale,#canvas { height: auto; width: auto; /* border: 1px solid gray; */ margin-left

c# - Detect 100% CPU load by a referenced library -

i have asp.net (c#) website uses third party dll process data users post via web form. call pretty straightforward: string result = thirdpartylib.processdata(mystring); once in blue moon library hangs , (according hosting provider logs) consumes 100% of cpu. website hosted on shared hosting, have no access iis or event logs. when happens, website automatically stopped hosting provider performance monitor, , have manually switch on. now, know right thing to investigate problem , fix (or replace) dll. it's third-party software, unuable fix it, , support not helpful @ all. moreover, can't reproduce problem. replacing library pain too. is there way in c# detect when dll starts consuming 100%cpu , kill process automatically asp.net code? you cannot "detect" if current process hanging because caller of method (third party or not) you're not in control until returns. what can move call third party library separate executable , have output result vi

android - Access Recyclerview viewholder from activity -

i'm developing music player app android. when song completes send broadcast , in activity want change play/pause icon in row accordingly. the activity receives broadcast of next song don't know how update row activity. protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_now_playing); mstaggergridlayoutmanager = new staggeredgridlayoutmanager(1, staggeredgridlayoutmanager.vertical); mrecyclerview = (recyclerview) findviewbyid(r.id.now_playing_songs_list); mrecyclerview.setlayoutmanager(mstaggergridlayoutmanager); madapter = new listadapter(this, msonglist) mrecyclerview.setadapter(madapter); mreciever = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { if(intent.getaction().equals(musicservice.song_finished)) { //want change row icon he

angularjs - angular button function run when the page loads -

i have ng-click button page loads execute save(); load page before click on submit button, add empty data database, why not wait clicked? can fix it? <div class="col-md-2"> <button ng-click="save()">submit</button> </div> this part of controller : var app = angular.module("app", ['angularjs-dropdown-multiselect']); app.controller('autocompletectrl', ['$scope', '$rootscope', 'myservices', function ($scope, $rootscope, myservices) { $scope.save = function () { var vcisel = angular.copy($scope.searchtext); var rolessel = angular.copy($scope.selecteditems); myservices.addrole(sel, "adad",rolessel) .success(function (data) { }) .error(function (error) { $scope.status = 'unable load customer data: ' + error.message; }); }; $scope.save(); }]); at end of controller definition, invo

How to add an attribute or attribute sets on homepage magento. 1.9.0 -

i want add custom search on frontend(magento). want add 2 or 3 attributes on frontend make custom/advanced search. have tried add catalosearch/advanced frontend attributes not showing dropdown menu product page. :) first make attribute searcheable admin. catalog->attribute->manage attributes. enable used in quick search , used in advanced search. searcheable attribute this $attributes = array(); foreach ($this->getsearchableattributes() $_attribute): $attributes[$_attribute->getattributecode()] = $_attribute; endforeach; show attribute $attributes['attribute_code'];

multithreading - Threading in python flask server -

i trying create thread in flask server , doesnt seem firing. not getting errors either. here code: t = thread(target=pourdrink, args=(valid_bcm_pin_numbers[0],float(j[1]), mc, total,)) print "turning on 1" t.start and i'm calling: def pourdrink(drink, amount, mc, total): # long running task here data = pin_update(drink, 0) print "sleeping amount " + str(amount) time.sleep(float(amount)) the thing never prints out "sleeping amount" there doing wrong? let me know if need provide more info or code well. you need call thread.start method: t.start() just referencing not enough.

unit testing - How can I execute in parallel Selenium Python tests with unittest -

for example have 2 tests: class test(unittest.testcase): def setup(self): self.driver = webdriver.firefox() self.driver.get("http://google.com") def teardown(self): self.driver.quit() def test_selenium_1(self): search_field = self.driver.find_element_by_id("lst-ib") search_field.send_keys("test 1. number 1") search_field.submit() time.sleep(2) def test_selenium_2(self): search_field = self.driver.find_element_by_id("lst-ib") search_field.send_keys("test 1. number 2") search_field.submit() time.sleep(2) if __name__ == '__main__': unittest.main() how can execute these 2 tests in parallel concurrent.futures.executor ? is possible? i created runner these purposes. and can execute tests in parallel modules, classes , methods. import unittest concurrent.futures import threadpoolexecutor class runner(): def parallel_execution(self, *name, options='

java - Draw on Loaded image on Android -

i load pic using code uri selectedimage = data.getdata(); string[] filepathcolumn = { mediastore.images.media.data }; cursor cursor = getcontentresolver().query(selectedimage, filepathcolumn, null, null, null); cursor.movetofirst(); int columnindex = cursor.getcolumnindex(filepathcolumn[0]); string picturepath = cursor.getstring(columnindex); cursor.close(); imageview imageview = (imageview) findviewbyid(r.id.imageview); imageview.setimagebitmap(bitmapfactory.decodefile(picturepath));` it work , shows pic on imageview not want draw circle on , save, can draw using code bitmapfactory.options myoptions = new bitmapfactory.options(); myoptions.indither = true; myoptions.inscaled = false; myoptions.inpreferredconfig = bitmap.config.argb_8888;// important myoptions.inpurgeable = true; bitmap bitmap = bitmapfactory.decoderesource(getresources(),r.drawable.ic_luncher); paint paint = new paint(); paint.setantialias(true); paint.setcolor(color.blue); bitmap workingbitmap = bitmap.