Posts

Showing posts from April, 2015

sails.js - How do I add properties to a js-data object that I don't want persisted? -

i'm using js-data (and js-data-angular) in conjunction sockets via sails.js. when new item created/updated via sockets want call attention in ui. i'd add "updated" property object, don't want inadvertently persist db. is there way hang non-persisting properties on js-data object? yes. you can set globally on data store or per-resource using omit configuration setting. instance, when instancing data store, can instruct jsdata ignore properties begin underscore: var store = new jsdata.ds({ omit: [ /^_/ ] });

VBA Excel: How to pass one parameter of different types to a function (or cast Int/String to Range)? -

i'm writing vba functions in excel compute word values , cross sums of input. i'm passing input public function cross_sum(myrange range) integer them take cell references input, e.g. =cross_sum(a1) . works fine. however when try chain 2 functions =cross_sum(word_value(a1)) run th value error because word_value() returns integer value , not range cross_sum() set expect. did not find way cast integer (or string) range. as excel's built-in functions support chaining range input wonder how. unfortunately first vba project wonder if , how cast or type choose working both ways. any pointers appreciated! tia, jbq you can pass variant function , function can determine type of input: public function inputs(v variant) string if typename(v) = "range" msgbox "you gave me range" else msgbox "you gave me string" end if inputs = "done" end function sub main() dim st string dim

Sorting the array with Custom Key in PHP -

