Posts

Showing posts from May, 2014

performance - A really slow UPDATE to a MySQL server -

i running cms, has nothing it. i have simple query is: update e107_online set `online_location` = 'http://page.com/something.php?', `online_pagecount` = 133 `online_ip` = '175.44.*.*' , `online_user_id` = '0' limit 1; but same query reported website support gives that: user@host: cosyclim_website[cosyclim_website] @ localhost [] thread_id: 7493739 schema: cosyclim_website query_time: 12.883518 lock_time: 0.000028 rows_sent: 0 rows_examined: 0 rows_affected: 1 rows_read: 1 it takes 12 (almost 13) seconds simple update query? there way optimize somehow? if run through phpmyadmin takes 0.0003s. the table: create table if not exists `e107_online` ( `online_timestamp` int(10) unsigned not null default '0', `online_flag` tinyint(3) unsigned not null default '0', `online_user_id` varchar(100) not null default '', `online_ip` varchar(15) not null default '', `online_location` varchar(255) not null default &

php - error #1146 in phpMyAdmin in XAMPP -

i did dumb. i'd imported create tables sql file twice. that's not worst part however. proceeded trying drop duplicate tables phpmyadmin database. loads when click on phpmyadmin now: error sql query: edit select `tables` `phpmyadmin`.`pma_recent` `username` = '[myusername]' mysql said: #1146 - table 'phpmyadmin.pma_recent' doesn't exist as in, above on otherwise blank, white page. edit returns normal when comment out "advanced features" section in config.inc.php file (the red exclamation signs still beside everything, i'm starting wonder if that's default icon choice phpmyadmin 4.0.1). once uncomment them, above returns. i've noticed tables seems empty (maybe reason exclamation signs?). mean anything? check whether tables inside phpmyadmin database have 2 underscores __ after pma prefix. if case, update entries in config.inc.php additional underscore.

sqlite - database is not created in android -

in application activity running fine database not getting created there no error in logcat. main activity class: package com.example.testdb; import android.os.bundle; import android.app.activity; import android.view.menu; public class mainactivity extends activity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); database d=new database(this); } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.main, menu); return true; } } database class: package com.example.testdb; import android.content.contentvalues; import android.content.context; import android.database.cursor; import android.database.sqlite.sqlitedatabase; import android.database.sqlite.sqlitedatabase.cursorfactory; import android.database.sqlite.sqliteopenhelper;

c++ - implement reverse_iterator for my string class (also rbegin() and rend() methods) -

