Posts

Showing posts from June, 2011

python - Return count of column based on previous data -

how can count user_id group type, country_code , date current type d or , previous type d or a. e.g query should return country_code 1 , type d => count(user_id) = 1 , country_code 2 , type => count(user_id) = 1 id country_code type user_id date 1 1 d 1 01-01-14 2 1 nd 1 02-01-14 3 1 d 1 03-01-14 4 1 d 1 04-01-14 5 2 d 1 05-01-14 6 2 nd 2 06-01-14 7 2 1 07-01-14 8 2 1 08-01-14 i think want following: select type, country_code, date, count(distinct user_id) tbl x type in ('d', 'a') , exists (select 1 tbl y y.type in ('d', 'a') , y.country_code = x.country_code , y.date <= (select max(z.date) tbl z z.date < x.date , z.type = y.type

java - Ant Colony Optimization trouble -

i have problem: build tower formed n colored cubes given side. there can't cube small side on cube bigger side , neither can't 2 neighbor cubes same color. i'm trying solve using ant colony optimization. trouble have don't know how choose next cube move ant on , leave pheromone on it. example: following cubes: c1 - side = 5, color = red c2 - side = 2, color = green c3 - side = 10, color = blue c4 - side = 1, color = red solution be: c3, c1, c2, c4 i've done far: ant class: public class ant { private int[] visited; private int size; public ant(int size) { this.size = size; this.visited = new int[size]; } public void clearvisited(){ for(int i=0; < size; i++){ visited[i] = -1; } } public void visit(int index, int cube) { visited[index] = cube; } public int visited(int index){ return visit

ios - NSConstraint.constant checking its value after setting to avoid animating view again -

Image
i have uitextfield (email) , uilabel (email error messages) - see image when enter invalid email, animate in uilabel in changing constraint (linked iboutlet - default setting 22 in ib overridden in viewdidload 0) 0 22. works perfectly. when enter valid email, reverse happens. works perfectly. i'm having trouble finding way not animate uilabel in even if there code below: self.usernameerrormessage.text = @"invalid email"; nslog(@"before constant: %f", self.emailerrormessagelabelheightconstraint.constant); nslog(@"before email textfield height: %f", self.usernameerrormessage.bounds.size.height); if (self.emailerrormessagelabelheightconstraint.constant != 22) { self.emailerrormessagelabelheightconstraint.constant = 22; [self.view setneedsupdateconstraints]; [self.view layoutifneeded]; [uiview animatewithduration:0.5 animations:^{ nslog(@"after constant: %f", self

sockets - Sending messages over an unreliable network in JAVA -

i need send continuous flow of messages (simple textmessages timestamp , x/y coordinates) on wireless network moving computer. there lot of these short messages (like 200 per sec) , unfortunately network connection unreliable since sending device leave wlan area time time... when connection not available, upcoming messages should buffered until connection again. order of transmitted messages not matter, since contain timestamp, messages must transferred. what simple reliable method sending these telegrams? possible use "plain" tcp or udp socket connection? messages buffered when connection temporarily down , send afterwards automatically? or connection loss directly detected , reported, buffer messages , try reconnect periodically on own? libraries netty here? i thought using broker broker communication (e.g. activemq network of brokers) alternative. overhead big here?! suggest messaging middleware in case? tcp guaranteed delivery (when it's connected is)

AJAX sequential request to the same page -

i trying make 2 ajax requests same page 1 after another. but, getting response of last request. have below code. <html> <head> <script type="text/javascript"> var xmlhttp; xmlhttp = new xmlhttprequest(); xmlhttp.open("get","getcdr.php?r=2",true); xmlhttp.send(); xmlhttp.open("get","getcdr.php?r=4",true); xmlhttp.send(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readystate==4 && xmlhttp.status==200) { document.getelementbyid("mytab").innerhtml=document.getelementbyid("mytab").innerhtml+xmlhttp.responsetext; } } </script> </head> <body> <table id="mytab"> <tr><td>sl</td><td>mal</td></tr> </table> </body> </html> your second request overwriting first request. since you're using async requests, should leveraging callbacks make sequential callbacks, if 1 request dep

wordpress - switch_to_blog errors when connecting to another wpdb -

i have created function within wordpress theme allows site connect second multisite installation (the "hub") , grab our staff directory, emergency alert information, , headline news. second multisite broken down several blogs: emergency notifications: site 2 campus directory: site 3 events calendar: site 4 news: site 5 dining calendar: site 6 you can see them in action @ http://inside.scrippscollege.edu the problem comes when site , our new external site share blog_id. example, site 3 (our faculty page) on inside scripps , site 3 (emergency response) on external staging site cannot run directory function because use same blog_id. don't know how work around problem, or troubleshoot it. the function begins this: global $wpdb; $wpdb_backup = $wpdb; // copies global wordpress variables later $wpdb = new wpdb('xxxx', 'xxxx', 'xxxx', 'xxxx'); $wpdb->set_prefix('wp_'); $wpdb->show_errors(); global $blog_id; global $swi

vb.net - Orientate a rotation Vector in 3D space to face a destination -

i got 2 position vectors in 3 dimensional space: dim position vector3 dim destination vector3 i got rotation vector, used rotate object. contains yaw, pitch , roll values (=> ranges 0 pi * 2) i want rotation vector point correct orientation, object in end points @ destination vector, being @ position vector. i have no idea how accomplish though. it's been while since did 3d stuff, hence going conceptual-only answer. you can construct 3 orthogonal unit vectors , combine rows in matrix. matrix transformation. know 1 vector already... forward = to_point - from_point now need "up" , "right" vector, can calculated using cross-product, provided have sort of world reference vector (otherwise solution space infinite). example, "up" vector should defined. this mean solution may suffer gimbal lock if "forward" vector becomes parallel "up" vector. in case, cross product come out small (or zero) , break. th

Default inputType of EditText in android -

suppose have edittext in layout. <edittext android:id="@+id/username" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/username" /> we can set inputtype edittext text, number, phone, textpassword, etc. inputtype of edittext default? it text no special options. type_class_text

java - Parse .txt to .csv -

is possible create java program recognizes text in .txt file , write in .csv file? if yes,how start such problem? my .txt file text1 |text 2 somehow char "|" , split 2 cells. this simple in java 8: public static void main(string[] args) throws exception { final path path = paths.get("path", "to", "folder"); final path txt = path.resolve("myfile.txt"); final path csv = path.resolve("myfile.csv"); try ( final stream<string> lines = files.lines(txt); final printwriter pw = new printwriter(files.newbufferedwriter(csv, standardopenoption.create_new))) { lines.map((line) -> line.split("\\|")). map((line) -> stream.of(line).collect(collectors.joining(","))). foreach(pw::println); } } first files @ path objects. open printwriter destination path . now java 8 stream processing lambdas: files.lin

java - how to Solve SQL Integrity Constraint Violation Exception -

i created entity class has same properties project.java, , created class can persist entity object. also, created database using databases in netbeans using embedded jdbc. have persistence.xml, provides properties connect db, , used persitence class on entitymanagerfactory object. connection seems fine having "internal exception: java.sql.sqlintegrityconstraintviolationexception: column 'project_id' cannot accept null value." error. is ok create db manually (executing ddl) or should create table in persistence.xml using "property name="javax.persistence.jdbc.url"" value="create-tables" ? regards you have set value of column project_id . you can either in code, example using annotations @sequencegenerator or @genericgenerator , or use db features (trigger) set id during insert.

parsing - C Parser using lex and yacc -

i fiddling code ansi c parser given here http://www.lysator.liu.se/c/ansi-c-grammar-y.html , here http://www.lysator.liu.se/c/ansi-c-grammar-l.html . unfortunately, code isn't working - modified bit make print message upon parsing input program, message never printed, if input program in c no syntax errors. i'd glad if can me out here. edit: just clarify - testing publicly available lex + yacc program on simple input c program prints "hello world!". links present above. please open them see code. it looks yacc file checks input program correct (by printing error if not), nothing else. add semantic actions (some code execute when rule has been matched), between curly braces after rules. see http://dinosaur.compilertools.net/bison/bison_4.html#sec11 you can start printing when rule matched, if want build c compiler, you'll have build ast . edit you need add main method calls parser. add void main() { yyparse(); } at end of yacc f

java - Get return value of build configuration -

i create cdt eclipse plugin specific build configuration. use setbuildcommand() , setbuildarguments() functions call batch file. my current code is: icprojectdescriptionmanager mngr = coremodel.getdefault().getprojectdescriptionmanager(); icprojectdescription des = mngr.createprojectdescription(project, false); managedproject mproj = new managedproject(des); configuration cfg = new configuration(mproj, null, "my.configuration.id", "myconfiguration"); cfg.setbuildcommand("script.bat"); cfg.setbuildarguments(arg1 + " " + arg2); i return code batch file can't find way it. any idea? maybe know how add marker project hold information? correct me if i'm wrong, programatically creating cproject definition bad mojo. answer using 'standard' plugin.xml + activator model (like when make new plugin project template). i think you're looking ierrorparser, can parse output bat file. myexerrorparser.java import or

Appending another child element to xml using powershell -

i have following xml file . add thing it, have tried several different ways can’t seem right. this xml files looks . <root> <device> <name>c:</name> <time> <timeofcheck>2014.3.18.22.36.43</timeofcheck> <size>120.14</size> <freespace>38.18</freespace> </time> </device> <device> <name>x:</name> <time> <timeofcheck>2014.3.18.22.36.43</timeofcheck> <size>23.23</size> <freespace>11.47</freespace> </time> </device> </root> i trying add <time> <timeofcheck>2014.3.18.22.36.43</timeofcheck> <size>120.14</size> <freespace>25</freespace> </time> so ends looking <root> <device> <name>c:</name> <time> <timeofcheck>2014.3.18.22.36.43</timeofcheck> <size>120.14</size>

c# - Finding file size to decide on size cutoff for loading? -

i writing 32 bit app , 4gb, files process can huge upto 3.5 gb, size should consider before loading file processing? i mean, c# .net suppose have limited ram framework, should cutoff file (though depends on how memory application takes, arrive @ ballpark figure) ? ( dont have file of magnitude, want handle before memory error) i suppose, need actual file size file size on disk ? , possible find without opening file? you can use fileinfo.length property. but instead consider using stream classes (see *reader classes in system.io), allow read parts of file, analyse , discard. in way don't care size of file @ all.

Copy more excel shapes into powerpoint -

i have following code let me copy sub pptcopy() dim pptapp powerpoint.application dim ppt powerpoint.presentation dim slide powerpoint.slide dim shape1 powerpoint.shape var2 = "c:\documents , settings\aa471714\desktop\presentation2.pot" set pptapp = createobject("powerpoint.application") set ppt = pptapp.presentations.open(var2) set slide = ppt.slides(2) set shape1 = slide.shapes.paste(1) pptapp.visible = true call copyexcel1 shape1 .left = 100 .width = 100 end end sub and macro sub copyexcel1() dim oexcel excel.application dim owb workbook dim cht excel.chartobject var2 = "c:\documents , settings\aa471714\desktop\template.xls" set oexcel = new excel.application set owb = oexcel.workbooks.open(var2) oexcel.visible = true sheets("sheet5").chartobjects("achmeabanknl").chart.chartarea.copy end sub i have 2 issues: i want move excel picture specific place in powerpoint (fe shape 3) i want copy more excel figur

c# - Two interfaces have same method -

interface { int add(int a,int b); } interface b { int add(int a,int b); } class d : a, b { int add(int a,int b) { return a+b; } } code works fine , didn't produce error. class d using interface's method? neither, since neither interface has method, merely method signature. method in d implements signature provided both interfaces, works. remember, interface merely specifies signatures of methods must exist in implementation.

google maps - Backbone GoogleMaps MarkerCollectionView collection and pagination -

i'm building page holds 2 different views. first view list of locations , information , second view google map shows markers of locations displayed on first view. the problem @ moment since collection can big , page holds pagination , displays 20 locations on each page, second view shows whole locations markers. i show in second view google map markers depending on page i'm on. how can approach problem? you should have view number 2(the map), listen change in collection shown in view number 1(the list). in view 2, when collection of places/markers change, need call setmap, clear markers, call collection.foreach, , place marker on map.

php - xampp, html files don't work in subfolders -

i have strange problem xampp. use: xampp 1.8.3 - windows 7 64bit on localhost, can not open files .html in subfolders. example: localhost/folder/*.html = works. page opens localhost/folder/subfolder/*.html = doesn't work. returns "object not found" with *.php files no problem, work in folder. looked @ configuration file httpd.conf <ifmodule dir_module> directoryindex index.php index.pl index.cgi index.asp index.shtml index.html index.htm \ default.php default.pl default.cgi default.asp default.shtml default.html default.htm \ home.php home.pl home.cgi home.asp home.shtml home.html home.htm </ifmodule> seems okay....

Internet explorer fails to play WEBM when encoded with FFMPEG -

i creating video hosting site users can upload videos converted web viewable webm format via ffmpeg, seem have problem getting html5-video work on internet explorer (ie 11, windows 8.1, webm extensions installed). the standard 'big bunny buck' video (found here: http://www.webmfiles.org/demo-files/ ) works fine on ie, if convert video webm using ffmpeg doesn't play @ states 'invalid source' on html5 video element. i using these commandline args convert webm on ffmpeg: ffmpeg.exe -y -i bunny.webm -vcodec libvpx -acodec libvorbis -f webm bunny2.webm its werid videos work fine on vlc, windows media player, firefox , chrome not on ie. ran issue before or offer pointers of how fix it? you can download example zip ( https://www.dropbox.com/s/dhp64c4rh7xqttj/ie-webm.zip ) includes bat script run above ffmpeg arguments , html page rendering 2 video elements before , after encoding ffmpeg. thanks! downloaded latest version , seems have sorted it, mus

c++ - What does "prompting" for an integer mean? -

i have following question on test review: you write program following: prompt user 32-bit integer number entered text via console determine if number prime output either phrase “prime” or “not prime” appropriate i'm confused prompting 32-bit integer. same declaring normal int variable? short answer: no. longer answer: possibly yes. why? int doesn't have fixed size; it's defined having at least 16 bits. might happen have 32 bits, isn't guaranteed. use int32_t or uint32_t purpose.

mvcsitemap - Strange error with MvcSiteMapProvider. It some how find 2 root nodes -

i using mvcsitemapnode without xml decorator's way. said in post i sure have 1 node empty root node. works, except times error. there more 1 node declared without parent key. parent key must set 1 node in sitemap. node no parent key considered root node. note when defining nodes in xml, xml file must contain root node. you can disable xml configuration setting mvcsitemapprovider_enablesitemapfile setting "false". external di configuration, can disable xml parsing removing xmlsitemapnodeprovider mvcsitemapprovider di module. alternatively, can set mvcsitemapprovider_includerootnodefromsitemapfile setting "false" exclude root node xml file, include of other nodes. external di configuration, setting can found on constructor of xmlsitemapnodeprovider. sitemapcachekey: 'sitemap://localhost/' ambiguous root nodes: parentkey: '' | controller: 'home' | action: 'index' | area: '

ruby on rails - Jquery/Datepicker works locally but not in production (heroku) -

the javascript error message keep seeing on browser inspector says "referenceerror: can't find variable $" on application-ccd035fs...... .js:1" it works fine locally though. based on error i'm imagining isn't recognizing jquery syntax. not sure how fix it. appreciated! my application.js follows: //= require jquery //= require jquery-ui //= require jquery_ujs //= require_tree . $(document).ready(function(){ $('#showdate').datepicker({date_format: "dd/mm/yyyy", altfield: '#mile_date', altformat: 'yy-mm-dd'}); }); my gem file has gem: 'jquery-rails', '~> 2.3.0' my layout has following in head: <%= javascript_include_tag "application" %> the relevant form code follows: <div class="field"> <%= f.label :date, "date:" %><br /> <%= f.text_field :date, :id => "showdate" %> </div> <%= f.hidd

c++ - can overuse in Macros hurt performance? -

i have long code, being called millions of time, have noticed if change macros inline functions code runs lot faster. can explain why is? aren't macros text replacement? opposed inline functions can call function? a macro text sustitution , such produce more executable code. every time call macro, code inserted (well, not necessarily, macro empty... in principle). inline functions, on other hand, may work same macros, might not inlined @ all. in general, inline keyword rather weak hint requirement anyway, compilers nowadays judiciously inline functions (or abstain doing so) based on heuristics, number of pseudo-instructions. inline functions may cause compiler not inline function @ all, or inline couple of times , call non-inined in addition. surprisingly, not inlining may faster inlining, since reduces overall code size , number of cache , tlb misses.

javascript - How to Debug EJS code in Chrome/Safari -

i using ejs templates canjs , looking way debug ejs code. firebug can show me syntax errors in ejs in other browsers, not able see anything.i need go through ejs file solve errors. searched on web , found out ejs_fulljslint https://code.google.com/p/embeddedjavascript/ , not able run properly. included script html file still wasn't getting console errors. not able find demo of debugging on web. can tell me how debug ejs code. if can provide me example, highly appreciated. in end, ejs translates javascript , therefore placing debugger; statement need , opening developer tools, might trick you. example, check on i variable in loop place debugger; this: <script type="text/ejs" id="todolist"> <% for(var = 0; < todos.length; ++i) { %> <% debugger; %> <li><%= this[i].attr('description') </li> <% } %> </script>

excel vba - Macro to merge cells from two columns -

i create macro merges cells in column cell in column b if there data in column a. please help do need this? assumed columns , b filled , concatenated values cells , b in cell a. sub concatenate() dim row integer range("a1").select row = 0 until activecell.offset(row, 0).value = "" activecell.offset(row, 0).value = activecell.offset(row, 0).value + activecell.offset(row, 1).value row = row + 1 loop end sub

angularjs - How Difficult/Project Size/Time to wrap an Angular/Firebase WebApp in PhoneGap -

how difficult wrap existing web app sole purpose of acquiring push notification capabilities?? i have complex working webapp proprietary ui utilizes custom css. written in angular , uses firebase , couple of proprietary backend servers ( python tornado , node ). apps runs reasonably ui not snappy , important lack of push notifications. understand knows phonegap how difficult do? many changes required of web app access push api?>

haskell - Moving .ghc and .cabal to a different user -

how can move ghc , cabal installed packages different user? i've copied directories i'm getting error messages like: configparser.hs:15:8: not find module `data.bytestring.char8' there files missing in `bytestring-0.10.2.0' package, try running 'ghc-pkg check'. use -v see list of files searched for. ghc-pkg check shows file package missing. how can resolve this? note: question intentionally not show research effort, because answered q&a-style. first, need copy .ghc , .cabal . these contain binary files , configurations. for simplicity, assume moving user foo user bar . note moving between architectures not possible, binaries produced ghc not platform-independent. after copying aforementioned directories, there paths /home/foo remaining in different locations. use sed replace (run bar ): sed -i -e "s/foo/bar/g" ~/.cabal/config sed -i -e "s/foo/bar/g" ~/.ghc/*-*/package.conf.d/*.conf however,

button - Errors with java applet -

i trying write applet calculate average amount of 4 input boxes or clear fields depending on box clicked. think have right, there error somewhere causing following error statement appear: exception in thread "awt-eventqueue-0" java.lang.numberformatexception: input string: " 10" here's have far: import java.applet.*; import java.awt.*; import java.awt.event.*; public class blooddriveaverage extends applet implements actionlistener { public void init() { label title = new label("blood drive!"); setbackground(color.red); label label1 = new label("department 1 amount: "); textfield1 = new textfield(" "); avg = new button("average"); clear = new button ("clear fields"); avg.addactionlistener(this); clear.addactionlistener(this); label label2 = new label("department 2 amount: "); textfield2 = new textfield(" "); label label3 = new label("department 3 a

python - How to send Autobahn/Twisted WAMP message from outside of protocol? -

i following basic wamp pubsub examples in the github code : this example publishes messages within class: class component(applicationsession): """ application component publishes event every second. """ def __init__(self, realm = "realm1"): applicationsession.__init__(self) self._realm = realm def onconnect(self): self.join(self._realm) @inlinecallbacks def onjoin(self, details): counter = 0 while true: self.publish('com.myapp.topic1', counter) counter += 1 yield sleep(1) i want create reference can publish messages on connection elsewhere in code, i.e. myobject.myconnection.publish('com.myapp.topic1', 'my message') from similar question answer seems upon connection, need set self.factory.myconnection = self . have tried multiple permutations of without success. the factory setup portion below: ## create wamp application sessio

javascript - Get word/character screen position by its string index in Kinetic.js Text element -

Image
input: some text contain regular words , special words/char separated #. font , fontsize constant, lets arial 14 without styling. example: lorem ipsum dolor #sit# amet, consectetur adipisicing elit, sed eiusmod tempor incididunt ut labore #et# dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis #aute# irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. excepteur #sint# occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. output: when user clicks #someseparatedword# need log word in console (in example user click 'sit', 'et', 'aute', 'sint' , log words). problem in how or calculate word/char canvas coordinates? your # delmiters can't recognize word because context.filltext paints words on canvas. those words become unrecognizable part of canvas bitm

java - Can I make an overridden method synchronized? -

i overriding method superclass, want method synchronized. allowed? alternative? yes, it's allowed doesn't change contract implementation. think add synchronized block : synchronized(this) { just @ start of method, achieve same result. there other (possibly hidden) locks deeper in method, makes part of implementation rather api.

javascript - Is there a way to get clicked element on blur or focusout event? -

this question has answer here: get clicked object triggered jquery blur() event [duplicate] 4 answers how know click on blur or focusout of input? i've sketched small example: html: <div id ="all"> <div id="whereisinput"> <input id="blur"/> </div> </div> css: #whereisinput{ height: 100px; width: 200px; background-color: yellow; } js: function onblur(e){ jquery('#all').append('<div>' + e.type + ', ' + e.target.tostring() + '</div>') } jquery('#blur').blur(onblur); jquery('body').on('click', onblur); so questions is: where click when blur occured? i've investigate this: 1. can't find in blur or focusout event arguments 2. click on body occurs later blur you can setup

r - RStudio fatal error while generating matrix -

i'm processing 2 char vectors outer function, results in matrix. i'm using levensthein function, compares 2 strings , outputs simialirity of them, each item vectors. for tests 1000x1000 vectors, runs fine. runs in 4.95 sec. calc_levensthein_d <- function(vector1,vector2){ #total matrix total <- as.matrix(outer(vector1,vector2,levenshteinsim)) return(total) } however 10000x5000 vector, fatal error message, @ ending of processament. here tests: ~1000x1000 -> 4~6 sec ~1000x5000 -> 40~60 sec ~10000x1000 -> 688 sec ~ 11min ~10000x5000 -> fatal error after 2hours it's memory problem? ideias? goal process 120000x10000 matrix. obs: levenshteinsim record linkage package.

java - draw a rectangle over an image -

i have tried code below drawing rectangle on image(jlabel) not drawing. please solve this. protected void paintcomponent(graphics g) { this.paintcomponent(g); g2 = (graphics2d) g; g.drawrect(n,n1,40,40); } private void jlabel1mouseclicked(java.awt.event.mouseevent evt) { // todo add handling code here: k=0; f=jlabel1.getmouseposition(); n=f.x; n1=f.y; n=n+p/2; n1=n1+(q/2-25); repaint(n,n1,40,40); } you have infinite recursion there, , stack overflow. this: this.paintcomponent(g) should instead: super.paintcomponent(g);

r - how do you convert df to json file with numbers as number -

i trying convert data frame json format. data frame called x: structure(list(desc = c("web", "mobile", "tv", "store"), total = c(223786915, 42053151, 232299534, 26317530), name = c("total login", "total login", "total login", "total login")), .names = c("desc", "total", "name" ), row.names = c(na, 4l), class = "data.frame") this function: servers <- split(x,x$name) dumfun <- function(x){ sdata <- servers[x][[1]] if(nrow(sdata) >0){ # create appropriate list dumlist <- unname(apply(sdata[,c(1,as.numeric(2))], 1, function(y) unname(as.list(y)))) return(tojson(list(name = x, data = dumlist))) } } jsdata <- lapply(names(servers), dumfun) jsind <- sapply(jsdata, is.null) p<-paste(jsdata[!jsind], collapse = ',') p<-paste('[', p, ']') it treating x$total string. need x$total number , don'

java - What is the logic behind collision detection in 2d games? -

this question has answer here: collision detection complex shapes 1 answer i want create 2d game tile based map. main problem collision. if there tree in way, how make sprite not move through tree? pseudo-code: some_event() { if (bullet.x == monster.x && bullet.y == monster.y) { collision_occurs(); } } of course semantics such event fired , whether or not event handler makes more sense (i.e.: collision_occurs() when x , y coordinates meet, rather if meet while some_event() fired) depend on game. if analyze more notice bullet , monster aren't 1 pixel each, more like: // while approaching left if ((bullet.x + (bullet.radius)) >= (monster.x + (monster.radius))) these fine details come after. have moving objects , these objects share coordinates. when these coordinates, properties of representational objects, near eno

javascript - Keep $_GET value of a drop down menu after submitting the form -

edited: demo: http://jsfiddle.net/53gkh/6/ i have 2 drop down menu's in html: first 1 car brand:(is working fine) <form action="car-list.php" method="get"> <select name="search" id="main_list" > <option value="bmw"<?php if ($_get['search']== 'bmw') {echo "selected='selected'"; } ?>>bmw</option> </select> </form> after user choose brand second drop down menu 'activated' choose model of car: <select name="model" id="brand" class="secondary"> <option disabled selected> kies </option> </select> to 'activate' second drop down menu im using following js code: $(function() { var sel, i, list = ['aixman', 'alfaromeo', 'bmw'], aixman = ['aixman'], alfaromeo = ['33', '75'], bmw= ['1-serie','3-serie&#

vb.net - Multiple Web Browsers sharing Document Completed? -

i have 4 web browsers , have similar coding inside each documentcompleted event. however, 4 using different login: ie: webbrowser1 = user1 webbrowser2 = user2 webbrowser3 = user3 webbrowser4 = user4 etc but, strange reason, wb4 using wb1s login, wb1 , wb2 using wb2s login , wb3 using wb4s login. now, know sounds crazy there recent update affects stuff? because code working fine until few days ago.

angular ui - Masking in AngularJS -

is possible create mask in angularjs looks this 02years 07months. and when user clicks on text box should change following text 0207 thanks ton! you can use directive bind focus , blur events. http://plnkr.co/sfyfystslqpztlugbmwh <input type="text" year-month data="foo.bar"></input> app.directive('yearmonth', function() { return { restrict: 'a', scope: { data: '=' }, link: function(scope, element, attr) { var re = /(\d{2})(\d{1,2})()/; function addmask(text) { return text.replace(re, "$1years$2months"); } function removemask(text) { return text.replace(re, "$1$2"); } element.val(addmask(scope.data)); element.bind('blur', function () { scope.$apply(function() { var text = element.val(); scope.dat

jquery - php - Enabling users to favorite posts -

on website want allow users favorite posts. logged in user directed page shows posts , under each 1 placed hyperlink favorite. want text change favorite favorited , other way around. how do that? html , php <?php session_start(); require_once('connection.php'); mysql_select_db($database_connection, $connection); $query_favorite = "select username, post_id favorite"; $favorite = mysql_query($query_favorite, $connection) or die(mysql_error()); $row_favorite = mysql_fetch_assoc($favorite); $totalrows_favorite = mysql_num_rows($favorite); ?> <a href="#" class="favourite">favourite</a> tables in datatbase create table `user` ( `username` varchar(45) not null, `email` varchar(45) not null, `password` varchar(45) not null, `profilepic` varchar(50) default null, primary key (`username`) ) engine=innodb default charset=utf8 create table `post` ( `post_id` int(11) not null auto_increment, `title` varchar(100) no

algorithm - Peak signal detection in realtime timeseries data -

Image
update: best performing algorithm so far is one . this question explores robust algorithms detecting sudden peaks in real-time timeseries data. consider following dataset: p = [1 1 1.1 1 0.9 1 1 1.1 1 0.9 1 1.1 1 1 0.9 1 1 1.1 1 1 1 1 1.1 0.9 1 1.1 1 1 0.9 1, ... 1.1 1 1 1.1 1 0.8 0.9 1 1.2 0.9 1 1 1.1 1.2 1 1.5 1 3 2 5 3 2 1 1 1 0.9 1 1 3, ... 2.6 4 3 3.2 2 1 1 0.8 4 4 2 2.5 1 1 1]; (matlab format it's not language algorithm) you can see there 3 large peaks , small peaks. dataset specific example of class of timeseries datasets question about. class of datasets has 2 general features: there basic noise general mean there large ' peaks ' or ' higher data points ' deviate noise. let's assume following: the width of peaks cannot determined beforehand the height of peaks deviates other values the used algorithm must calculate realtime (so change each new datapoint) for such situation, boundary value needs constructed

c++ - Is it possible to take two values of one class to another class and use it? -

i beginner. and, tried one. #include <iostream> using namespace std; class square { int number; public: square(int a): number(a) {} int getsquare() { return number*number; } }; class sumnumber { square a; int firnum; int secnum; public: sumnumber(int number, int x, int y): a(number),firnum(x), secnum(y) {} int getsumnumber() //output-er { return firnum + secnum + a.getsquare(); } }; int main() { sumnumber a(2,3,4); //sums squared number 2, , 3 , 4 cout << "sum of numbers\t" << a.getsumnumber() << endl; //=11 } but, if wanted have 2 values of class square class square { int number; int nextnumber; public: ... }; and on other class class sumnumber //creating class sumnumber { square a; int firnum; //first number int secnum; //second number public: ... }; question is: possible take 2 values declared in square cl

ios - Storyboard issue: Gesture recognisers cannot be used on prototype objects -

this question has answer here: why i'm getting gesture recognizers cannot used on prototype objects? 2 answers i started error on project: gesture recognisers cannot used on prototype objects. seems error in storyboard. might have stated after upgraded to: xcode 5.1 does know means? how can fixed? i solved problem myself locating places in storyboard connected tapgesturerecognizer directly control inside custom uitableviewcell. strange, because in xcode 5 used work , started screaming in xcode 5.1.

c - int vs short vectorization -

i have following kernel vectorized arrays integers: long valor = 0, i=0; __m128i vsum, vecpi, vecci, vecqci; vsum = _mm_set1_epi32(0); int32_t * const pa = a->data; int32_t * const pb = b->data; int sumdot[1]; for( ; i<size-3 ;i+=4){ vecpi = _mm_loadu_si128((__m128i *)&(pa)[i] ); vecci = _mm_loadu_si128((__m128i *)&(pb)[i] ); vecqci = _mm_mullo_epi32(vecpi,vecci); vsum = _mm_add_epi32(vsum,vecqci); } vsum = _mm_hadd_epi32(vsum, vsum); vsum = _mm_hadd_epi32(vsum, vsum); _mm_storeu_si128((__m128i *)&(sumdot), vsum); for( ; i<size; i++) valor += a->data[i] * b->data[i]; valor += sumdot[0]; and works fine. however, if change datatype of , b short instead of int , shouldn't use following code: long valor = 0, i=0; __m128i vsum, vecpi, vecci, vecqci; vsum = _mm_set1_epi16(0); int16_t * const pa = a->data;

python - Iterating over nested list -

i have list nested list returned view, - [[1, [1, 2, 3]], [2, [2, 3, 4]], [3, [3,4,5]]] i want this, work in python - for obj in my_list: nested_obj in obj[1]: print nested_obj but django template system, if try - {% obj in data_list %} <h2>{{obj.0}}</h2> <p> {{for nested_obj in obj.1}} <h5>{{nested_obj}}</h5> {{ endfor }} </p> {% endfor %} i - could not parse remainder: ' nested_obj in obj.1' 'for nested_obj in obj.1' why this? thanks! edit - so, stupid - wrote {{for .... }} instead of {% ... %} @allcaps {{ x in ... }} causing templatesyntaxerror , should {% x in ... %} . python manage.py shell from django.template import template, context data_list = [[1, [1, 2, 3]], [2, [2, 3, 4]], [3, [3, 4, 5]]] template = """ {% obj in data_list %} obj {{obj.0}} {% nested_obj in obj.1 %} nested {{nested_obj}} {% e

php - Codeigniter caching the same method with other parameters -

i´m working on caching in codeigniter , find out 1 problem don´t know how solve: have method view_produdcts() products according url , render view. turned on cache there if want render product´s parameters first time, it´s ok, if try render products other parameters, still returns me products loaded first time. do know, how solve it? thank ideas. here method: /** * view products parameters */ public function view_products() { $limit = 12; // limit of products per page $attrs = parse_attributes_from_url($_get); // load attributes url $config['per_page'] = $limit; // set config files paging $config['base_url'] = prepare_url_from_attributes_for_paging(generate_url_from_attributes($attrs)); $config['cur_page'] = $attrs['page']; $attrs['limit'] = $limit; $data['products'] = $this->products_model->get_products_specified($attrs); products $data['popular_categories'] = $this->