i have array of 1 structure below $array1 = array( [123] => array('1'=>'1','2'=>'3'), [345] => array('1'=>'3','2'=>'5'), [789] => array('1'=>'1','2'=>'5'), [567] => array('1'=>'6','2'=>'5'), ); and array structure $array2 = array(567,345,789,123); now want sort 1 php sort function, mean sort first array second 1 looks desired output below $array1 = array( [567] => array('1'=>'6','2'=>'5'), [345] => array('1'=>'3','2'=>'5'), [789] => array('1'=>'1','2'=>'5'), [123] => array('1'=>'1','2'=>'3'), ); i want these desired result sorting function exists. thanks. loop $array2 , populate third array follows: $array1 = array( [123] => arra

java - Speeding up sql inserts on postgresql with JDBC? -

i have 2 methods below checking if match in database , if not if call insert method. program has go through thousands of rows , takes long time. doing incorrectly? can make faster? public boolean ismatchidindatabase(string matchid) throws sqlexception { connection conn = null; preparedstatement pst = null; resultset rs = null; boolean exists = false; try { class.forname("org.postgresql.driver"); conn = drivermanager.getconnection(url, props); pst = conn.preparestatement("select count(*) match match_id = ?"); pst.setstring(1, matchid); rs = pst.executequery(); while (rs.next()) { exists = rs.getboolean(1); } } catch (exception e) { e.printstacktrace(); } { pst.close(); rs.close(); conn.close(); } return exists; } public boolean insertmatchid(string matchid, string name, timestamp birthdate, stri

javascript - JS/jQuery passing $_POST information to PHP script -

it might simple thing, spent way time unsuccessfuly trying make work. basically have following bootstrap buttons: <div class="bs-example"> <div class="btn-group" data-toggle="buttons"> <label title="this display" class="btn btn-lg btn-info"> <input type="radio" name="todo" id="todo" value="enablessh"> enable ssh </label> <label class="btn btn-lg btn-info"> <input type="radio" name="todo" id="todo" value="migratedb"> migrate database </label> </div> i have following button lower in page need use above selected value: <button id="submit" class="btn btn-default" type="button">go!</button> when button clicked, triggers following jquery function: $("#submit").click(function(){ var buttonv

Why does the Lua interactive interpreter stop letting me type things in? -

i writing program find standard deviation of data set. don't have proper lua editor testing interactive interpreter. in code below, seems work until diffsqrd function. after call function, interpreter stops letting me type in. have close , start on again. have tested function itself, without code before , works fine. i tried saving whole thing .lua file , running dofile did same thing. nothing, , can no longer type interpreter. going on? --a function see if file exists function file_exists(file) local f=io.open(file, "r") if f f:close() end return f ~= nil end --get lines file, returns empty --list/table if file not exist function lines_from(file) if not file_exists(file) return {} end lines = {} line in io.lines(file) lines[#lines + 1] = line end return lines end --put .rec file array y_positions=lines_from([[z:\octupole stuff\programming\y_p_test.rec]]) --functions find standard deviation of array. --total, ave

apache - Wamp server online but connection timed out to localhost -

Image
i access localhost , phpmyadmin. i've installed wampserver so. wampserver installed , when open goes green. that takes time , have go apache -> service -> instal service go orange green works. but till can't access local host. when accessing http://localhost/ or http://localhost/phpmyadmin or when pressing localhost @ wampserver menu, "this webpage not available, err_connection_timed_out". i have been working days on fix no use. know lot of people had same problem here , asked many questions non of solutions written did help. did have iis using port 80 , made port empty. had skype using , fixed it. now when test port 80 on wamp server gives me your port 80 not used. . my wamp icon green, internet on, firewall , antivirus turned off. i'm using windows 7, wamp server 2.5 64. here http.confd file: # # main apache http server configuration file. contains # configuration directives give server instructions. # see <url:http://httpd.apache

Join python iterators on key -

i'm looking way join python iterators itertools.izip_longest() does, join elements have same "key" (as defined parameter) , output none when key not exist on iterators. i'm assuming iterators sorted ascending "key". example: iter1 = iter((1, 3, 4, 9)) iter2 = iter((3, 5, 6)) iter3 = iter((1, 3, 10)) zipjoiner(iter1, iter2, iter3) should give: iter(((1, none, 1), (3, 3, 3), (4, none, none), (none, 5, none), (none, 6, none), (9, none, none), (none, none, 10))) (in case key default identity lambda x: x ) i've tried modify izip_longest() implementation found in python documentation , works (at least on example), i'm looking more elegant solution. idea? this code: def zipjoiner(*args, **kwds): # izip_longest('abcd', 'xy', fillvalue='-') --> ax c- d- fillvalue = kwds.get('fillvalue') key = kwds.get('key', lambda x: x) counter = [len(args) - 1] def sentinel(): i

c++ - Troubles on training Haar cascade with LBP -

Image
i'm trying train branch logos haar_cascade. i've done is, i've taken 2500 squared pictures of 500 x 500 populate samples opencv_createsamples . generate them as: opencv_createsamples -info 'logo.info' -vec '../logo.vec' -bg '../negatives/bg.txt' -w 24 -h 24 -num 2500 in logo.info i've got lines correspond relative path of every picture, 1 0 0 500 500 meaning "there's 1 object between (0,0) , (500, 500)" then train cascade as: opencv_traincascade -data 'cascade/' -vec '../logo.vec' -bg '../negatives/bg.txt' -numpos 2500 -numneg 3019 -numstages 25 -featuretype lbp -w 24 -h 24 with these parameters: parameters: cascadedirname: cascade/ vecfilename: ../logo.vec bgfilename: ../negatives/bg.txt numpos: 2500 numneg: 3019 numstages: 25 precalcvalbufsize[mb] : 256 precalcidxbufsize[mb] : 256 stagetype: boost featuretype: lbp

c# - Add custom image or text to QR code generated by ZXing.Net -

Image
i use zxing.net library generate qr code image - at top of class: [system.runtime.interopservices.dllimport("gdi32.dll")] public static extern bool deleteobject(intptr hobject); my method: protected void updateqrsource(string address) { qrcodewriter qrcode = new qrcodewriter(); barcodewriter barcodewriter = new barcodewriter { format = barcodeformat.qr_code, options = new encodingoptions { width = 300, height = 300, margin = 4 } }; using (bitmap bitmap = barcodewriter.write(address)) { intptr hbmp = bitmap.gethbitmap(); try { bitmapsource source = imaging.createbitmapsourcefromhbitmap( hbmp, intptr.zero, int32rect.empty, bitmapsizeoptions.fromemptyoptions());

php - Laravel-5 using fill() to update database -

i'm trying use fill() update current row in database. however, seems creating new row instead of updating each time. does know wrong? here's code: $reserve->where('cookie_id', 'idcode')->first(); $reserve->fill($request->all())->save(); return redirect::to('checkout'); judging code you've misunderstood how fetch instance out database. see http://laravel.com/docs/5.1/eloquent#retrieving-single-models try following $reserve = reserve::where('cookie_id', $id)->first(); $reserve->fill($request->input())->save(); return redirect()->to('checkout');

Error with l2 normalization on a vector [Java] -

i'm trying use l2 normalization on double vector java. double[] vector = {0.00423823948, 0.00000000000823285934, 0.0000342523505342, 0.000040240234023423, 0, 0}; now if use l2 normalization for(double : vector){ squarevectorsum += * i; } normalizationfactor = math.sqrt(squarevectorsum); // system.out.println(squarevectorsum+" "+normalizationfactor); for(int = 0; < vector.length; i++){ double normalizedfeature = vector[i] / normalizationfactor; vector_result[i] = normalizedfeature; } my normalized vector this normalized vector (l2 normalization) 0.9999222784309146 1.9423676996312713e-9 0.008081112110203743 0.009493825603572155 0.0 0.0 now if if make squared sum of normalized-vector components should sum is equal one, instead squared sum for(double : vector_result){ sum += i*i; } squared sum of normalized-vector 1.0000000000000004 why sum not equal one? there problems in code? or it's because numbers small , there approximation d

javascript - Capture Link from onClick Event -

our contact page under support directory want test if contact-us in url , 1 thing if not else. "this" not valid - how full value of link under execution, e.g., "www.example.com/support/cars.html" or "www.example.com/support/contact-us.html" jquery('a[href*="www.example.com/support"]').click(function(event){ event.preventdefault(); if (this.indexof("contact-us") > -1) { alert('contact us'); } else { alert('support'); } }); thanks use href attr. can using attr() jquery('a[href*="www.example.com/support"]').click(function(event) { event.preventdefault(); if (jquery(this).attr('href').indexof("contact-us") > -1) { alert('contact us'); } else { alert('support'); } });

vb.net - Why is my Nullable(Of Int32) = 0 after I set it to Nothing? -

i think i'm missing fundamental nullable types. example open new understanding, @ least, maybe can 1 thing working right. in class (a dialog form), declare: property productstructureheaderkey int32? in class, declare instance of dialog , attempt set property line: dr.productstructureheaderkey = if(parentrow.cells(1).value nothing, nothing, int32.parse(parentrow.cells(1).value)) when line assigns nothing property, property equal 0. (and later, it's passing 0 db when want passing null.) that's not expect , keep finding code (so, msdn, etc) looks i'm doing things right, clearly, i'm not. so, friends, doing wrong? how employ nullable types meet needs? that's 1 of differences between c# , vb.net. in vb.net nothing not mean null default . assigning default value of int32 property 0. caused if -operator has infer type 2 values not property want assign. instead use either if...else : if parentrow.cells(1).value nothing dr.product

c# - Twitter OAuth request_token stopped working -

out of no where, twitter api calls, specificly first step in 3-legged auth, stopped working. i've compared timestamps, keys , oauth signature generator tool, , match (execpt oauth_nonce thats point guess). here code. suggestions or small observations appreciated. protected void requesttoken() { string oauthcallback = request.url.host + "/twittercallback.aspx"; string oauthconsumerkey = "xxx-consumerkey"; string oauthconsumersecret = "xxx-consumersecret"; string oauthtokensecret = string.empty; string oauthtoken = string.empty; string oauthsignaturemethod = "hmac-sha1"; string oauthversion = "1.0"; string oauthnonce = convert.tobase64string(new asciiencoding().getbytes(datetime.now.ticks.tostring())); timespan timespan = datetime.utcnow - new datetime(1970, 1, 1, 0, 0, 0, 0, datetimekind.utc); string oauthtimestamp = convert.toint64(timespan.totals

Can I mark an issue as "false-positive" from a sonarqube plugin? -

just can auto-assignment issues sonarqube plugin using api of issuehandler , issue.context.assign(user), can mark issue false-positive plugin? yes, possible. but: with changes being done next 5.2 version, won't possible more. so if have use case think valid, please feel free come , discuss on sonarqube google group !

android edittext with drop down list -

Image
i have edittext gets values user. want add option allows user choose different options via drop down list when edittext clicked. have idea how this? this edittext code: <edittext android:layout_width="match_parent" android:layout_height="wrap_content" android:inputtype="textpersonname" android:ems="10" android:id="@+id/dish_quantity" android:layout_below="@+id/dish_name" android:layout_alignparentright="true" android:layout_alignparentend="true" android:hint="quantity" /> i want this: i think requirement: just follow example: xml:- <?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" >

Python 2.5 - Update folder of text files from values stored in a lookup list -

i trying write script update folder of text files based on lookup table. lookup table filename, oldpath, new path. script looks in each text file filename, if there updates oldpath in same line new path. code is: # import array import * import glob # specify lookup table, keep simple drop in workspaces lookup = "./lookup.csv" # specify workspaces = glob.glob('./*.wor') # open lookup table line in open(lookup).readlines(): # create list store lookup parameters of lookup line lookuplist = [] # split lookup csv @ comma in line.split(","): #print lookuplist.append(i) # use list parameters populate variables (could use list parameters # easier assign variable) filename = lookuplist[0] oldpath = lookuplist[1] newpath = lookuplist[2] # have variables use in replace statement # use workspaces glob loop through workspaces wor in workspaces: # try open the first workspace (text file) f = open(wor, 'r+') # lo

mongodb - Mongo DB Authentication 3.0.4 -

i having issue mongo db 3.0.4 randomly started happening today. authentication stopped working randomly without user action on our part. our setup easy. 1 application, 1 database. take application out of equation , still same result. here steps taking. reinstalled mongo , pointed logpath , dbpath new folder start scratch. create config file. logpath=c:\data\logs\mongod.log dbpath=c:\data\db log in mongo shell , run command. db.createuser({user: "admin",pwd: "admin", roles: [ { role: "useradminanydatabase", db: "admin" }]}) add auth=true in config file. auth=true restart mongodb service. start mongo shell mongo -u admin -p admin --authenticationdatabase admin then error 18 authentication failed. i lost words. appreciated. thanks i think user doesn't have efficient privileges. try role. use admin {user:"admin",pwd:"admin",roles:["root"]}

Formatting Dates in R -

i having issue formatting dates in dataset yyyymmdd , convert them dd/mm/yyyy . i have tried lubridate library not luck in converting it. thanks, droy what have tried do? indeed reader see what's causing issue, rather guessing it. nonetheless, think should work: new_format <- paste(substr("20150625",7,8),substr("20150625",5,6),substr("20150625",1,4), sep="/") note anyway class of object created above code not date: class(new_format) [1] "character"

c# - Gecko/Firefox 38 not being recognized as FF on whatsappweb -

im trying create simple app has 1 form on load goes web.whatsapp.com using geckofx 38 ( https://bitbucket.org/dherken/geckofx-38.0 ) , xulrunner 38.0 , browser picked on www.whatsmybrowser.org firefox 38 see here: http://imgur.com/5v5oh6g.png still whatsapp web doesnt see it, see here: http://i.imgur.com/vyc4oec.png i got snippet geckofx dev forked geckofx 38 me debugging in c# not know. converted vb.net using tool still not sure how incorporate app. c# code: geckopreferences.user["general.useragent.override"] = "mozilla/5.0 (windows nt " + environment.osversion.version.major + "." + environment.osversion.version.minor + "; rv:38.0) gecko/20100101 firefox/38.0"; geckopreferences.user["extensions.blocklist.enabled"] = false; geckopreferences.user["media.navigator.enabled"] = true; geckopreferences.user["media.navigator.permission.disabled"] = true; converted vb.net code: geckopreferences.user("g

Firebug not showing ::before and ::after pseudo-elements -

Image
after searching extensively on why these pseudo-elements not shown firebug in html inspector way in firefox , chrome built-in debugger, came across number of results indicating indeed possible. testing on 4 different computers including windows , mac os still not find these in html inspector. there setting missing? right using firefox 38.0.5 , firebug 2.0.11 on mac yosemite. update: actually looks feature still in development: https://code.google.com/p/fbug/issues/detail?id=5785 . screenshots saw must have been related effort. firebug displays pseudo-elements within style side panel selected element, not within main html panel.

java - jquery not working in IE11 -

these methods jquery seems not working in ie11, same code working in firefox , chrome. function createcategory() { showloading(); $.post('<s:url value="/social/addeditcatsettings"/>',function(data){ hideloading(); $.prompt(data, { title: "add categories", buttons: { "add": true, "cancel": false }, submit: function(e,v,m,f){ if(v){ e.preventdefault(); saveupdatecat(); } } }); }); } function saveupdatecat(id) { var name = $('#catname').val(); var name_sanitized = name.replace(some scritp....); if(name !== name_sanitized) { showmessage('invalid input. please try agai

aggregation - Plot a graph in kibana 4 with raw performance counter data -

i new kibana. using version 4.1.0. i using logstash agent on application servers publish custom performance counters elasticsearch incidence. the performance counter data’s fetched each server using logstash wmi input plugin , interval set 30 seconds. every 30 seconds have new row in elasticsearch timestamp, cumulative calls, calls per second, cumulative exceptions, cumulative process success , successful process per second. now requirement plot graph similar perfmon on incoming performance counter data. i tried using kibana line chart requirement timestamp (date histogram) in x axis , other counters y axis. not sure aggregation need select each counters on y-axis because need plot graph on raw data received , not on calculated data. if select of aggregation kibana calculation on data based on selected aggregation , result not matching perfmon. can point me right chart type , way plot graph in kibana raw value of counter. thanks, with x-axis date histogram

c# - How to create an accordion in Xamarin.Forms ListView -

how can create accordion in listview data binding? creating app xamarin.forms . this have far: <listview x:name="list" hasunevenrows="true" > <listview.itemtemplate> <datatemplate> <viewcell> <viewcell.view> <grid padding="10,10,10,10"> <grid.rowdefinitions> <rowdefinition height="auto"></rowdefinition> <rowdefinition height="auto"></rowdefinition> </grid.rowdefinitions> <grid.columndefinitions> <columndefinition width="*" /> <columndefinition width="*" /> </grid.columndefinitions> <label text="abc:-" fontsize="20" textcolor="black" grid.column="0" grid.row ="0"/> <label text="{binding abc}"

ios - Issue with Swift 2 Error Handling -

i using rest json data , parse it. using nsjsonobjectwithdata, far i'm aware method used have error handler within parameters it's no longer there. in code here: let err: nserror? let options:nsjsonreadingoptions = nsjsonreadingoptions.mutablecontainers var jsonresult = nsjsonserialization.jsonobjectwithdata(data!, options: options) as! nsdictionary; i error says: "call can throw, not marked 'try' , error not handled" how go fixing error? here correct implementation, do { let jsondictionary = try nsjsonserialization.jsonobjectwithdata(data!, options: nsjsonreadingoptions.mutablecontainers) as! nsdictionary //use dictionary here. print("json : \(jsondictionary)") } catch { print(error) //handle error. }

php - Unexpected behaviour of Intval -

this question has answer here: php intval() weird results 5 answers here, $username userinput, , trying check if entry username, or userid (all integers) i thought use intval function see if $username , intval($username) same, means input userid. the input gave google . , intval('google') 0. why true part of if statement executed? idea? i amnt using === because userinput string. if($username == intval($username)) { echo "userid"; } else { echo "username"; } not sure why unexpected behaviour happening. it happening because of conversion & type juggling of comparison operators. intval('anystring') 0 . and when string getting compared converted numeric value. when string converted 0 . if compare number string or comparison involves numerical strings, each string con

set values on the auth::user controller laravel -

so far laravel site login worked default laravel login attempt function, per new reuqirment, here after login checking performed third party api, after successful authentication checking, application redirect home page. in application lot of place, have used " auth " controller variable value. (ie) auth::user()->name, auth::guest() etc. due third party checking not able value on " auth " controller, when try print auth::user()->name, getting empty value, please advise how set values auth::user()->name etc after third party login checking. please advice got solution $user =user::firstbyattributes(['email' => $email]); auth::login($user);

java - Android SQLite: Running the Same Query with Different Parameters Multiple Times Efficiently -

i have table in sqlite database: species : _id | species | description --------------------------- 1 | aardvark | description aardvark 2 | aardwolf | description aardwolf 3 | caracal | description caracal i receive list of ids server , want display species corresponding ids received. now aware of few options: 1 . obvious , naive way of doing along lines of: sqlitedatabase db = this.opendatabase(); (int id : idlist) { cursor cursorspecies = db.query(true, table_species, new string[] {col_species_species}, col_id + "=?", id, null, null, null, null); cursorspecies.movetonext(); specieslist.add(cursorspecies.getstring(0)); cursorspecies.close(); } this execute way many operations , assume multiple small "disk" reads, slow. 2 . option use sqlitestatement returns single value, doesn't work example , shouldn't used queries anyway. 3 . yet option manually concatenate conditions raw sql query,

php - Can you create an 'if' statement for iFrame blocking instead of: X-Frame-Options? -

when use following code, @ top of php file, block visiting iframes, possible display php page in stead, sort of like, change code 'if' statement? if so, how that? code: <?php /* prevents page being loaded in iframe, on domain, besides original domain [begin] */ header('x-frame-options: sameorigin'); /* prevents page being loaded in iframe, on domain, besides original domain [end] */ ?>

AngularJS: button focused -

i have few input fields , save button. 1 of field type-ahead functionality(tag-input). when pressing enter on keyboard when tag-input focused trigger save button. it seems save button still focused if doing input in other element. how can un-focus button angular? the problem not button has focus, default behavior of enter key submit form. need answers this question .

xcode - Debugging a Quick Look plugin -

i'm new osx development. i'm writing app has own (cross-platform) custom xml-based file type. i want write quick plugin things in finder, , have found tutorial on how supposed work, apparently must doing wrong since see in /var/log/system.log segfault when quick plugin ran. i'd see it's crashing, can't life of me figure out how that. where osx store core dumps (if that)? need set system option or enable that? how xcode @ these core dumps? i'm lost. as you've discovered, since quicklook plugin plug-in instead of standalone executable, need debug process hosts plugin. that, can hook qlmanage executable. the first step make .qlgenerator plugin available quick server. that, need copy ~/library/quicklook , run qlmanage -r . first can implemented post-build action, second has specified in debug options. for post-build action, should follow these steps: hit alt+cmd+r open run configuration window; unfold "build" tab on left ,

javascript - Page_ClientValidate is not a function -

i have client side code i'm running on localhost works fine, when copy same files server runs site, , try same, site fails run same code. specifically, code: var flag = window.page_clientvalidate('vgperosnal'); it works fine when run through localhost, when line through website, next error in chrome debugger: uncaught typeerror: window.page_clientvalidate not function i checked see if there function missing, file "webuivalidation.js" holds function copied well. i searched web hours solutions no luck. please me. update: turns out bigger problem. the answer here old: *after hours of searching didn't find perfect answer, including trying reinstall .net framework, managed overcome problem. copied line code: <script src="/scripts/webforms/webuivalidation.js"></script> and works.

How to generate a symbol table for a Pascal-subset compiler in C? -

i'm writing compiler in c, interpret pseudo-pascal instructions (their syntax irrelevant) asm output. know now, need: a syntax scanner scan user input , identify tokens parser process a parser check if tokens fit defined grammar productions a symbol table i'm little bit stuck on important phase - symbol table. i'm unsure should included in table. variables (identifiers), address. should include keywords such if , for etc? guidelines on appreciated. for now, think logical way define structure: struct entry{ char* name; vartype vartype; int address; } where vartype enum available variable types ( integer , real ). ofc make array of structures , expand when necessary. how , when should modify it? here awsome free book: compiler design in c

django - is_authenticated returns True for logged out user -

i'm writing server app using django, django rest framework, django-rest-auth , django-allauth. have method that's used pass messages between users, , should happen when receiver logged in. however, seems user object's is_authenticated() method returns true though user has logged out (called rest-auth/logout/ , should in turn call django's logout). cause this? there i've missed here? here's code have: class sendmessage(generics.createapiview): permission_classes = (permissions.isauthenticated,) serializer_class = messageserializer def perform_create(self, serializer): m = self.request.data['msg'] targetuser = user.objects.get(pk = self.request.data['user']) if targetuser.is_authenticated(): # send message else: # don't send message unfortunately, is_authenticated() method returns true. def is_authenticated(self): """ return true.

MYSQL, multiple insert and ON DUPLICATE UPDATE -

i'm blocked multiple insert values , if 1 exist, custom update. here query not work : insert `table` (f1,f2,status) values (1,5,'on') on duplicate key update status='off', (3,2,'on') on duplicate key update status='off', (15,20,'on') on duplicate key update status='off'; there solution can query? thanks everyone you can have 1 on duplicate key per insert : insert `table`(f1, f2, status) select 1 ,5, 'on' union select 3, 2, 'on' union select 15, 20, 'on' on duplicate key update status = 'off'; (of course, can values ; prefer select because more general.)

python - Multiple streamhandlers -

i trying beef logging in python scripts , grateful if share best practices me. have created little script (i should run python 3.4) import logging import io import sys def streamhandler(stream, level, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"): ch = logging.streamhandler(stream) ch.setlevel(level) formatter = logging.formatter(format) ch.setformatter(formatter) return ch # root logger logger = logging.getlogger() stream = io.stringio() logger.addhandler(streamhandler(stream, logging.warn)) stream_error = io.stringio() logger.addhandler(streamhandler(stream_error, logging.error)) logger.addhandler(streamhandler(stream=sys.stdout, level=logging.debug)) print(logger) h in logger.handlers: print(h) print(h.level) # 'application' code # goes root logger! logging.debug('debug message') logging.info('info message') logging.warning('warn message') logging.error('error message') log

javascript - Extend node application with new actions -

i've created application handle basic actions save(e.g. saving file in file system) edit etc ,now want users have ability extend functionality new actions,for example user clone application , add additional file new actions (and callback) , register on event i should new actions under hood,my question how can take new actions new file , run in process,simple example helpful update lets assume file handle action , user want add additional action delete var fs = require('fs'); module.exports = { fileaction: function (req, res, filepath) { var urlaction = urlpath.substr(urlpath.lastindexof("/") + 1); if (urlaction === 'save') { this.save(req,res,filepath); } else this.delete(req,res,filepath); }, save: function (req,res,filepath) { var writestream = fs.createwritestream(filepath, {flags: 'w'}); req.pipe(writestream); res.writehead(200, { 'content-type&#

c - I can change the pointer's function? -

in script languages, such perl , python, can change function in run-time. can in c changing pointer function? something like: void fun1() { printf("fun1\n"); } void fun2() { printf("fun2\n"); } int main() { fun1 = &fun2; fun1(); // print "fun2" return 0; } no. can't that . you can regard fun1 placeholder fixed entry point of function. the semantic looking fun1=&fun2; point on every call fun1 causes fun2 called. fun1 value not variable. in same way in statement int x=1; x variable , 1 value. your code makes no more sense thinking 1=2; compile , point on x=x+1; result in x being incremented 2. just because fun1 identifier doesn't mean it's variable let alone assignable.

javascript - Refresh jquery object after ajax -

i have lucky spin script need random number database , let spin number. the problem is, after document.ready, cant assign value object option again. <input type="button" value="test" id="playbtn" onclick="getluckynumber();"/> <input type="button" id="fire" style="visibility:hidden;"/> <input type="hidden" id="luck" value=""/> function getluckynumber(){ $.ajax({ url:"ajax.php", method:"post", data:{event_id:'<?=$event_id ?>'}, }) .done(function(data){ $("#luck").val(data); $("#fire").trigger("click"); }); } $(document).ready(function(){ $('.slot').jslots({ spinner:'#fire',

android - substring in AsyncTask cause app to force quit -

i have code: package com.jamie.translate; import android.content.context; import android.net.uri; import android.os.asynctask; import android.util.log; import android.widget.edittext; import android.widget.textview; import org.apache.http.httpresponse; import org.apache.http.client.httpclient; import org.apache.http.client.methods.httpget; import org.apache.http.impl.client.defaulthttpclient; import java.io.bufferedreader; import java.net.uri; /** * created jamie on 25/6/2015. */ public class translatetexttask extends asynctask<textview, void, string> { textview t; string result = ""; string sourcetext = ""; string sourcelanguage = ""; string resultlanguage = ""; public translatetexttask(string _sourcetext, string _sourcelanguage, string _resultlanguage) { this.sourcetext = _sourcetext; this.sourcelanguage = _sourcelanguage; this.resultlanguage = _resultlanguage; } protec