Posts

Showing posts from January, 2012

mysql - How can I include a field that is not part of the group clause in a ActiveRecord query? -

(ruby 1.9.3-p429; rails 3.0.6) recent changes way queue our tests have rendered our last_ids scope: last_ids = tests.where('end_time != 0'). group(:condition1, :condition2, :condition3, :condition4). select('max(id) id') logically obsolete. previously, tests queued , completed in same order test record created maximum id each grouping latest test record. now, efficiency, have queuing algorithm no longer guarantees order of tests. have added "end_time" column test table. solution, far slow use: max_end_times = tests.where('end_time != 0'). group(:condition1, :condition2, :condition3, :condition4). .maximum(:end_time) which yields hash: {[:condition0, :condition1, :condition2, :condition3]=>:endtime}. follows: hash.each_pair |key, value| last_ids << tests.select(:id). where(condition0: [key[0]]). where(con...

sql - Statistical significance for average values? -

consider voting system. e.g. cars. 10 people think give car a score of 70%. 1000 people think give car a score of 60%. hence, have values 0.7 , 0.6 . how compare these values? goes without saying 1000 votes more significant 10 votes. preferably, efficiently in sql (using avg function or similar). there ought well-known formula type of problem. please help! ok, let's count people. have 1010 people 1000 gave score 60 , 10 gave score 70. average score is: (1000 * 60 + 10 * 70)/(1000 + 10) = 60,09 now put them table , run query against it: create table scores (cust_id int identity(1,1), car char(1), score float); go ------------------------------------------------------ declare @i int = 0; while @i < 1000 begin insert scores(car, score) values ('a', 60.0); set @i = @i + 1 end while @i < 1010 begin insert scores(car, score) values ('a', 70.0); set @i = @i + 1 end; --------------------------------------------...

dbcontext - Does entity framework provide the functionality to update one graph with another dirty graph -

is there method updatecomplexobject in entityframework (6)? have write method myself? i want method modify/delete/add graph returned zoo.animals(), new graph newsetofanimals. animals newsetofanimals = getnewsetofanimalsmock(); zoocontext _db = new zoocontext(); // inherits db context zoo zoo = _db.zoo().include(x=>x.animals).first(); _db.updatecomplexobject(zoo.animals(),newsetofanimals); _db.savechanges(); //the database should consistent after method newsetofanimals graph

Grails jquery changes -

i brand new grails of today , coming ruby on rails. question if edit jquery or code while grails app running locally, need restart server every time see changes? or when save changes should see them on localhost in rails? thanks! grails have auto reloading feature: when grails application executed via 'grails run-app' command configured auto-reloading (development mode). mode disabled when war created via 'grails war' command. this feature recompiles classes don't need restart application in each file change.

objective c - What does "int count = [self count]" mean in this context? -

i guess basic question doing tutorial nick kuh's book "foundation iphone app development" , not understand line: int count = [self count]; ...really initiates "self"? here whole code: #import "nsmutablearray+shuffle.h" @implementation nsmutablearray (shuffle) - (void)shuffle { int count = [self count]; nsmutablearray *dupearr = [self mutablecopy]; count = [dupearr count]; [self removeallobjects]; (int = 0; < count; i++) { // select random element between , end of array swap with. int nelement = count - i; int n = (arc4random() % nelement); [self addobject:dupearr[n]]; [dupearr removeobjectatindex:n]; } } @end since in category of nsmutablearray, self refers instance of nsmutablearray. count property of nsmutablearray returns number of objects contained array. line in question says number of items in current instance of nsmutablearray , store in variable named "count" of type int. int ...

reference - MySQL - are there any benefits replacing an INT(11) UNSIGNED with a FK to INT(11) UNSIGNED that is UNIQUE? -

if have table player_res : +-----------+-------+ | player_id | score | +-----------+-------+ | 1 | 30 | | 2 | 30 | | 3 | 22 | | 4 | 22 | +-----------+-------+ would better have score being foreign key referencing lets num.value , num.value being unique ? score can appear once in num.value field. is there advantages in database size and/or speed both types ( player_res.score , num.value ) int(11)? believe doesn't matter else tried convince me using second table store scores uniquely better performance in case table grow large, that's why decided asking here! regards int(11) same size int 4 bytes in mysql. integer types value in parenthesis number of digit displayed. not type size. http://dev.mysql.com/doc/refman/5.0/en/integer-types.html using secondary table deduplicate score values doesn't seems serious idea... or , really missing subtleties? if size issue, might perhaps use smaller integer (li...

regex - Php regexp for escaping characters -

i have string user may split manually using comma's. for example, string value1,value2,value3 should result in array: ["value1", "value2", "value3"] now if user wishes allow comma substring? solve problem letting user escape comma using 2 comma's or backslash. example, string "hi, stackoverflow" written "hi,, stackoverflow" or "hi\, stackoverflow". i find difficult evaluate such string however. have attempted preg splitting, there no way see if lookbehind or lookahead series of characters consists of or odd number. furthermore, backslashes , double comma's meant escaping must removed well, requires additional replace function. $text = 'hello, world \,asdas, 123'; $data = preg_split('/(?<=[^\\\]),/',$text); print_r($data); result array ( [0] => hello [1] => world \,asdas [2] => 123 )

javascript - Prevent browser(Chrome) to run default functions like scroll with space -

i have used 2 functins here first 1 blocking default feature space bar scroll,etc <span id="current"></span> $("html").on("keydown", function (e) { { e.preventdefault(); } }); document.onkeypress = function(evt) { evt = evt || window.event; var charcode = evt.keycode || evt.which; document.getelementbyid("current").innerhtml=charcode; }; now code works in firefox blocking various default functions of firefox ctrl+a ctrl+s space bar scroll , gives output in span when tried in chrome ,it blocks various default functions of chrome didn't give output in span. i can write as document.onkeypress = function(evt) { evt = evt || window.event; var charcode = evt.keycode || evt.which; document.getelementbyid("current").innerhtml=charcode; return false; }; it worked both firfox , chrome function(evt) long , contain many if-else loops , if press double space or press space...

linux - process substitution in bash, sometimes I have to press "Enter" -

i'm learning use process substitution in bash. here's command: echo text > >(tee log) this pointless command thing have press enter after run it. why that? sometimes happens more useful commands like: ls some_non_existing_file 2> >(tee log) actually enter not needed, can enter next command e.g. date , check. happening because of process substitution command exits first , output gets written on terminal, reason false impression of need press enter .

javascript - Jquery generate html or php page -

it's posible generate file using jquery ? make web site maker. on left side have list of elements : ---------------------------------------------------------------- elements attributes ---------------------------------------------------------------- ------------ | | align 4-col layout | | style 3-col layout | |-------------- 2-col layout | | value ------------ | area drag | class form | drag , drop | id ------------ | elements |--------------- input | | onclick button | | onpress ------------ | | onblure etc... | | ---------------------------...

anova - P-value Troubles in R -

i have question regarding p-values. i've been comparing different linear models determine if 1 model better following function in r. anova(model1,model2) unfortunately, not calculate f or p-value. here example of anova summary did not give p-value analysis of variance table model 1: influence ~ sortedsums[, combos2[1, a]] + sortedsums[, combos2[2,a]] model 2: influence ~ sortedsums[, b] res.df rss df sum of sq f pr(>f) 1 127 3090.9 2 128 2655.2 -1 435.74 for sake of symmetry, here anova summary did yield p-value. analysis of variance table model 1: influence ~ sortedsums[, combos2[1, a]] + sortedsums[, combos2[2,a]] model 2: influence ~ sortedsums[, b] res.df rss df sum of sq f pr(>f) 1 127 3090.9 2 128 3157.6 -1 -66.652 2.7386 0.1004 do know why occurs? not questions require code examples. don't deserve snarked @ being new, , i'm sorry people...

python - Add filter on executable files in filechooser dialog using pygtk when OS is Ubuntu -

i using pygtk create file chooser widget. using ubuntu os. want put filter in selecting files. chooser widget should select executable files (diamond icons or in ubuntu). trying use below code: dialog = gtk.filechooserdialog(title=none,action=gtk.file_chooser_action_open, buttons=(gtk.stock_cancel,gtk.response_cancel,gtk.stock_ok,gtk.response_ok)) filter_file = gtk.filefilter() filter_file.add_pattern("*.bin") filter_file.add_pattern("*.run") filter_file.add_pattern("*.sh") dialog.add_filter(filter_images) dialog.show() it not working. not show executable files in chooser window. there way can put filter on executable files because seems ubuntu not have extension executable files. i'm not familiar gtk, quick @ docs gtk.filefilter leads me believe using filefilter.add_custom instead of filefilter.add_pattern allow write custom filter function can permission bits file determine if executable or not...

android - Customizing the Contextual Action Bar -

Image
so i'm trying figure out how change color of contextual action bar menu item text in abs. how customize text color , positioning (that is, gravity centered) of menu items? i've been struggling styles xml while trying change text color, can't figure 1 out. this style i'm trying achieve. appreciated! thanks! <style name="theme.myapp" parent="@style/holo.theme.light.darkactionbar"> <item name="android:actionbaritembackground">@drawable/selectable_background_myapp</item> <item name="android:popupmenustyle">@style/popupmenu.myapp</item> <item name="android:dropdownlistviewstyle">@style/dropdownlistview.myapp</item> <item name="android:actionbartabstyle">@style/actionbartabstyle.myapp</item> <item name="android:actiondropdownstyle">@style/dropdownnav.myapp</item> <item name="android:actionbars...

android - Unable to start phonegap application in eclipse -

i have import several open source phonegap application in eclipse , can compiled , installed on devices. issue is, when start these applications, android throw dialog saying "unfortunately, (app name) has stopped". after observing log files, found apps, logcat print same message during crash. copy these message here: 08-09 14:48:07.906: w/dalvikvm(1984): unable resolve superclass of lorg/ztepc/rss/rssreaderactivity; (43) 08-09 14:48:07.906: w/dalvikvm(1984): link of class 'lorg/ztepc/rss/rssreaderactivity;' failed 08-09 14:48:07.906: d/androidruntime(1984): shutting down vm 08-09 14:48:07.906: w/dalvikvm(1984): threadid=1: thread exiting uncaught exception (group=0x42077438) 08-09 14:48:07.906: e/androidruntime(1984): fatal exception: main 08-09 14:48:07.906: e/androidruntime(1984): java.lang.runtimeexception: unable instantiate activity componentinfo{org.ztepc.rss/org.ztepc.rss.rssreaderactivity}: java.lang.classnotfoundexception: org.ztepc.rss.rssreaderactivit...

inheritance - Python -- using __init__ with an inherited method for polynomials class -

this class take in input , output polynomial in string form (both ways same format). arithmetic performed in various methods. i've been trying inherit class class use __mod__() special method of first class (or make it's own special method if necessary don't see how can't use original method) perform mod on intake. seems goes __init__() i've tried 5 different versions of this, going far change parent class, , i'm getting nowhere. i'm teaching myself python i'm sure junior python dev can see i'm going totally wrong. import re class gf2polynomial(object): #classes should inherit object def __init__(self, string): '''__init__ standard special method used initialize objects. here __init__ initialize gf2infix object based on string.''' self.string = string #basically initial string (polynomial) self.key,self.lst = self.parsepolyvariable(string) # key determines polynomial compatibili...

Filtering a custom field added to the User Model in Django -

class snippet(models.model): language = models.charfield(max_length=25) content = models.textfield(max_length=500) description = models.charfield(max_length=200) privacy_choices = ( ('me', 'me'), ('friends', 'friends'), ('everyone', 'everyone'), ) privacy = models.charfield(max_length=8,choices=privacy_choices,default='everyone') class siteuser(models.model): user = models.onetoonefield(user) snippets = models.manytomanyfield('snippet', null=true, blank=true) friends = models.manytomanyfield(user, related_name='friends') i trying check if current user friend of person page viewing. then, based off of whether friend, need show snippets right privacy level. so if friend snippets privacy = 'everyone' or 'friends', if stranger, ones privacy = 'everyone', etc. i'm able figure out required privacy level easily, i'm havi...

Java Syntax Error -

what wrong code? have error concerning scanner part of it. have add "more details be4 can post question, it. import java.util.scanner class rectangle { double width; double length; double findarea(double a, double b) { width=a; length=b; return a*b; } } public class area { public static void main(string args[]) { { system.out.println("enter dimensions of square."); scanner x = new scanner(system.in); scanner y = new scanner(system.in); } { rectangle objrect = new rectangle(); system.out.println(objrect.findarea(x, y)); } } } you passing 2 scanner objects method findarea expects 2 double values; won't work. should have 1 scanner object, should able obtain double values can pass in findarea method.

osx - Why is Xcode's Search Navigator pulling searches from Safari? -

i have safari open while working on project in xcode, looking stuff on stack overflow , like. few times, i've searched in web address/search engine field of safari, , word or 2 typed in , entered search navigator in xcode, though didn't type in there. doesn't every time. edit: text entered in through search navigator can pop in safari too. this doesn't cause problems, words picks don't seem have relevance, , i'm curious why oddity happening. i'm running xcode 4.6.3, safari 6.0.3, , mac os x 10.8.4 is glitch? half-baked feature? what seeing os x global find pasteboard in action. anywhere private class nsfindpanel invoked (typically in conjunction text field) global pasteboard invoked , provides single, central location 'find' metadata includes recent query: in addition communicating search strings via find pasteboard, standard find panel nstextview communicates search option metadata, including case sensitivity , substring m...

Nginx + FastCGI + PHP (php-fpm) not logging caught errors/warnings -

fastcgi doesn't want log php errors properly. well, that's not entirely true: logs errors fine, little fiddling; won't log else, such warnings. the notorious fastcgi -> nginx log bug isn't issue, necessarily. errors , warnings php-fpm go straight nginx--but if they're uncaught. is, if set_error_handler intercepts error, no log entry appended. means can see parse errors, that's it. php-fpm doesn't log php errors (separate nginx) without bit of hack. php-fpm's instance configuration file includes these 2 lines default: php_admin_value[error_log] = /mnt/log/php-fpm/default.log php_admin_flag[log_errors] = on i changed error_log path, obviously. had add following line log anything: php_admin_value[error_reporting] = e_all & ~e_deprecated & ~e_strict version note: e_strict part unnecessary, i'm using php 5.3.27, plan on upgrading 5.4 @ point. line, logs errors--and errors--to /mnt/log/php-fpm/default.log . now, sets err...

c - How to compile this program with inline asm? -

i cannot compile program taken tutorial. should print "hello world". void main() { __asm__("jmp forward\n\t" "backward:\n\t" "popl %esi\n\t" "movl $4, %eax\n\t" "movl $2, %ebx\n\t" "movl %esi, %ecx\n\t" "movl $12, %edx\n\t" "int $0x80\n\t" "int3\n\t" "forward:\n\t" "call backward\n\t" ".string \"hello world\\n\"" ); } gcc 4.7 under linux gives me following error: gcc hello.c -o hello hello.c: assembler messages: hello.c:5: error: invalid instruction suffix `pop' is there way avoid specify double quotes each line? also, i'd know how modify program use libc call printf instead of kernel service. q : hello.c: assembler messages: hello.c:5: error: invalid instruction suf...

c++ - Value Type from Arbitrary Iterator in Template Function -

i trying retrieve value type iterator parameter. how that? googled , see iterator_trait features, couldn't figure out how implement on function. iterator templated t can take either integers or float numbers, , on following function trying iterate through container of either integers or float numbers, , store them, depending on value type, new vector container. to summarize, how value type information arbitrary iterator template<typename t> void merge_function(t begin, t mid, t end) { vector<auto> left_half (begin, mid); left_half.push_back(infinite); vector<auto> right_half (mid+1, end); right_half.push_back(infinite); } update: trying sort of in-place merge sort. vector<int> numbers = {5, 6, 3, 4, 1, 2, 7, 13, -6, 0, 3, 1, -2}; vector<int> l_half(numbers.begin(), numbers.end()); this works, try similar thing on following template<typename t> void practice(t begin, t end) { auto length = end - begin; auto ...

r - How to get the order number of same record if the object is data.frame? -

if object vector, can order of same record following method: > serial <- c("df12", "cv22", "ca11", "he22", "jj32", "sq11", "cv22") > which(serial%in%serial[duplicated(serial)]) [1] 2 7 what can if object data.frame? which(iris%in%iris[duplicated(iris)]) error in `[.data.frame`(iris, duplicated(iris)) : undefined columns selected > which(duplicated(iris)) [1] 143 > iris[143,] sepal.length sepal.width petal.length petal.width species 143 5.8 2.7 5.1 1.9 virginica > iris[which(iris[,1]==5.8),] sepal.length sepal.width petal.length petal.width species 15 5.8 4.0 1.2 0.2 setosa 68 5.8 2.7 4.1 1.0 versicolor 83 5.8 2.7 3.9 1.2 versicolor 93 5.8 2.6 4.0 1.2 versicolor 102 5.8 2.7 5.1 1.9 virginica 115 5.8 2.8 5.1 2.4 virginica 143 5.8 2.7 5.1 1.9 virginica the order of same record 102 , 143,how can line of r command? duplicated has fromlast argument, ...

php - Multiple dropdown values inserting in a single row not in multiple row -

in code when selected multiple values dropdown stoing in single row apply value in each row please me. actual result: id game 1. cricket,football,tennis expecting result: id game 1 cricket 2 football code - <html> <body> <?php if(isset($_post['submit'])) { $query=mysql_connect('localhost','root',''); mysql_select_db("freeze",$query); $choice=$_post['game']; $choice1=implode(',',$choice); mysql_query("insert tb values('','$choice1')"); } ?> <form method="post" action="multipleselect.php"> select favourite game:<br/...

java - Controlling JComponents from other classes -

is possible control instances variables, jcomponents, timer in other external classes? for example class1 public class class1 extends jframe { jlabel lbl = new jlabel("hello"); public class1() { super("class1"); container c = getcontentpane(); setlayout(null); c.add(lbl); lbl.setbounds(0,0,100,20); class2.process(); setsize(200,100); setlocationrelativeto(null); setvisible(true); } public static void main(string var[]) { new class1(); } } you can see there's class2.process(); here's other class externally in same folder public class class2 { public static void process() { // want control lbl class1 class inside method // lbl.setvisible(false); } public static void main(string args[]) { // } } is possible? sorry. can't find answers on other website. you have pass instance of jlabel e.g.; jlabe...

ajax - Short cut way of collecting form input values using javascript -

i have form collects information user. form composed of 10 input text field. individual value of input text field accessed via var first_name = $("#fname").val() example , passed var postdata = {'fname':first_name}; , passed ajax url: "<?php echo base_url(); ?>main_controller/save_data", data: postdata controller function again collect it. if have 30 input text field , used way, take me lot of time. best way pass numerous input field values using javascript in miniature way? there shortcut this? lot. have sample code below. views: <input class="input input-large" type="text" name="fname" id="fname" value=""/> <input class="input input-large" type="text" name="lname" id="lname" value=""/> <input class="input input-large" type="text" name="address" id="address" value=""/> <in...

How to read Xml file(which is used as data base ) using javascript or jquery or ajax call.? -

i saw 1 project in 1 developer save 1 xml(as database) file having data .and call database (xml file) using jquery or ajax , used data in project .i want learn thing .he placed file on project.he call database , fetch data database.can please give me example in jquery how fetch data?he making mobile app using jquery , phonegap . thanks $.get('/some/path/file.xml', function (data) { var xmldoc = $(data); // traversing: var somechildnodes = xmldoc.find('section > article'); }

c# - Open new database connection in scope of TransactionScope without enlisting in the transaction -

is possible open new sqlconnection inside transactionscope, without referencing other connection in transaction? inside transaction, need run command should not take part in transaction. void test() { using (var t = new transactionscope()) using (var c = new sqlconnection(constring)) { c.open(); try { using (var s = new sqlcommand("update table set column1 = 1"); { s.executescalar(); // if fails } t.complete(); } catch (exception ex) { saveerrortodb(ex); // don't want run in same transaction } } } // don't want involved in transaction, because generate // distributed transaction, don't want. want error go // db not caring run inside transactionscope of previous function. void saveerrortodb(exception ex) { using (var db = new sqlconnection(constring)) { db.open(); using (var cm...

c# - %APPDATA% in connection string is not substituted for the actual folder? -

when using wpf , entity-framework have app.config looks following: <?xml version="1.0" encoding="utf-8"?> <configuration> <connectionstrings> <add name="databaseentities" connectionstring="metadata=res://*/model.csdl|res://*/model.ssdl|res://*/model.msl;provider=system.data.sqlserverce.4.0;provider connection string=&quot;data source=%appdata%\folder\database.sdf&quot;" providername="system.data.entityclient" /> </connectionstrings> </configuration> when using code throws following error: system.data.entityexception: underlying provider failed on open. ---> system.data.sqlserverce.sqlceexception: path not valid. check directory database. [ path = %appdata%\folder\database.sdf ] when run path "%appdata%\folder\database.sdf" command prompt works fine, , if remove "%appdata% , hardcode path works fine - looks %appdata% not being substituted actual folder... ...

Jquery filter list without case sensitive -

i want filter list without case sensitive. want match character not match upper case or lower case. xxxxxxx yyyyyyy xxxxx if enter "x" in search box displays both 1 , 3. added code below match case sensitive also. <!doctype html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script> <script> function filter(element) { var value = $(element).val(); $("#thelist > li").each(function() { if ($(this).text().search(value) > -1) { $(this).show(); } else { $(this).hide(); } }); } </script> </head> <body> <input type="text" onkeyup="filter(this)" /> <ul id="thelist"> <li>xxvxvxx</li> <li>yyyyyyyyyy</li> <li>rrrrrrrrrr</li> <li>vvvvvvvv...

macvim - Can vim command history store commands that produce an error? -

i'm new vim (for seventh time) may not makes sense vim style but: command history in command window has up-arrow mapped history , has been helpful in learning, except not seem store commands fail execute in history. obviously, bad configuration choice trying learn mistakes. there way force remember failed commands, in sense can recalled up-arrow? fyi, using macvim janus extensions. what kind of error talking about? :s/foo/bar recorded history, if there no foo on current line , e486. as side note, if use ex commands lot might interested in command line window, invoked q: , can navigate , edit other window. it's great. also, drop janus possible! pile of crap absolute worth thing install when learning vim. seriously.

jquery - jQgrid's gridComplete event is firing but loadComplete is not firing..... why? -

in asp.net project integrating jqgrid show data. problem loadcomplete event not firing. entire jqgrid code follows: function getdata(jqgridparams) { var sortcookieval = $.cookie("itemgridsortinfo"); var sname = ""; var sorder = ""; if (sortcookieval != null) { var sortinfo = sortinfofromcookie("itemgridsortinfo"); sname = sortinfo.sortname; sorder = sortinfo.sortorder; } else { sname = ""; sorder = "asc"; } var params = new object(); params.pageindex = jqgridparams.page; params.pagesize = jqgridparams.rows; params.sortindex = sname; //jqgridparams.sidx; params.sortdirection = sorder; //jqgridparams.sord; params._search = jqgridparams._search; if (jqgridparams.filters === undefined) params.filters = null; el...

php - Counting rows with conditions? -

before has been answered before, have tried everything, literally. i trying count number of rows in mysqli query 2 clauses. if (isset($_post['member_name']) , isset($_post['memeber_password'])) { $member_name_input = mysqli_real_escape_string($query, $_post['member_name']); $member_password_input = mysqli_real_escape_string($query, $_post['member_password']); $result = mysqli_query($query, "select count(*) member_count `members` `member_name` = '$member_name_input' , `member_password` = '$member_password_input'") or die(mysqli_error($query)); $counter = $row['member_count']; if ($counter = 1) { $result = mysqli_query($query, "select * `members` `member_name`='$member_name_input' , `member_password`='$member_password_input'") or die(mysqli_error($query)); $row = mysqli_fetch_array($result); $member_suspended = $row['member_suspended'];...

sortedset - Redis: storing intermediate set results, use random names or wrap in transaction? -

i'm having result based on intersection of multiple unions of (sorted) sets. e.g. intersect(union(a,b), union(c,d), e) the obvious way of doing storing union(a,b) , union(c,d) in temporary sets , using in final intersection command. but obviously, temporary sets need name , despite redis being single-threaded, if use fixed names it, i'll run concurrency problems. my solution has been entire 'query' in multi/exec-block (create temporary sets, intersection, fetch results, delete temporary keys). the obvious alternative not use multi/exec use sufficiently random names temporary sets. my question is: preferable/best practice? the former comes performance (/availability other threads) penalty latter adds complexity , isn't guaranteed not cause concurrency problems. haven't looked doing in lua, i'm assuming that'll make more complex.

android - Why it won't detect onTouch? -

my actionbar called pressing "menu button" this. , it's working fine @override public boolean onkeydown(int keycode, keyevent event) { if(keycode == keyevent.keycode_menu){ if (mactionbar.isshowing()) { mactionbar.hide(); } else { mactionbar.show(); } }else if(keycode == keyevent.keycode_back){ webview mywebview = (webview)findviewbyid(r.id.webview1); mywebview.goback(); } return true; } when user touches screen while actionbar shown, actionbar should disappear. won't detect ontouch event. why? public boolean ontouch(view view, motionevent event) { switch(event.getaction() & motionevent.action_mask) { case motionevent.action_down: if (mactionbar.isshowing()) { mactionbar.hide(); } case motionevent.action_up: break; case motionevent.action_pointer_up: break; } return true; } update: view.ontouchlistener mdel...

javascript - Quickest way to check if a number is in a set? -

what fastest method check if number in list in javascript? i know indexof >= seems rather slow me. i have perform millions of checks per second , list rather short (max ~10 entries) try out @ jsperf suspect using object , setting numbers properties faster array search. var thelist = { 1: true, 2000: true, 253: true, -12077: true, ... }; if (thelist[ somenumber ]) { // see if number in list now, said, you're not going able useful in javascript in web browser millions of times per second, except perhaps on extremely high-end machines aren't doing else.

twitter bootstrap - jQuery - show one by one, classes step1, step2, step3 -

this question related bootstrap carousel. i want show items 1 one inside carousel item. like: <div class="carousel-inner"> <div class="active item"> <div class="step3">..</div> <div class="step1">..</div> <div class="step2">..</div> </div> <div class="item">…</div> <div class="item">…</div> </div> when carousel item active show step1 then step2 then step3 step4. .. . ... . i know insert code in bootstrap carousel plugin, don't know how start: here code can write code need (about line 125): if ($.support.transition && this.$element.hasclass('slide')) { this.$element.trigger(e) if (e.isdefaultprevented()) return $next.addclass(type) $next[0].offsetwidth // force reflow $active.addclass(direction) $next.addclass(direction) this.$...

php - Insert into table with prepared statement -

i'm trying insert data form database using php , mysqli can't working! database has 4 fields: date, title, content, id. id field auto-increment. i've checked connection , that's working fine. i've echoed form field values , $blogdate variable created, they're fine too. here's prepared statement: if ($newblog = $mysqli->prepare('insert blog values ($blogdate, $_post["btitle"], $_post["bcontent"])')) { $newblog->execute(); $newblog->close(); } it's not inserting values table. you generating sql containing strings not quoted or escaped. don't insert data directly sql string, use placeholders ( ? ) , bind parameters before executing. $query = "insert blog values (?, ?, ?)"; $stmt = $mysqli->prepare($query); $stmt->bind_param("sss", $blogdate, $_post["btitle"], $_post["bcontent"]); $stmt->execute();

java - jdbc Error, unable to connect to sql -

i want use database in project, use code test( jdbc tutorialspoint ) , change code , db error: creating statement... have error in sql syntax; check manual corresponds mysql server version right syntax use near 'from test set name=eee id=1' @ line 1 error: unable connect sql! java.sql.sqlexception: have error in sql syntax; check manual corresponds mysql server version right syntax use near 'from test set name=eee id=1' @ line 1 @ com.mysql.jdbc.mysqlio.checkerrorpacket(mysqlio.java:2975) @ com.mysql.jdbc.mysqlio.sendcommand(mysqlio.java:1600) @ com.mysql.jdbc.mysqlio.sqlquerydirect(mysqlio.java:1695) @ com.mysql.jdbc.connection.execsql(connection.java:3020) @ com.mysql.jdbc.connection.execsql(connection.java:2949) @ com.mysql.jdbc.statement.execute(statement.java:538) @ test.main(test.java:49) my code: import java.sql.*; import java.math.*; public class test { final static string db_url = "jdbc:mysql://localhost/testdb...

php - Using PDO with other classes -

i have been forcing myself more oop. have hated in till now. when using simple prepare statment in pdo within class method never works. resolved doing obvious: globalising pdo object method. works, , want - if had many many methods loads of different classes, adding "global $db;" first line alllll functions/methods seems quite tedious. there way of integrating pdo classes? or @ least each class- instead of every single bloody method? heres very simple example of what curretnly works, said tedious: <?php $db = new pdo("mysql:host=localhost;dbname=blaa;", "blaa", "blaa"); class test{ function show($col, $id){ global $db; $result = $db->prepare("select ".$col." products id = :id"); $result->execute(array("id"=>$id)); $row = $result->fetch(); echo $row[$col]; } } $show = new test(); $show->show("price", 1); ?> ..so can use pdo in method "show()" if...

iphone - Custom NavigationItem's TouchUpInside Event is outside boundaries -

i'm using custom uibarbuttonitem replace leftbarbuttonitem, when press outside of button, within around 20 pixels of button, detects button being pressed. here's code: - (void)changenavbarbuttons { uibutton *backbutton = [[uibutton alloc] initwithframe:cgrectmake(0, 0, 44, 44)]; [backbutton setbackgroundimage:[uiimage imagenamed:@"navbarback.png"] forstate:uicontrolstatenormal]; [backbutton addtarget:self action:@selector(popviewcontroller) forcontrolevents:uicontroleventtouchupinside]; uibarbuttonitem *backitem = [[uibarbuttonitem alloc] initwithcustomview:backbutton]; uibarbuttonitem *negativespacer = [[uibarbuttonitem alloc] initwithbarbuttonsystemitem:uibarbuttonsystemitemfixedspace target:nil action:nil]; negativespacer.width = -5; self.navigationitem.leftbarbuttonitems = [nsarray arraywithobjects:negat...

linux - when parent process is killed by 'kill -9', how to terminate child processes -

this question has answer here: are child processes created fork() automatically killed when parent killed? 1 answer kill -9 send sigkill signal parent process. sigkill can not caught. how parent process terminate child processes? the parent, once killed via sigkill, stop existing , cannot send signals child processes more. child process have monitor parent process itself. when parent gets killed, ppid changes 1 - might helpful client act on parent being killed. "ensure child process closed parent process" not possible parents process - that's nature of sigkill. however, if feel brave can hack source , redefine sigkill else, wouldn't recommend :)

web crawler - Scrapy/Python Issue: [count] does not collect entire table -

this spin off of previous xpath thread (dude told me it's not xpath related). so trying scrape web page: http://www.baseball-reference.com/teams/bos/2013.shtml rank, position, name, age, etc. whenever use: item['rank'] = stat.select('//table[@id="team_batting"]/tbody/tr/td[1]//text()')[count].extract() item ['position'] = stat.select('//table[@id="team_batting"]/tbody/tr/td[2]//text()')[count].extract() it gives me 5 results: [{"position": "c", "rank": "1"}, {"position": "1b", "rank": "2"}, {"position": "2b", "rank": "3"}, {"position": "ss", "rank": "4"}, {"position": "3b", "rank": "5"}] if remove [count], gives me of ranks , positions, not in correct format, , gives me 4 duplicate lines of (i condensed fit in here,th...

bash - Recursively finding with AWK -

i've got file looks this: $cat myfile.dat number of reps: nrep= 19230 flop count: nops= 4725964800. clock resolution 4.7619047619047619e-4 , usecs time = 7.18247611075639725e-6 calc 0: time= 2.902 gflop/s= 1.629 error= 0.00000000 calc 201: time= 1.186 gflop/s= 3.985 error= 0.00000000 number of reps: nrep= 13456 flop count: nops= 4234564800. clock resolution 3.7619047619047619e-4 , usecs time = 7.18247611075639725e-6 calc 0: time= 1.232 gflop/s= 2.456 error= 0.00000000 calc 201: time= 3.186 gflop/s= 1.345 error= 0.00000000 i interested filter need : nrep , time , gflop/s last 2 of line starting calc 201 . so far i've managed filter want, except elements time , gflop/s . i've done: awk -f'= ?' '/nrep=/||/time=/||/gflop/{print $2}' myfile.dat 19230 2.902 gflop/s 1.186 gflop/s 13456 1.232 gflop/s 3.186 gflop/s this obviosly wrong. need...

how to host website in azure and email in google apps -

is possible host website in widows azure using custom domain (e.g mydomain.com) , have same domain used in google apps mail server? (e.g mail.mydomain.com)? thanks amit yes - through dns registrar, point cname records azure , mx records google. read understand mx records google mail setup , create cname records .

java - Retrieving Shibboleth attributes from AJP connector request -

i have encountered weird problem when working shibboleth authentication running on apache , when tomcat7 running on end, apache sends through mod_proxy_ajp. , parameters sibboleth. in documentation ( https://wiki.shibboleth.net/confluence/display/shib2/nativespjavainstall ) explicitly stated ajp sends attributes prefix attributeprefix="ajp_" , developer should not take shortcuts , enable sending auth attributes trough http headers ( https://wiki.shibboleth.net/confluence/display/shib2/nativespspoofchecking ) i try retrieve attributes using httpservletrequest req = (httpservletrequest) facescontext.getcurrentinstance() .getexternalcontext().getrequest(); enumeration<string> e = req.getattributenames(); but no matter try, no shibboleth attributes ever show up. after 2 hours of trying find out doing wrong. tried retrieve attribute name using. req.getattribute("uid"); and reason works. though "uid" is...

python - Place a timeout on calls to an unresponsive Flask route (updated) -

i have route in flask app pulls data external server , pushes results front end. external server slow or unresponsive. what's best way place timeout on route call, front end doesn't hang if external server lagging? or there more appropriate way handle situation in flask (not apache, nginx, etc)? my goal timeout route call, not keep arbitrary long process alive question: time out issues chrome , flask . options websockets run background processes/threads until finish; however, want stop slow route call after fixed amount of time has elapsed. timeout on function call , python timeout within flask context. celery's task decorator ( concurrent asynchronous processes python, flask , celery ) seems great solution, don't want require large dependency use small amount of functionality. not entirely sure if i'm right this, understanding if thread (or greenthread) handling request network call in it's own "foreground", , call times out, borken ...

ios - Phonegap 3.0 app with facebook login using xCode -

i trying build phonegap app facebook login. using phonegap 3.0, developing xcode ios. i followed steps on https://github.com/phonegap/phonegap-facebook-plugin after start app in simulator, keep getting following error in output: error: plugin 'org.apache.cordova.facebook.connect' not found, or not cdvplugin. check plugin mapping in config.xml. my config.xml: <feature name="notification"> <param name="ios-package" value="cdvnotification" /> </feature> <feature name="org.apache.cordova.facebook.connect"> <param name="org.apache.cordova.facebook.connect" value="facebookconnectplugin" /> </feature> can please me this? in advance! earlier had same problem, got running on phonegap 3.0 through combination of below things. need use facebook sdk 3.2. i found few branches of plugin have wrong 'cdv-plugin-fb-connect.js' file . need find branc...

java - Insert image into borderpane as background -

i want load image borderpane. have static java method makes task more complicated me: private static final image iv; static { iv = new image(startpanel.class.getclass().getresource("/images/system-help.png").toexternalform()); } public static void insert(){ bp.setcenter(iv); } can tell me how can load image properly? p.s executing com.javafx.main.main /home/rcbandit/desktop/test/dx-57dc/dist/run1833589211/dx-57dc.jar using platform /opt/jdk1.7.0_25/bin/java exception in application start method java.lang.reflect.invocationtargetexception @ sun.reflect.nativemethodaccessorimpl.invoke0(native method) @ sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:57) @ sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43) @ java.lang.reflect.method.invoke(method.java:606) @ com.javafx.main.main.launchapp(main.java:642) @ com.javafx.main.main.main(main.java:805) caused by: ...