below code string class. want implement reverse_iterator , rbegin() , rend() methods. have pasted code assign method. string::reverse_iterator rbegin = str2.rbegin(); string::reverse_iterator rend = str2.rend(); for(string::reverse_iterator b = rbegin; b!= rend; ++b) { cout<<*b; } class string {//my custom string class public: class iterator:public std::iterator<std::random_access_iterator_tag, char> { public: iterator():ch(null){} iterator(const iterator& it) : ch(it.ch) {} char& operator*() { return *ch; } iterator& operator++() { ch = ch+1; return *this; } bool operator==(const iterator& rhs) { return ch == rhs.ch; } bool operator!=(const iterator& rhs) { return ch != rhs.ch; } private: friend class string; iterator(char* c):ch(c) {} char* ch; }; explicit st

c - Why aren't standard escape sequences like \a ,\v working?Why ' works without \,and is \? standard? -

why aren't \a (beep), \v (vertical tab) not working in program though standard according links below?and why single quotation mark working without using \' ? , finally,is \? escape character @ microsoft site says,because use ? symbol inside printf() format string without \ , works fine. to put clearly: why \a , \v not working? why single quote works without \ though \' escape sequence? is \? escape sequence?(the link says ? works without \ ) http://msdn.microsoft.com/en-us/library/h21280bw(v=vs.80).aspx http://en.wikipedia.org/wiki/escape_sequences_in_c why \a , \v not working? because console you’re using doesn’t support them. compiler does, , produces correct character code in output, terminal emulator ignores them. why single quote works without \ though \' escape sequence? because it’s unnecessary escape in strings, need escape in char literal. same \" string literal: "'" vs.

java - Freeze a gui jdbc ,when save a data,why? -

hy create 1 project (i maked using turtorial: http://www.homeandlearn.co.uk/java/save_a_new_record.html using database: http://www.homeandlearn.co.uk/java/java_and_databases.html ) when want save new record program freezing.(i want when save new data program able wrok next , prev buttons) the save_button changed these code: private void btnsaverecordactionperformed(java.awt.event.actionevent evt) { //................................................................................... string first = textfirstname.gettext(); string last = textlastname.gettext(); string job = textjobtitle.gettext(); string id = textid.gettext(); int newid = integer.parseint(id); try { string insertsql = "insert workers (id,first_name,last_name,job_title) values(" + newid + ",'" + first + "','" + last + "','" + job + "')"; stmt.executeupdate(insertsql); rs.next();

css - How to place DT elements side by side? -

this: http://jsfiddle.net/zcdkt/1/ renders: dt-namea dd-definitiona 1 dt-nameb dd-definitionb 1 dd-definitionb 2 i wish have this: dt-namea dt-nameb dd-definitiona 1 dd-definitionb 1 dd-definitionb 2 i've tried display inline, float, clear... can't figure out. ? update: inside anchors, may have different size images this, hence, don't side side: http://jsfiddle.net/j6ute/3/ separate dls way achieve because need wrapper element: http://jsfiddle.net/david_knowles/j6ute/ <div id="links-logolinks"> <dl> <dt>support</dt> <dd><a href="">support 1</a></dd> </dl> <dl> <dt>partners</dt> <dd><a href="">partner 1</a></dd> <dd><a href="">partner 2</a></dd> </dl> </div>

javascript - Using both scroll and touchevents on android (phonegap) -

i'm building app in phonegap. app makes heavy use of javascript , has content area should scrollable. need use touchstart , touchend events. the problem that, unless use e.preventdefault on touchmove/touchstart, touchstart event once , never again after (not useful). if e.preventdefault() on either of two, native scrolling disabled (on mobile devices). how allow native scrolling while listening touchstart + touchend? failing that, simulate native scrolling (using touchmove?)? i've tried hand @ myself, , result of frankly terrible.

vb.net - VB - Change application text with button -

i want button1 change text of form1 "my application name" "my application name2" click of button. what i've tried: form1.text = (textbox1.text) but no luck. any help? you cannot can change form name @ run time. name of form can want, must stay same throughout. can't imagine why ever want change name in runtime not visible users. form's caption on other hand completly different thing, adressed in @matzone's answer.

jetty - Jersey resource not resolving in OSGI -

i have been following tutorial video shows how run jersey server ( edit: jax-rs server via apache wink, see accepted answer) in osgi. short video , process seems clear. i'm not clear on how helloworldresource loaded jersey. helloworldresource registered osgi container service using apache felix dependencyactivatorbase (which works great). gather apache felix whiteboard supposed somehow magically map jersey resource, when go run 404. i know service mapped correctly shows in console when issue 'services' command. know server running or wouldn't 404 not found. i've double checked bundles , believe installed correctly. any hints appreciated. first of all, amdatu not based on jersey. jersey 1 of many jax-rs implementations available. amdatu based on apache wink. shouldn't matter however, since should programming standard anyway. amdatu looks services registered object.class in service registry, , checks if registered service annotated @pat

java - Color changes when turning Blob from SQLite database to a bitmap and then a mat -

Image
so have image put in blob in sqlite database what next read out blob database (so turn blob bitmap). turn bitmap mat (cause need use feature descriptor) end following mat: as can see, colors wrong. code: bitmapfactory.options bmpfactoryoptions = new bitmapfactory.options(); bmpfactoryoptions.inpreferredconfig = bitmap.config.argb_8888; bmpfactoryoptions.inscaled = false; bmpfactoryoptions.outheight = 240; bmpfactoryoptions.outwidth = 320; // decodes blob bitmap byte[] blob = contact.getmp(); bytearrayinputstream inputstream = new bytearrayinputstream(blob); bitmap bitmap = bitmapfactory.decodestream(inputstream); bitmap scalen = bitmap.createscaledbitmap(bitmap, 320, 240, false); mat imagemat = new mat(); utils.bitmaptomat(scalen, i

opencv - Internal thinning -

given outcome of applying canny edge detector image using cv2 python library, want dilate edges internal part of convex boundaries using morphological operators. kind of structure element should use that? late answer, here simple trick: you duplicate image you put 0 outside convex boundaries, inner pixels used during dilation you apply dilation you compute maximum between original image , dilation result. you can use structuring element of choice. square little bit aggressive, when ball preserve euclidean distance.

java - Different for-loop incremental value -

i fiddled around loops, , tried head around of logical part of it. while i'm far beyond level of loops @ point, still tend bit weird when comes logic sometimes. however, found incremental value of loop different depending on whether inside or outside loop: int i; for(i = 0; < 10; i++) { system.out.println(i); // 0 ... 9 } system.out.println(i); // 10 now, i'm afraid 1 day i'll come point i'll have use counter more matching against condition... now think understand why happening; being incremented after condition fails , loop dies, supposed happen? is there mathematical/logical (or elegant) way not make go n+1 after loop termination, i'm missing here? that how loop works: check condition, if holds go 2, else terminate; run body; execute modification, go 1. so in word, cannot. also, how loop terminate if variable not go n + 1 ? in case, loop condition holds, run forever.

javascript - JS - set a global variable -

i want set global variable via set function sets undefined value: var name; var setname = function(name){ this.name = name; } in case don't use this . (it work not necessarily. why? read this ) just use: var name; var setname = function (aname) { name = aname; } also make sure code not inside of scope (function): function foo() { // ... var name; var setname = function (aname) { name = aname; } // ... } in case name not global , have omit declaration make global: function foo() { // ... var setname = function (aname) { name = aname; // not global, if not defined in visible scope } // ... } but bad practice, try avoid polluting global namespace . variable considered in global namespace if: it has no var ( name = ... , , there no other visible local variable called name it set on window (e.g. window.name = ... )

Distinguish between ImportError because of not found module or faulty import in module itself in python? -

i have few modules in python, imported dynamicly , have same structur (plugin.py, models.py, tests.py, ...). in managing code want import submodules, example models.py or tests.py not mandatory. (so have plugin_a.plugin , plugin_a.tests plugin_b.plugin ). i can check if submodule exists by try: __import__(module_name + ".tests") except importerror: pass that fail, if module_name+".tests" not found, fail if tests -module try import something, not found, example because of typo. there way check if module exists, without importing or make sure, importerror raised 1 specific import-action? you know import error message if module doesn't exist check that: try: module = module_name + '.tests' __import__(module) except importerror, e: if e.args , e.args[0] == 'no module named ' + module: print(module, 'does not exist') else: print(module, 'failed import')

c# - A good solution for await in try/catch/finally? -

i need call async method in catch block before throwing again exception (with stack trace) : try { // } catch { // <- clean things here async methods throw; } but unfortunately can't use await in catch or finally block. learned it's because compiler doesn't have way go in catch block execute after await instruction or that... i tried use task.wait() replace await , got deadlock. searched on web how avoid , found this site . since can't change async methods nor know if use configureawait(false) , created these methods take func<task> starts async method once on different thread (to avoid deadlock) , waits completion: public static void awaittasksync(func<task> action) { task.run(async () => await action().configureawait(false)).wait(); } public static tresult awaittasksync<tresult>(func<task<tresult>> action) { return task.run(async () => await action().configureawait(false)).result; }

adobe - Is there a pdf library (.Net/C# compatible) that allows for embedding Audio/Video media in a pdf? -

i have requirement need attach audio/video media submitted binary files embedded pdfs residing on server. btw, audio/video binary coming mobile app. is there pdf library out there allows embedding audio/video in pdf? also, need these media embedded in simplest form when pdf containing media opened on target device, there should no need installing additional media decoders. my server side environment in .net/c# need pdf library compatible .net almost pdf .net supports movie annotations, itextsharp (open source), tallpdf, xfinium.pdf (i work company), pdf4net, docotic.pdf, name few. thing media files embedded (converting video not job) , target machine must have required codecs in order play media. if have control on media format, can choose format supported many platforms.

MYSQL select random of each of the categories -

i want select random 5 records each categories in same table. table name: t_shop column name: shop_id, shop_categoryid for example: shop_id | shop_categoryid 1 | 1 2 | 1 5 | 1 7 | 1 9 | 1 10| 1 13| 2 15| 2 22| 2 23| 2 25| 2 i have tried using limit in subquery, error occur: version of mysql doesn't yet support 'limit & in/all/any/some subquery i ask there ways solve? thanks. if have 2 categories (as in question), easiest way in mysql use union all : (select * t_shop category = 1 order rand() limit 5) union (select * t_shop category = 2 order rand() limit 5)

objective c - dipatch_async releases local variable -

i did not find suitable answers on web, post question here. __block int test = 1; dispatch_async(dispatch_get_main_queue(), ^{ test = 2; }); nslog(@"%i",test); this code result in console message "1". __block nsstring *test = @"no"; dispatch_async(dispatch_get_main_queue(), ^{ test = @"yes"; }); nslog(@"%@",test); this code result in console message "no". why so? thought __block identifier should solve problems in case. hypothesis local variable copied , code inside block hadn't modify outside itself. how can modify local variables inside dispatch_async? sorry if noob question. you dispatching asynchronously main queue. the dispatch_async returns before block executed (coincidentally). to underscore how non-deterministic concurrent programming can be: note nslog() might see new value maybe once in blue moon. might not ever see in debugging environment, customer might encounter b

php - How do I say IF class #1 on left, if class #2 on right in loop -

i have loop in wordpress spit out 2 classes. 1 class photos, other video. once new photo or video added, adds below last div. example: photos photos video photos video so need happen is, need photos left , videos right. tried using float:left , float:right , clear:left; , clear:right; , it's not working planned since divs set @ 50%. if not cleared, go in rows photos, photos, new row, video, photos. i thinking there php can use, saying if photos, in column, if videos in other column. i tried following: .photos { float: left; width: 50%; display: block; clear: left; } .video { float:right; width:50%; display: block; clear:none; } and also: .photos { float: left; width: 50%; display: block; clear: none; } .video { float:right; width:50%; display: block; clear:none; } i want videos go right , photos left top bottom. can't separate 2 in 2 different div's because in loop. here array: <?php while (have_posts()) : the_post(); ?>

c++ - How to return an Iterator--list<T>:: iterator, as function return value -

i implementing abstract hash-table container. find() function defined , works fine, shown below: template <class hashedobj> hashedobj& hashtable<hashedobj>::find(const hashedobj &x){ typename list<hashedobj>::iterator itr; itr = std::find(thelist[hash(x)].begin(), thelist[hash(x)].end(), x); if(itr == thelist[hash(x)].end()) return item_not_found; else return *itr; } however, want define function called findaddress() returns itr (the iterator) instead of *itr . code is: typedef list<hashedobj>::iterator iterator; template <class hashedobj> iterator hashtable<hashedobj>::find(const hashedobj &x){ return std::find(thelist[hash(x)].begin(), thelist[hash(x)].end(), x); } the above complain that: type std::list<hashedobj, std::allocator<_chart> > not derived type hashedtable<hashedobj>. basically want return iterator type has been defined std before. i no ex

key - How to implement "press to enter"in c++ -

any idea on how implement "press key move on" in c++? based on understanding, input stream function, requires users hit "enter" read. but how make “whenever key being hit, moves on next stage without hitting enter key?" by way, working station linux thanks lot this not possible in standard c++, since os specific. on linux can use curses , getch in loop until character. or can use "press enter continue" http://linux.die.net/man/3/getch

c++ - FFMPEG audio upsampling/resampling to 48000 Hz causes sound wheeze/noises/dissortions -

i'm using following example http://svn.gnumonks.org/tags/21c3-video/upstream/ffmpeg-0.4.9-pre1/output_example.c make videos. if use 44100 hz output audio format seems fine, if use 48000 hz audio gets wheeze. any suggestion, please. here input audio , encoded video audio in 48 khz has wheezing audio: http://www.unsode.com/test.zip

javascript - Keep Reference to Connected Sockets Per User -

i have (for clarity's sake) chat. users can login, write messages, , others see [name]:[message] . i don't want send user's name , id every time write socket.emit('say', message); because that's redundant, i'm doing on server so: var io = require("socket.io").listen(server), sockets = {}; io.sockets.on('connection', function (socket){ socket.on('savepersontosocket', function(user){ socket.user = user; sockets[user.id] = socket; } socket.on('dosomething', dosomething); }); // must outside of 'connection' since have tons of these in more //complex structure , don't want create them per user connection. function dosomething(){ ... sockets[userid].emit('foo'); // how userid @ point? ... } so, how userid @ point? notes: for each user logs in , connects facebook account, client tell server save person's name , id. i thought of doing cookie

c++ - Why is this use of the [] operator causing a compiler error? -

i wrote quick function familiar boost::program_options . please note po namespace alias, defined thus: namespace po = boost::program_options . int application(po::variables_map* vm) { std::cout << vm << std::endl; std::cout << *vm["infile"].value(); // tried: std::cout << *vm["infile"] return success; } //application when comment out second line in function body, application compiles , prints address of vm . however, when try compile function appearing here, following compiler insult: invalid types ‘boost::program_options::variables_map*[const char [7]]’ array subscript i should note replacing second line std::cout << vm->count("infile") returns 1 . what have done wrong? abusing boost construct or getting mixed in (de)referencing vm ? update following suggestion pass reference avoid operator precedence issue, rewrote function thus: int application(po::variables_map& vm) {

html - WkHTMLtoPDF not loading local CSS and images -

i've seen multiple questions similar one, hesitant @ first post it. nothing suggested resolved issue , can't seem figure out what's wrong myself. for project made 1 client wanted ability convert quotes customers (generated using online form) pdfs. simple enough. entire project in php, used following simple process: save quote temporary html file use wkhtmltopdf convert html file pdf output pdf file clean (delete temporary files) this worked until changed servers. new server has firewall. at first pdf conversion step returning firewall page saying server couldn't make outbound connections. resolve fed html file directly instead of linking (/var/www/mysite/temp/18382.html instead of www.example.com/temp/18382.html). converted html, firewall prevented loading of css , images i can overcome css embedding directly in site instead of linking (using <style> tags), doesn't work images i tried using relative links first. changed <img src="

Python list extend functionality using slices -

i'm teaching myself python ahead of starting new job. django job, have stick 2.7. such, i'm reading beginning python hetland , don't understand example of using slices replicate list.extend() functionality. first, shows extend method by a = [1, 2, 3] b = [4, 5, 6] a.extend(b) produces [1, 2, 3, 4, 5, 6] next, demonstrates extend slicing via a = [1, 2, 3] b = [4, 5, 6] a[len(a):] = b which produces exact same output first example. how work? has length of 3, , terminating slice index point empty, signifying runs end of list. how b values added a ? python's slice-assignment syntax means "make slice equal value, expanding or shrinking list if necessary". understand may want try out other slice values: a = [1, 2, 3] b = [4, 5, 6] first, lets replace part of a b : a[1:2] = b print(a) # prints [1, 4, 5, 6, 3] instead of replacing values, can add them assigning zero-length slice: a[1:1] = b print(a) # prints [1, 4, 5, 6, 2

ruby on rails - setting up nginx.conf file -

i have vps passenger , nginx installed , trying app deployed, however, i'm getting 404 error. in vpn app located in: ~/app1 so in nginx.conf file have following: server { listen 80; server_name localhost; location / { root /app1/public; } passenger_enabled on; } however, tried setting root ~/app1/public, still got 404, i'm not quite sure how set up. also, don't quite understand , pointing public work, don't have default index.html file, rather in routes.rb define root :to => "controller#index". how passenger find index page inside /views when pointing public directory? thanks try this server { listen 80; # server_name mysite.com; root /app1/public; passenger_enabled on; } and restart nginx: $ sudo service nginx restart

java - Separate String into two parts -

my string looks this: "/namestart blabla1 /nameend blabla2" . ps. might /namestartblabla1/nameendbababa2 example. i need 2 strings: string1 == blabla1 string2 == blabla2 i got strings this: if(mystring.startswith("/namestart")){ pattern p = pattern.compile("/namestart(.*?)/nameend"); matcher m = p.matcher(mystring); if (m.find()) { string string1 = m.group(1); string string2 = mystring.substring(mystring.indexof("/nameend")+8, mystring.length())); } } first question can done better or solution ok? and second problem blabla1 , blabla2 can anything, can /nameend (probaby wont be) or screw reg expression. theoretical solution that? i not sure trying maybe try using groups indexes instead of substring . rid of if(mystring.startswith("/namestart")){ can use ^ anchor @ star of regex indicate matching part should placed @ start of string. string mystring = "/namestart blabla1 /na

cocoa touch - Is the main Grand Central Dispatch queue serial or concurrent? -

suppose call dispatch_async() 3 times in order: dispatch_async(dispatch_get_main_queue(), ^{ [self doone]; }); // code here dispatch_async(dispatch_get_main_queue(), ^{ [self dotwo]; }); // more code here dispatch_async(dispatch_get_main_queue(), ^{ [self dothree]; }); will executed like [self doone] , [self dotwo] , [self dothree] , or order guaranteed? in case, question if main queue serial or concurrent. from documentation: dispatch_get_main_queue returns serial dispatch queue associated application’s main thread. so main queue serial queue, , [self doone] , [self dotwo] , [self dothree] executed sequentially in order.

php - Database Error. SQL query is not being executed -

i have form takes 2 values input , parses them using post method next file have piece of code. should save 2 values in mysql database. strangely doesn't .. , in output error this: 0: 0: $service_name = $_post['service_name']; $service_price = $_post['service_price']; $link = mysql_connect("localhost", "db_user", "pa$$"); mysql_select_db("database", $link); echo mysql_errno($link) . ": " . mysql_error($link). "\n"; mysql_select_db("database", $link); mysql_query("insert service_tbl(id_service, service_name, service_price) values(null,'$service_name','$service_price')", $link); echo mysql_errno($link) . ": " . mysql_error($link) . "\n"; in database table service_tbl , id_service is auto_increment , other 2 columns varchar. doing wrong here? you trying insert null in auto increment column, wich not possible, change mysql_query("

javascript - Add onclick and onmouseover to canvas element -

i want add onclick , onmouseover , onmouseout events individual shapes in canvas element. i have tried doing svg in different ways , found no single method work in major browsers. maybe, there simple way add onclick , other events canvas shapes? can please show me how add onclick ? here code: canvas { background:gainsboro; border:10px ridge green; } <canvas id="canvas1"></canvas> var c=document.getelementbyid("canvas1"); var ctx=c.getcontext("2d"); ctx.fillstyle="blue"; ctx.fillrect(10,10,60,60); var ctx=c.getcontext("2d"); ctx.fillstyle="red"; ctx.fillrect(80,60,60,60); // these need onclick fire them up. how add onclick function blue() { alert("hello blue square") } function red() { alert("hello red square") } here barebones framework adding events individual canvas shapes here's preview: http://jsfiddle.net/m1erickson/safku/ unlike svg, aft

.htaccess - Redirecting subdomain from an alias domain -

so have been searching net along site regarding htaccess redirections, have yet not managed find solution myself (it may not possible). so scenario this: have bought cheap host, comes subdomain, has ability add own domain alias it. right can access site using: subdomain.hostprovider.com , mydomainasalias.com what wish achieve here, able redirect subdomain domain alias random page on random site. so subdomain.mydomainasalias.com 2ndsubdomain.subdomain.hostprovider.com i have tried this: rewriteengine on rewritecond %{http_host} ^subdomain\.mydomainasalias\.com$ [nc] rewriterule ^ http://randomsite.com/asd [l,r] amongst other things, achieve this, have yet not succeeded. possible?

php - Find FILE path relative to the htdocs directory -

i have script displays images present on folder. e.g. script path (from htdocs): /admin/global/thisscript.php e.g. pictures folder path (from htdocs): /public/test/images/ now need print under each image path of file starting htdocs directory. e.g. if have: $picture1 = /web/mysite/htdocs/public/test/images/picture1.png $picture1name = basename($picture1) i'd print print "/public/test/images/".$picture1name having /public/test/images in variable automatically update if picture1.png path changes. if use $_server['php_self'] it returns path of file i'm displaing. also __file__ __dir__ basename dirname are not working me. how can path? thank you perhaps $_server['document_root'] edit: something like: $path = "/web/mysite/htdocs/public/test/images/picture1.png"; $path = dirname(str_replace($_server['document_root'], '', $path));

I can't receive data from custom module in node.js -

i wrote module called accountmanager.js var sqlite3 = require('sqlite3'); var db = new sqlite3.database("./users.db"); exports.userexists = function userexists(nickname) { var stmt = 'select * users login="' + nickname + '"'; db.each(stmt,function(err,row) { if(row) { if(row.login==nickname) return true; else return false; } }); } in main app.js file i've got var accountmanager = require('./lib/accountmanager'); console.log(accountmanager.userexists('user1')); this app says 'undefined' in console... checked module working fine, guess it's problem callback? please, give me help, don't understand wrong code... you need understand how asynchronous functions , callbacks work. basically cannot return inside callback need invoke callback pass userexists . var sqlite3 = require('sqlite3'); var db = new sqlite3.database("./u

c# - WPF application very slow - Kinect SDK 1.7 -

i have 1 simple application kinect seems consumes lot of resources. works 1-2 minutes , lag becomes unbearable. this configuration: intel core i3 cpu m330 2.13 ghz 4 gb ram ati radeon hd 4570 this code application window: public partial class mainwindow : window { public mainwindow() { initializecomponent(); loaded += mainwindow_loaded; } void mainwindow_loaded(object sender, routedeventargs e) { this.windowstate = system.windows.windowstate.maximized; } private void stopkinect(kinectsensor sensor) { if (sensor != null) { if (sensor.isrunning) { //stop sensor sensor.stop(); //stop audio if not null if (sensor.audiosource != null) { sensor.audiosource.stop(); } } } } private void window_closing_1(object sender, system.componen

testing - Grails - Recreate database schema for integration test -

is there convenient way force grails / hibernate recreate database schema integration test? if add following in datasource.groovy empty database created before integration tests run: environments { test { datasource { dbcreate = "create" } } } by default each integration test executes within transaction rolled-back @ end of test, unless you're not using default behaviour there shouldn't need programatically recreate database. update based on comment, seems want recreate schema before integration tests. in case, way can think of, run drop , recreate schema use grails schema-export import fresh schema class myintegrationtest { sessionfactory sessionfactory /** * helper executing sql statements * @param jdbcwork closure passed <tt>sql</tt> object used execute jdbc statements */ private dojdbcwork(closure jdbcwork) { sessionfactory.currentsession.dowork(

PHP substr counts wrong -

i want 130 chars random string $param['sec1'] = base64_encode(openssl_random_pseudo_bytes(95)); $param['sec1'] = substr($param['sec1'], 0, 130); var_dump($param['sec1']); and following result: string(128) "zrand6xjvrefta6smfp1k9c+udzabpmse6awd/1vul+2aghlbzooc0t/vlbqsv6dvjy38 d/3dkrdanng9tjjcvy3bm/occpko2amjkeantawtvt+cptgizw42fwdnte=" ["zrand6xjvrefta6smfp1k9c+udzabpmse6awd\/1vul+2aghlbzooc0t\/vlbqsv6dvjy38d\/ 3dkrdanng9tjjcvy3bm\/occpko2amjkeantawtvt+cptgizw42fwdnte=","dt+w00j2fqpwst2 vkkg55cck6thlw7pikkqreylw4u3q4fwjqagsxfrzrgl0fshbjwww9diykqdbagjlwm0kcuvjhtc 9rs62tv1tdyixnkjtc7ba4mrbbtozphpehfw=","sabufosdfs1kkhxaxggtfxo09wxeqk\/ro10 9ckktupua7dgn\/jc\/snrzt4z\/oalmdl4fu9nq0hxcvxaafkpdv3aklcqrejavybkjiptutpcu 5jo6n1kxft3tx5ggwp0="] var_dump says 128 chars more 128 - why that? the part beginning ["zrand not generated code have given, code executed not shown in question. var_dump($

c# - How to mark gmail UNREAD emails using asp.net -

i using tutorial http://www.codeproject.com/articles/188349/read-gmail-inbox-message-in-asp-net make gmail client. using code in tutorial retrieving emails inbox. have problem distinguishing unread ones. can me one, please? if you're communicating using pop3, there isn't way tell unread. need talk on other api (perhaps gmail inbox feed?) https://developers.google.com/google-apps/gmail/#gmail_inbox_feed

webdriver - How to set username and password for Chrome Proxy Using Selenium? -

i'm using webdriver.chrome.driver proxy proxy = new proxy(); proxy.sethttpproxy("0.0.0.0:1234"); capabilities.setcapability("proxy", proxy); and worked great before, i'm tested behind proxy server requires authentication. how pass chrome username / password proxy requires? i can't find in docs :/ any appreciated. so after research i've learned pretty limitation lot of people working around using chrome extension automatically puts in proxy password pops up. i chose not go down route , switched proxy ip based authentication. hope helps else.

c++ - why is setw not working? -

#include<fstream.h> #include<iomanip.h> #include<iostream.h> using namespace std; ifstream f("atestat.in"); ofstream g("atestat.out"); int n,i,nr=0; float v[100]; void a(int n) { for(i=1;i<=n;i++) f>>v[i]; for(i=1;i<=n;i++) cout<<v[i]<<" "; } int main() { f>>n; a(n); cout<<endl; float s=0; for(i=1;i<=n;i++) { if(v[i]<0) { s=s+v[i]; nr++; } } cout<<setw(2)<<s/nr<<endl; } my "atestat.in" file contains: 6 -56.765 2.3 4.56 -1.2 -1.8 3 the program first displays numbers on second line of "atestat.in" file, through use of array, , supposed display arithmetic mean of negative numbers inside array, precision of 2 numbers after decimal mark. reason, setw(2) nothing @ all, cout<<setw(2)<<s/nr<<endl; displays "19.9217" instead of "19.92

ruby on rails - How can i specify SSL version in curb -

i interacting api requires ssl3. from command line form request like: curl -ssl3 -h 'authorization: bearer xxxx' https://capi-eval.signnow.com/api/user/documentsv2 with curb have implemented: c = curl::easy.new("https://capi-eval.signnow.com/api/document") |curl| curl.headers["authorization"] = "bearer xxxx" curl.use_ssl = true curl.ssl_version = "ssl3" end this ssl_version method seem should same thing -ssl3 switch error message results is: 1.9.3-p286 :082 > c.perform curl::err::sslconnecterror: curl::err::sslconnecterror do know how create curb request? i realized ssl flags require integers. works. c = curl::easy.new("https://capi-eval.signnow.com/api/documentsv2") |curl| curl.headers["bearer"] = "xxxx" curl.verbose = true curl.use_ssl = 3 curl.ssl_version = 3 end

ruby on rails - ActiveRecord find with joins and associations? -

i have model twitteruser has_one website shown in model below: class twitteruser < activerecord::base has_one :website, :foreign_key => :id, :primary_key => :website_id end i'm trying run query join twitteruser website , twitterusers' website has updated_at date > date, limited 10 rows. i thought give me wanted, apparently it's not. what's wrong it? twitteruser.includes().find(:all, :limit => 10, :conditions => ["websites.updated_at >= '2013-05-12 05:31:53.68059'"], :joins => :website) in database, twitter_users table consist of website_id field. websites table has id field. this should work. twitteruser.joins(:website).where("websites.updated_at >= '2013-05-12 05:31:53.68059'").limit(10)

C# Need Help Changing a Label.Text - My Function/method won't change my Form Label Text -

i wanted make function organize code better giving me headache, problem want use public function change label.text whenever call them form it's not working. how can working , please basic. thank you. here's code: namespace nosleephd { public partial class nosleephd : form { public nosleephd() { initializecomponent(); } public void selectfolder(string drivelabel, string writepath) { folderbrowserdialog tree = new folderbrowserdialog(); tree.rootfolder = environment.specialfolder.mycomputer; tree.shownewfolderbutton = false; tree.description = "please select drive or folder on external hard drive"; tree.showdialog(); if (tree.selectedpath.length != 0) { drivelabel = tree.selectedpath.tostring(); properties.settings.default.writepath01 = drivelabel.tostring(); properties.se

windows applications - Setting ControlID to be used for AutoIT -

i trying automated functional testing windows app , got hands on autoit. looks (if not all) standard windows applications have control id set. unfortunately, control id field blank when mouse hover using finder tool. looks application (written in c) hasnt set id each element? i've used xcode's ui automation ipad apps , use "setaccessibilityidenitifier" uniquely identify each field. trying find out equivalent windows application. that begs question, autoit correct tool? testing calculation based. can assume 2 input fields , 1 output. if user enters 5, , 2 , hits "add", need check if output 7. need uniquely identify each element. i noticed when there group of elements, when hover mouse on group, "static" classname , coordinates change when try access each element, , every other control instance, classnamenn remain same. ideas? thanks in advance! edit: autoit forum guys, group issue fixed - http://www.autoitscript.com/forum/topic/151055-

jquery - Is it possible to use setDate on an inline Bootstrap Datepicker? -

does know how setdate on inline calendar in bootstrap datepicker eternicode( https://github.com/eternicode/bootstrap-datepicker ). i've been struggling figure out, alas have fallen short. can work input, not inline view. the simplest solution seems be: the_date = new date(2013, 10, 25); $('#datepicker').datepicker('update', the_date);

jquery - Validating an autocomplete selection on a ko observable value -

i have autocomplete list of values. selected value of selection ko observed variable. need validate value selected list or value typed in, incase did not select value list. it appears right when type letter , select value list, validation call fired letter typed , called @ same time value selected. is there approach validating value user selected or typed not race condition? here code: html <div> <label for="assignedto">assigned to: </label> <input id="assignedto" placeholder="assigned to" data-bind="ko_autocomplete:{source: $parent.users(), select: addassignedto}, value: assignedto"/> <span class="error" data-bind="text: assignedtoinvalid"></span> </div> model self.assignedtoinvalid= ko.observable(); self.assignedto= ko.observable(); self.addassignedto=

c# - Smoother transition in movement? -

i question. still new sfml 1 seemed bit tough. have tried using while loops , such no avail. the game doing @ moment car going , forth on x axis , guess able pick points , stuff or avoid objects coming towards car until dies. how make movement smoother? car move 8 units first, before moving 8 units in desired direction until let go of button. it's same when other way. instantly move , keep moving when press either key. static void onkeypressed(object sender, eventargs e) { vector2f newpos = new vector2f(0, car.position.y); keyeventargs ke = (keyeventargs)e; if (ke.code.equals(keyboard.key.a)) { if (car.position.x != 0) { newpos.x = car.position.x - 8; car.position = newpos; } else if (car.position.x < 0) { newpos.x = 0; car.position = newpos; } else if(car.position.x == 0)

What does Clojure’s bit-and-not do? -

from docs : bit-and-not function usage: (bit-and-not x y) (bit-and-not x y & more) bitwise , complement added in clojure version 1.0 clojure's other bit- functions make sense me, don't understand one. it equivalent this: (bit-and x (bit-not y)) this function can used subset tests. set a (represented bitmask) subset of set b if , if (bit-and-not b) zero.

nvd3.js - NVD3 RotateLabels not working on MultiChart -

first , last labels rendered incorrectly. know if there's way fix this, or bug? here's how it's rendering me http://i.imgur.com/f4i9fjl.png the solution can change depending of elements you've inside body tag. i've selected .nv-x .nv-axis elements inside <body> . line defines attr option, can change de translate , rotate values. var chart = nv.models.discretebarchart(); nv.addgraph(function() { ... (chart options chart.x , chart.y, load data, etc.) d3.select('body') .selectall('.nv-x.nv-axis > g') .selectall('g') .selectall('text') .attr('transform', function(d) { return 'translate (-13, 15) rotate(-45 0,0)' }); }); return chart; });

sql - Making an AJAX request with AngularJS -

i started angularjs app learn more js framework, i'm confused in things working sql want little make show on click table. what im trying make request database , fill table ng-repeat , show sliding effect when click button. i dont have idea how sql query , insert controller in angularjs, please help. database movies table: |--id--|------text------|-----year-----| |______________________________________| |--1---|----avengers----|-----2012-----| |--2---|------mama------|-----2013-----| i want pass angularjs like: $scope.movies = [ {text:'mama', year:'2013',id:2}, {text:'avengers', year:'2012',id:1}]; this should started. it's simple controller data-binding property named myscopedata . code uses $http object in angular make ajax request php retrieve data database. scope variable myscopedata gets set , updates view. html <div ng-app="myapp"> <div ng-controller="maincontroller">