Posts

Showing posts from January, 2011

c - How can i perform my exe file from boot.local -

Image
i've written code boosting priority of process on opensuse 12.2 system. #include <stdio.h> #include <sched.h> #include <unistd.h> int printusage(void) { printf("\nusage:\nboostprio [pid] [priority: (0-99)] [policy: ff:rr:oth]\n"); exit (1); } int main (int argc , char *argv[]) { int pid = -1 ; int pri; struct sched_param param; if(argc != 4 ){ printf("\nargument miss match !!"); printusage(); return -1; } if((strcmp(argv[1],"-h" ) == 0) || (strcmp(argv[1],"--help") == 0)) printusage(); pid = atoi(argv[1]); if(pid <= 0){ printf("\npid not correct!!\n"); return -1; } pri = atoi(argv[2]); if((pri > 99) || (pri < 0)){ printf("\npriority value not valid !!\n"); return -1; } param.sched_priority = pri; if(strcmp(argv[3],"ff") == 0) sche...

Issue with decoding YUV Image on some Android devices -

i trying create online scanner using android onpreviewframe method. i've created asynctask process image me. code of converting method: public bitmap rendercroppedgreyscalebitmap() { int width = getwidth(); int height = getheight(); int[] pixels = new int[width * height]; byte[] yuv = yuvdata; int inputoffset = top * datawidth + left; (int y = 0; y < height; y++) { int outputoffset = y * width; (int x = 0; x < width; x++) { int grey = yuv[inputoffset + x] & 0xff; pixels[outputoffset + x] = 0xff000000 | (grey * 0x00010101); } inputoffset += datawidth; } bitmap bitmap = bitmap.createbitmap(width, height, bitmap.config.argb_8888); bitmap.setpixels(pixels, 0, width, 0, 0, width, height); return bitmap; } everything works great on devices, htc desire hd, samsung galaxy s2 or samsung galaxy gt or lg-p500. frames correctly sent server in greyscale , p...

python - sort() and reverse() functions do not work -

i trying test how lists in python works according tutorial reading. when tried use list.sort() or list.reverse() , interpreter gives me none . please let me know how can result these 2 methods: a = [66.25, 333, 333, 1, 1234.5] print(a.sort()) print(a.reverse()) .sort() , .reverse() change list in place , return none see mutable sequence documentation : the sort() , reverse() methods modify list in place economy of space when sorting or reversing large list. remind operate side effect, don’t return sorted or reversed list. do instead: a.sort() print(a) a.reverse() print(a) or use sorted() , reversed() functions. print(sorted(a)) # sorted print(list(reversed(a))) # reversed print(a[::-1]) # reversing using negative slice step print(sorted(a, reverse=true)) # sorted *and* reversed these methods return new list , leave original input list untouched. demo, in-place sorting , reversing: >>> = [66.25, ...

linux - Is there any efficient way to get panic log of Go program under Unix easily? -

since i'm running go program server, need mechanism catch panic log if goes wrong later analyze & debug. there efficient way panic log of go program under unix easily? can guys introduce experience this? :) i notification on phone of fatal panics on go programs. here's how: first, run under daemontools (or similar) it's monitored , restart on failure. then, log syslog using built-in log package. syslog forwards papertrail can review state of things, set alerts, etc... here forward undesirable event notifications email address , notifymyandroid can made aware of problems, search similar recent issues, @ context around problems, etc... ...but can't log own uncaught fatal panic, wrote logexec execute program , log stdout , stderr separately along unsuccessful exit notification. example: logexec -tag myprogram /path/to/myprogram -and -its arguments

jQuery TinyMCE with wordcount plugin -

i'm trying "wordcount" plugin working tinymce jquery. i'm not using other tinymce plugins @ moment. based on limited tinymce documentation i've been able find, should straightforward option gets added tinymce init, config not loading @ all. i've searched high , low tips might problem, cannot find anything. (i'm aware of how terrible documentation tinymce is) the form being rendered rails 3.2.12, jquery plugin tinymce included in asset pipeline in application.js file, , i'm using following coffeescript code init tinymce editor: $('main_form').find('textarea.wysiwig').tinymce script_url: '/assets/tinymce/tiny_mce.js', plugins: "wordcount", content_css : '/assets/editor.css', theme : "advanced", theme_advanced_buttons1 : "bold,italic,bullist,numlist", theme_advanced_buttons2 : "wordcount", theme_advanced_buttons3 : "", valid_elemen...

xslt - xsl - Get all attributes from childs -

i'm having trouble getting attributes parent tag, , childs. xml: <macro name="editor"> <names variable="editor" delimiter=", "> <name and="symbol" delimiter=", "/> <label form="short" prefix=" (" text-case="lowercase" suffix=".)" /> </names> </macro> i want able , attributes childnodes. have: <xsl:for-each select="macro"> <xsl:value-of select="@*" /> <br /> </xsl:for-each> how want turn out: editor names editor, name symbol, label short ( lowercase .) when xslt transformation <?xml version='1.0'?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:output method="text"/> <xsl:template match="macro"> <xsl:value-of select="@na...

How to view an online markdown document in an online editor -

i have online markdown doc, www.example.com/readme.md. want online application can take url , render markdown in html. this: www.example.com/awesomemarkdownviewer.php?edit=www.example.com/readme.md stackedit can markdown documents published on gist. way, can use stackedit publish document on different websites. update: stackedit can open url within viewer that: http://benweet.github.io/stackedit/viewer.html?url=http://path/to/file.md update: i'm developer of stackedit. update: to avoid browser caching of multiple pages, use: https://stackedit.io/viewer#!url=http://path/to/file.md

multithreading - C++ program threading concepts -

i attempting write should simple c++ program. 3 parts: serial client: should poll serial server continuously , save received values in table, has infinite loop continue polling serial server logging: write current table values .csv file timestamp every few seconds menu: simple command line menu start/stop server , exit program i have tried use pthread , boost::thread make 3 functions occur simultaneously haven't had luck. can provide me bit of direction on this, i'm new threading, , maybe threading isn't right way go here. here way asking: boost::mutex mtx; void poll_thread() { while(!done) { poll_for_data(); if(data_received) { boost::unique_lock<boost::mutex> lock(mtx); //write data table } } } void log_thread() { while(!done) { sleep(1); boost::unique_lock<boost::mutex> lock(mtx); //log table csv file... } } int main() { //create , start pol...

java - Not specifying Hibernate dialect -

i new hibernate. while reading hibernate, came across dialect property. whatever database use in our application, need set dialect related database , hibernate generate appropriate query related database. just want know if mandatory property set? if not , not specified in hibernate.cfg.xml file, how hibernate generate sql queries i.e. database compliant sql query generated? no not mandatory per documentation http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/session-configuration.html#configuration-optional-dialects , had not try same. while answer of others points answer experienced here. :)

javascript - Finding process id of a Node.js server in Windows -

to find process id of node.js server in unix, use below code: if (process.getgid) { console.log('current gid: ' + process.getgid()); } so output 1888 in *nix os, when execute same in windows os, getting output undefined per node.js docs have explicitly mentioned method won't work in windows. so question, there anyway can process id in windows os? tried execute taskkill /f /im node.exe kills node processes, want kill particualr process. there anyway achieve this? on windows process.pid works me. regarding docs, getgid not returning process id, rather group identity of process , process id use pid to kill process use: taskkill /f /pid processid

Is it possible to override window.location.hostname in Javascript? -

i'm curious there possibility override window.location.hostname? didn't found on google... searched wrong phrases because think had asked before me. sorry bad english. edit: more specific. don't want that. want know if can override execute code. in general - have list of domains approve execute code. when if (window.location.hostname === myurl.com) gives true go, other case have alert or something. don't want that: window.location.hostname = "myurl.com" if (window.location.hostname === myurl.com) according reference: https://developer.mozilla.org/en-us/docs/dom/window.location these properties. can "set them navigate url" - however, result in redirection.

vb.net - Protecting information after installer VB 2012 -

when in make installer on project in visual basic 2012. i'm using installshield - , filed need create program "debug or realese" folder. there files "program.exe.config" files. can open if has vb or program can open vb 2012 files. in files there information connection server program makes. have server name , mine user/password gives access mine sql server. can make line server information crypted , still workes avoid - changing server/logging server. or how can block files while i'm making installer. - not open them. store encrypted password , username in config file. , decrypt them inside code right before connection. should make trick. make same server name if you'd to.

gwt - Spring Security X.509 Preauth -

i'm using spring security 2.x's preauthentication x.509 certificates. i certificatetext via httpservletrequest.getattribute("certificate") . sometimes, above call returns "" (empty). believe occurs when http session has expired. what explain why httpservletrequest.getattribute("cert") returns empty? edit in kerberos, example, ticket available in every http request. cert not in x.509 http requests? please access certificate using code: x509certificate[] certs = (x509certificate[]) request.getattribute("javax.servlet.request.x509certificate"); certificate populated request after successful client certificate authentication. ensure support long certificate chain: add max_packet_size propery worker.properties file worker.ajp13w.max_packet_size=65536 add packetsize propery configuration of ajp connector in tomcat configuration \conf\server.xml <connector port="8089" enablelookups=...

else-if statements in javascript -

i'm facing serious problem else-if statements in javascript. use them assign session variable value whenever try assigns last value written in last else if statements, odd thing goes right else if block , gets value right @ end of function changes wrong value. here's code i'm working on: function showinput(value){ if(value==='username'){ document.getelementbyid('search').innerhtml = "user name: " <?php $_session['searchfield']="user name"; ?> } elseif (value==='phonenumber'){ document.getelementbyid('search').innerhtml = "phone number: " <?php $_session['searchfield']="phone number"; ?> } elseif (value==='email'){ document.getelementbyid('search').innerhtml = "e-mail: " <?php $_session['searchfield']="email"; ?> }...

asp.net mvc - MVC display foreign key from another table -

controller: public actionresult details(int id) { viewbag.accounttype = new businesslayer.accounttypemanager().getaccounttypes(); return view(new businesslayer.accountmanager().getaccount(id)); } view: <div class="display-label">account type</div> <div class="display-field">@html.displayfor(modelitem => modelitem.accounttype)</div><br /> this current view displays accounttype id. how can display accounttype name being passed viewbag.accounttype (ienumerable) something following <div class="display-label">account type</div> <div class="display-field">@html.displayfor(modelitem => modelitem.accounttype)</div> @{ var typenames = viewbag.accounttype ienumerable<string>; foreach(var item in typenames) { <div>item</div> } } mode elegant way public class accounttypevewmodel { public ienumerable<...

php - Form emailing on browser load -

the form have created below emails input data in csv file. problem having every time browser loads page sends blank version of csv file, , once form submitted want redirect "thank you" page. how can accomplish this? the php use before html form is: <?php if(isset($_post['formsubmit'])) { } $email=$_request['email']; $firstname=$_request['firstname']; $lastname=$_request['lastname']; $to = "ali@ebig.co.uk"; $subject = "new application submission"; $message = "". "email: $email" . "\n" . "first name: $firstname" . "\n" . "last name: $lastname"; //the attachment $vartitle = $_post['formtitle']; $varforname = $_post['formforname']; $varmiddlename = $_post['formmiddlename']; $varsurname = $_post['formsurname']; $varknownas = $_post['formknownas']; $varadressline1 = $_post['formadressline1...

ios - UIImageView finding how much is out of bounds -

i'm scaling image within uiimageview using : uiviewcontentmodescaleaspectfill the image scales nicely issue imageview sits within uiscrollview, i've set origin 0,0. fine majority of images i'm using have greater height , push out of bounds. don't want trim image, i'd dynamically push uiimageview frame down on y axis based off amount that's out of bounds. how can go finding out what's out of bounds on y axis / height? excuse poor code example. nsstring *imageurl = [self.detailitem objectforkey:@"job_header"]; animage = [[uiimageview alloc] initwithframe:cgrectmake(0, 0, max_height, 118)]; animage.contentmode = uiviewcontentmodescaleaspectfill; [animage setimagewithurl:[nsurl urlwithstring:imageurl] placeholderimage:[uiimage imagenamed:@"placeholder.png"] completed:^(uiimage *image, nserror *error, sdimagecachetype cachetype) { //adjust frame once image loaded [self adjustposition...

asynchronous - Synchronization when implementing push , iOS -

i have special problem of synchronization application share , ideas me solve it. i developing application 2 things : 1) registers push notifications in appdelegate . 2) opens webview in viewcontroller , loads url. form of url loaded : http://.www.thisismyurl.com/udid , udid users unique identifier. in didregisterforremotenotificationswithdevicetoken: registering token , after receive , inside function make http request server send push token , udid. so in both didregisterforremotenotificationswithdevicetoken of appdelegate , in viewcontroller retrieving udid , using described. everything till last week worked perfectly. apple decided reject application using udid. way go me create unique identifier using cfuuid , save key chain. the problem : as see make use of unique identifier both in appdelegate's didregisterforremotenotificationswithdevicetoken function inside viewcontroller . must created in 1 of these controllers or else different!!! (remember cfuu...

database - Using PL/SQL to develop relationship among two tables? -

i new pl/sql language , working on problem , looking advice right direction go. appreciated! i have employee table , building table. employee table consists of employee_id, last_name, first_name, , job(f/p) full or part time. building table consists of employee_id , building_location.(this location employee works from) either home or office. i want user type in last_name user input. result looking information employee: employee name, job (full or part employee) , building_location. example, want output if user typed in johnson: employee name job position building location ==================================================== andre johnson part time home office nick johnson full time downtown office if user types in string want list employees work company. if name on employee table 'johnson' displays johnson. need add in select clause? at point put code checks if employee works company or not. looking build this. accept p_1 pro...

javascript - shopify app (python)Uncaught ReferenceError: require is not defined -

with shopify api python i able place script tag in (client's) store . problem having 2 script tags among 1 require.js. store page's source code (client's store) var urls = ["myjsfilewithrequire.js? shop=store.myshopify.com","mysecondfile.js?shop=store.myshopify.com"]; this gets loaded . how can make sure 1 js loaded completed (requre.js) before rest files loaded . is way of doing right ? ( have not tired yet ) var imported = document.createelement('script'); imported.src = 'myscriptfile.js'; document.head.appendchild(imported); function load_data(){ undone = true; while(typeof(window.myscriptfile.data)=="object" && undone){ loop();} i guess there must better way . i had same problem, , solved using almond . it's maintainer of requirejs, , light-weight amd loader. can compiled in optimized js, , included (as scripttag) in client's shopify site.

c++ - Unresolved external symbol _IID / _CLSID -

i created default atl project msvc 2010 simple default atl dialog. added second project solution, named mycontrols, created atl dhtml control of wizard. placed atl dhtml control atl dialog. now call methods of atl dhtml control in atl dialog's oninitdialog function. in order able make call like: ccomptr<idhtmlcontrol> ptr; hresult hr = getdlgcontrol(idc_activex_control_dhtml , iid_idhtmlcontrol, (void**)&ptr); i including file dhtmlcontrol.h mycontrols project. however, following errors: error 1 error lnk2001: unresolved external symbol _iid_idhtmlcontrol error 2 error lnk2001: unresolved external symbol _libid_mycontrolslib error 3 error lnk2001: unresolved external symbol _clsid_dhtmlcontrol error 4 error lnk2001: unresolved external symbol _iid_idhtmlcontrolui note: appears linking mycontrols.lib incorrectly, however, added mycontrols.lib linker->input->additonal dependencies & specified ../$(configuration) in linke...

vb.net - String 3 decimal places -

example 1 dim mystr string = "38" i want result 38.000 ... example 2 mystr = "6.4" i want result 6.400 what best method achieve this? want format string variable atleast three decimal places. use formatnumber : dim mystr string = "38" msgbox(formatnumber(cdbl(mystr), 3)) dim mystr2 string = "6.4" msgbox(formatnumber(cdbl(mystr2), 3))

c# - While databinding checkboxlist -

i have 2 checkbox lists in asp.net, 1st list has fruit names , 2nd list has few fruit names. list getting populated database using sqldatasource now need 1st list fruits should have fruits not in list 2 here's code sir, private void allfruitsnames() { using (sqldatasource ds = new sqldatasource(connectionstring(), "select fruitname fruittable")) { checkboxlist1.datasource = ds; checkboxlist1.datatextfield = "fruitname"; checkboxlist1.databind(); } } private void populateonlyfewfruitsnames(int crateid) { checkboxlist2.items.clear(); using (sqldatasource ds = new sqldatasource(cs(), "select fruitname fruittable crateid ='" + crateid + "'")) { checkboxlist2.datasource = ds; checkboxlist2.datatextfield = "fruitname"; checkboxlist2.databind(); } } how can balance fruits if fruit in 2nd checkbox list should removed...

vb.net deserialize an xml string -

i've got simple xml string looks this: <?xml version="1.0"?> <accountbalance> <value> 22.00 </value> </accountbalance> i'd set value of <value> variable in vb.net. how do this? not sure serialization comes play this, if it's simple xml string can use linq xml value quite easily: dim xml xelement = new xelement.parse(xmlstring) dim balance integer = x in xml.descendants("value") select cint(x.value) this give collection of value elements in xml. if have one, can this: dim balance integer = (from x in xml.descendants(xmlstring) select cint(x.value)).singleordefault() xmlstring xml string want values - parse method loads xml supplied string. use .load if it's in file. syntax might bit off - i'm doing off top of head.

How to handle configuration in Go -

i'm new @ go programming, , i'm wondering: preferred way handle configuration parameters go program (the kind of stuff 1 might use properties files or ini files for, in other contexts)? the json format worked me quite well. standard library offers methods write data structure indented, quite readable. see this golang-nuts thread . the benefits of json simple parse , human readable/editable while offering semantics lists , mappings (which can become quite handy), not case many ini-type config parsers. example usage: conf.json : { "users": ["usera","userb"], "groups": ["groupa"] } program read configuration import ( "encoding/json" "os" "fmt" ) type configuration struct { users []string groups []string } file, _ := os.open("conf.json") decoder := json.newdecoder(file) configuration := configuration{} err := decoder.decode(&...

awk - bash - padding find results -

i'm running following command directory listing: find ./../ \ -type f -newer ./lastsearchstamp -path . -prune -name '*.txt' -o -name '*.log' \ | awk -f/ '{print $nf " - " $filename}' is there way can format output in 2 column left indented layout output looks legible? the command above adds constant spacing between filename , path. expected output: abc.txt /root/somefolder/someotherfolder/ helloworld.txt /root/folder/someotherfolder/ a.sh /root/folder/someotherfolder/scripts i nice tool kind of thing column -t . add command on end of pipeline: find ... | awk -f/ '{print $nf " - " $filename}' | column -t

qt - The use of setFrameRange method -

what use of setframerange method (which part of qtimeline class)? found example: qgraphicsitem *ball = new qgraphicsellipseitem(0, 0, 20, 20); qtimeline *timer = new qtimeline(5000); timer->setframerange(0, 100); qgraphicsitemanimation *animation = new qgraphicsitemanimation; animation->setitem(ball); animation->settimeline(timer); (int = 0; < 200; ++i) animation->setposat(i / 200.0, qpointf(i, i)); qgraphicsscene *scene = new qgraphicsscene(); scene->setscenerect(0, 0, 250, 250); scene->additem(ball); qgraphicsview *view = new qgraphicsview(scene); view->show(); timer->start(); obviously seems work noticed modifying parameter doesn't change thing. tried write sth this: timer->setframerange(100, 100) timer->setframerage(0,0) but despite of i'm doing result still same. to sum up, have 2 questions. method doing (and yes, i've read documentation), , why modifications doesn't change anything? ...

java - ActionBar and CustomView - home button -

i want have customview on actionbar define buttons, logos, etc. want make use of home button , ability search in actionbar via search interface. possible add, i.e. home button icon on actionbar custom view layout? thanks it possible use custom view on action bar. strava android app (or @ least gives appearance of action bar @ top has non-standard layout). addressing requirements 1 @ time: can inflate view of own , assign action bar: view customview= getlayoutinflater().inflate(r.layout.customview, null); getsupportactionbar().setcustomview(customview); what put in view is, naturally, entirely have manage yourself, including home button actions. includes icon , text home button on left hand side , search functionality. on small device (especially in portrait mode) i'd go search icon on devices more real estate fit text input field in well, using alternative layouts feature automatically pick appropriate view device.

c - What is wrong in this code: giflib library usage -

i have read giflib usage explanation , wrote following code: giffiletype *giffile = dgifopenfilename("d:\\my.gif00.gif"); dgifslurp(giffile); int h = giffile->sheight; int w = giffile->swidth; int count = giffile->imagecount; gifpixeltype *mypixels = new gifpixeltype[w]; int errcode = dgifgetline(giffile, mypixels, 1); if (errcode == gif_ok) { } else { printgiferror(); } as see there, file set dgifopenfilename function argument results in error, printgiferror() prints out following message: gif-lib error: #pixels bigger width * height. i can't understand wrong in code. want read gif file's pixels, edit them set gif file. issue? as far can tell, seems indicate gif file corrupt. the problem shouldn't using dgifgetline() . function dgifslurp() reads entire gif file giffile structure. internally, calls dgifgetline() (and fair few other things), , time returns, entire file has been processed. trying call dgifgetline() after doe...

.net - Get user-friendly name for generic type in C# -

is there easy way without writing recursive method give 'user friendly' name generic type type class? e.g. following code want 'list<dictionary<int>>' instead of shorthand or full name given following code: var list = new list<dictionary<int, string>>(); var type = list.gettype(); console.writeline(type.name); console.writeline(type.fullname); based on edited question, want this: public static string getfriendlyname(this type type) { if (type == typeof(int)) return "int"; else if (type == typeof(short)) return "short"; else if (type == typeof(byte)) return "byte"; else if (type == typeof(bool)) return "bool"; else if (type == typeof(long)) return "long"; else if (type == typeof(float)) return "float"; else if (type == typeof(double)) return "double"; else if (type == ty...

excel - automated solution for manual copy-paste-transpose? -

i have excel spreadsheet has data pulled different data source. the problem have data 'repeated': (site column , owner column b): site owner http://website1.com john doe http://website1.com jane doe http://website2.com john smith http://website2.com jane smith http://website2.com john doe what change this: site owner1 owner 2 owner 3 http://website1.com john doe jane doe http://website2.com john smith jane smith john doe i have copying "owners" each site, , pasting them using "transpose" method in order accomplish this. problem is, there lot of records , boring , wasteful work. is there way accomplish automatically via macro, script, or otherwise? thanks! to make bad pivot table suggestion above... sub tester() dim data, rngtl range, num dim long, f range dim site, owner data = sel...

PHP Assistance with empty() in a loop -

let's wanted check see if variable empty , something... can this: if ( empty($phone) ) { $phone = 'not provided'; } but want bunch of items. i'm thinking array , loop, this: $optionalfieldsarray = array($phone, $address, $city, $state, $zip); foreach ($optionalfieldsarray $value) { //what goes here???? } is foreach resonable way it, check if $phone, $address, $city, etc. empty , assign "not provided" string when is? if so, can me syntax goes inside loop? you can this: <?php $required_vars = array( 'phone', 'address', 'city', 'state', 'zip' ); foreach( $required_vars $required_var ) { if( empty( $$required_var ) ) $$required_var = 'not provided'; // $$var -> variable name = value of $var } ?> check above code yourself. can understand how works. because confusing concept.

ruby on rails - URL requests with [object] in place of parameter values -

we're seeing requests our server literal [object] replacing values parameters should be. for example: http://example.com/users/[object] i've found suggestions might ie9 can't quite nail down. see: http://www.webmasterworld.com/webmaster/4560505.htm has else seen behaviour? have managed nail down problem is? i don't know, seems duplicate of we getting slew of requests ie9 /scanimageurl closed off-topic. maybe there's more appropriate sister site web-development questions. have suggestions?

heredoc - How to have a shell script that unpacks several files when executed? -

i have several text files within shell script file unpack directory once script executed. i've been getting 'here-doc' solutions this: cat>mytextfile.txt<<'eof' content eof however, shell scripts getting larger , beginning require more , more files unpacked. basically, making computational pipeline, , want distribute single shell script, needs expand several directories/subdirectories/files once run. thanks! you can embed in script uuencoded tar file , unpack this: tar xf - <<eof uuencoded tarball eof you can encode data way: $ tar cf - src_tree | compress | uuencode src_tree.tar.z >your_here_doc then paste file your_here_doc 'the uuencoded tarball' line now, this: $ (echo tar cf - '<<eof'; cat your_here_doc; echo eof) >self_expanding_files.sh

python - flask-login not sure how to make it work using sqlite3 -

so far made user object , login function, don't understand user_loader part @ all. confused, here code, please point me in right direction. @app.route('/login', methods=['get','post']) def login(): form = login() if form.validate(): user=request.form['name'] passw=request.form['password'] c = g.db.execute("select username users username = (?)", [user]) userexists = c.fetchone() if userexists: c = g.db.execute("select password users password = (?)", [passw]) passwcorrect = c.fetchone() if passwcorrect: #session['logged_in']=true #login_user(user) flash("logged in") return redirect(url_for('home')) else: return 'incorrecg pw' else: return 'fail' return render_template('login.h...

What kind of Makefile variable assignment is this? -

i've used simple makefiles years, been assigned task of learning ins , outs of large, complicated set of autotools-generated makefiles used code base employer has bought. in these, i'm running variable declarations following: qobject_mocsrcs = $(qobject_header:%.h=.gen/moc_%.cpp) \ $(qobject_srcs:%.cpp=.gen/moc_%.cpp) qobject_deps = $(qobject_mocsrcs:%.cpp=.deps/%.po) my best guess context these set lists of names of files provided build process, eg., qobject_mocsrcs should end list of (a) .h files, (b) .cpp files, based on % stem names of set of intermediate .cpp files generated during build, in temporary directory ./gen. used store moc_%.cpp files output result of build of qt files qt's moc tool...what driving me crazy, have been unable find in make documentation i've got (mostly gnu make manual) tells me style of declaration called, can track down , grip on syntax. contents of $() sort of rules, , nearest equivalents in gnu make manual s...

asp.net mvc - How to return status information during lengthy batch process in MVC 4 action? -

in mvc 4 app, have view uploads file client machine with: <snip> @using (html.beginform("batch", "home", formmethod.post, new { enctype = "multipart/form-data" })) { <input class="full-width" type="file" name="batchfile" id="batchfile" <input type="submit" value="do it" /> } <snip> the "batch" action in home controller takes file , processes in way may lengthy.... minutes even: <snip> [httppost] public fileresult batch(modeltype modelinstance) { // batch work. string result = lengthybatchprocess(modelinstance.batchfile.inputstream) var encoding = new asciiencoding(); byte[] bytearray = encoding.getbytes(result); response.addheader("content-disposition", "attachment;filename=download.csv"); return file(bytearray, "application/csv"); } <snip> this works fine, , isn't inherent pro...

r - Replacing data.table observations; vector approach -

i replace select values in data.table variable new set of values. ### vector of old values replace char <- c('one', 'two', 'three', 'four', 'five', 'six', 'seven') ### vector of new values replace old values num <- as.character(1:7) ### create data.table dt <- data.table(a = c(rep(char, each = 2), c('something', 'else', ' ', '')), b = 1:18, c = letters[1:18]) ### note warning, appears work expected dt[a == char, := num] i following error: warning messages: 1: in == char : longer object length not multiple of shorter object length 2: in `[.data.table` (dt, == char, `:=` (a, num)) : supplied 7 items assigned 2 items of column 'a' (5 unused) i curious, what's correct way this? help appreciated. realize can achieve same result brute force: data[var == 'seven', var := '7'] data[var == 'six', var := ...

python - Operations on huge dense matrices in numpy -

for purpose of training neural network, @ point have huge 212,243 × 2500 dense matrix phi , , vectors y (212243) , w (2500), stored numpy arrays of doubles. i'm trying compute is w = dot(pinv(phi), y) # serialize w... r = dot(w, transpose(phi)) # serialize r... my machine has 6 gb of ram , 16 gb of swap on ubuntu x64. started computation twice , twice has ended system (not python) swap errors after hour of work. is there way perform computation on computer? doesn't need done python. if don't need pseudoinverse else computing w , replace line with: w = np.linalg.lstsq(phi, y)[0] on system runs 2x faster, , uses half intermediate storage.

r - arranging matrix - network graphs -

Image
i trying make network graph, using function gplot library(sna) . graph represent links between different fields. have following data: mtm <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1) fi <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) mcli <- c(0,0,1,0,0,1,1,1,0,0,0,0,1,0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1) mat1 <- data.frame(mtm,fi,mcli) mat1 <- as.matrix(mat1) where "mtm", "fi" , "mcli" "fields of interest" , every row different project has some/any/none of fields in common. how transform these data this? matx: mtm fi mcli mtm 10 0 1 fi 0 1 1 mcli 10 1 17 i interested in representing -in network graph- fields "nodes", , connections "edges". helpful in representing "popular" , interconnec...

bash - Linux find files with similar name and move to new directory -

say have unorganized directory thousands of files have prefix in names abc-tab, abc-vib, h12-123, h12-498.... how move files same prefix own directory? i thinking using like find . -path '*/support/*abc*' -exec mv "{}" /new/abc\; but means have retype command every prefix. grab prefixes ls , uniq single list, move files using loop. for f in $(ls | cut -d- -f1 | uniq); mkdir "${f}" && mv "${f}"-* "${f}" done many people learn shell scripting advanced bash scripting guide . check out cut , uniq man pages details on programs.

css - Images disappear during translate3d on Chrome for iPhone and iPad -

i have coverflow type image gallery have created mobile picture viewing. first iteration lives here: http://codepen.io/jasonmerino/pen/fsloq . i've wired touch events , seems going mobile safari on iphone , ipad, when go view on chrome iphone or ipad images disappear during part of css translate3d moves images sides. i have added -webkit-backface-visibility: hidden; of markup comprises swiper, not fix disappearing act images doing. what missing here? appreciated. thanks! the problem peice of code removing inlined css translate3d . code had in place dealt removing translate re-assigning background images. for (var = 0; < images.length; i++) { $el.images.eq(i).css('style', 'background-image: url(' + images[i].src + ')'); } in mobile safari fine, in chrome images reloaded when re-assigned background image, hence disappearing act. adjusted code little smarter, , concise, removed translate inlined styles. $el.images.css('transfo...

How to check ranges of java versions in javascript? -

i stuck: how check if user has specified java requirement? need find ranges (for instance java versions between 1.5.0_10 , 1.6.0_10). using javadeploy.js oracle , using versioncheck method can't figure need pass inside versioncheck method ranges such example provided. try this: var lower = deployjava.versioncheck("1.5.0_10+"), higher = deployjava.versioncheck("1.6.0_10+") if (lower && !higher) { // between 1.5.0_10 && 1.6.0_10 } reference: http://docs.oracle.com/javase/tutorial/deployment/deploymentindepth/ensuringjre.html

Meteor filter collection -

i'm trying secure accessing specific collection i'm having troubles doing it. have no problems disabling insert, update , delete collection.allow() map. the problem want filter results returned collection.find() , collection.findone() function. read meteor.publish() , meteor.subscribe() stuff, somehow cannot make work (it's not getting filtered, can see results). in server-code following: groups = new meteor.collection("groups"); meteor.publish("mygroups", function() { if (functions.isadmin(userid)) { return groups.find({ sort: { name: 1 } }); } }); the function i'm using works (so it's not it's returning true ). in client-code wrote following: meteor.subscribe("mygroups"); groups = new meteor.collection("groups"); now when groups.find{}); @ client still results (and should no result). am misunderstanding or doing wrong? of course ma...

backbone.js - How do I send a model that was clicked on within a ItemView to another ItemView that is on the same page? -

i have collection of tools displayed compositeview. each of rendered items in collection itemview. name of region holds these called toolnameregion. i have region named tooldetailsregion in page , has supposed render attributes of clicked tool in toolnameregion. here view: @tools.module "aboutapp.show", (show, app, backbone, marionette, $, _) -> class show.layout extends backbone.marionette.layout template: jst['backbone/apps/about/templates/about'] regions: toolnameregion: "#tool-name" tooldetailsregion: "#tool-details" class show.tool extends backbone.marionette.itemview template: jst['backbone/apps/about/templates/_tool'] tagname: "li" events: "click a.tool-link" : -> @trigger "tool-name:link:clicked", @model # how hell pass show.tooldetail class? console.log @model # shows model attributes clicked class show.tools extends bac...

c# - Uniform random numbers to simulate with ten decimal places -

i'm tring run specific simulation, have code implemented result not 1 i'm expecting, need generate random uniform(ranged 0 1) numbers 10 decimal places (in order convert in other distribution). example: 0,0345637897, 0,3445627876, 0,9776428487 this code: double next = r.next(1000000000, 9999999999); return double.parse(string.format("0.{0}", next)); this should enough: double v = math.round(myrandom.nextdouble(), 10); the difference between 0.123 , 0.1230000000 matter of formatting, see answer @samiam. after edit: double next = r.next(1000000000, 9999999999); return double.parse(string.format("0.{0}", next)); this getting integer between 1000000000 , 9999999999 , uses default culture convert double (in 0 ... 1.0 range). since seem use comma ( , ) decimal separator, @ least use return double.parse(string.format("0.{0}", next), cultureinfo.invariant);

c++ - Why don't default-template arguments work on using declarations? -

i'm trying search alternative following dilemma. know how when have template class/function default template-argument have apply angle brackets when they're empty? attempt @ making fix. know can use simple typedef ( typedef x<> l ) don't want use different names refer class. so tried following. reason when supply type template argument still doesn't work. why that? #include <type_traits> template <typename = void> struct x {}; template <typename t = void> using l = typename std::conditional< std::is_void<t>::value, x<>, x<t> >::type; int main() { l l; } errors: prog.cpp: in function ‘int main()’: prog.cpp:10:7: error: missing template arguments before ‘l’ prog.cpp:10:7: error: expected ‘;’ before ‘l’ the syntax same other type templates: need provide empty template brackets default templates: l<> l; the using declaration redundant ...

google app engine - At what rate do indexes "explode" in GAE's big table? -

at rate indexes "explode" in gae's big table? the excerpt documentation below explains collection values, indexes can "explode" exponentially. does mean object 2 collection values, there index entry each subset of values in first collection paired each subset in second collection? or there index entry each possible pair of values? example: entity: widget:{ mamas_list: ['cookies', 'puppies'] papas_list: ['rain', 'sun'] } index entry each subset of values in first collection paired each subset in second collection: cookies rain cookies puppies rain cookies puppies rain sun cookies sun cookies rain sun puppies rain puppies sun puppies rain sun only index entry each possible pair of values: cookies rain cookies sun puppies rain puppies sun exploding indexes excerpt: source : https://developers.goog...

Scala type projection -

i have collection of models, each of exposes next(...) method moves model forward discrete step. each next() method has parameter given abstract type t. i want able wrap each model class, wrapper inherit type t (which different each model), provide additional logic. trivial letting wrapper extend model, not feasible internal logic of actual model implementations. my solution use type projections so: trait model { type t // works fine when concrete implementation, cannot overridden def next(input : t) = println(input) } abstract class parent { type s <: model type t = s#t val model : s def next(input : t) = model.next(input) } this fails compiler error: type mismatch; found : input.type (with underlying type parent.this.t) required: parent.this.model.t note in concrete implementation of parent, parent.this.t should equal parent.this.model.t. so far workaround abandon using type system, , creating unique parent classes each model (ie duplicating of ...

mapping key value xml pair to java map using xstream -

i trying convert xml file follows java map. xml <person> <id>123</id> <demographics> <lastname>abc</lastname> <firstname>xyz</firstname> </demographics> <married>yes</married> </person> the xstream code follows: final xstream xstream = new xstream(); xstream.alias("person", map.class); xstream.alias("demographics", map.class); xstream.registerconverter(new mapentryconverter()); final map<string, object> map2 = (map<string, object>) xstream.fromxml(xml);//where xml above defined string. the custom mapentryconverter is: public class mapentryconverter implements converter { public boolean canconvert(final class clazz) { return abstractmap.class.isassignablefrom(clazz); } public void marshal(final object value, final hierarchicalstreamwriter writer, final marshallingcontext context) { final abstract...

Sip client for Java -

this question has answer here: what popular java sip library? [closed] 5 answers i need develop java sip client will 1) receive caller id when phone answered. 2) send caller number along information (such line answered caller) given tcp port. does have expirience in field , can advise me can find client api or useful documents? below article indicating libraries... sip java api / library there also: https://java.net/projects/jsip i have not used these seem have decent options you.

Does anyone know where I can find a set of online Ruby programming sets/exercises? -

i searching set of problems, book of exercises or challenges ruby and/or ruby on rails. resources found appear offline or outdated. see recommendations ruby quiz, site seems dead. appreciated. i completed ruby series on codecademy, , starting pickaxe book programming ruby 1.9 & 2.0. it's tutorial book no exercises or challenged though. project euler pretty solid ( http://projecteuler.net/ ) ruby koans ( http://rubykoans.com/ ). can try "learn ruby hard way" well. as far rails exercises, i'd "learn rails example" michael hartl (which free , easy find online).

json - callback functions - url redirection -

i want create callback function, handles javasripting - callback function if want append redirection url - how do - confused start - callback functions - callback code called on event, events can click, mousemove, keypress, window resize, ... you can start search google event handling in js by example http://www.w3schools.com/js/js_htmldom_events.asp you can use js library too, jquery managing event for url redirection, have @ location.href location.href = "http://google.com";

jquery - Fancybox links to specific tabs in an iframe with tabify, doesnt work -

not sure if title helps have lightbox links iframe runs fanybox, loads iframe jquery 'tabify' plugin. here live link: http://intp.co/periodic-table/table.html the link fancybox this: <a href="elements.html#li" class="element fancybox.iframe"><img src="elements/li.png" alt="lithium"></a> it loads box, doesn't select content. i'm looking happen: http://intp.co/periodic-table/elements.html#zr-tab unfortunately iframe link fancybox doesn't load this. you have not given link proper. '-tab' added in href. <a href="elements.html#li-tab" class="element fancybox.iframe"><img src="elements/li.png" alt="lithium"></a>

basic - TrueBasic Error: Library LEVEL1.TRU: no such file -

i programmed game in truebasic , main program has call external library named "level1.tru". main program , level1.tru in same folder, reason following error: truebasic error: library level1.tru: no such file this in version 6, on previous version @ school no such error arises. i'm terribly confused on why happening appreciated. thank so so in advance (: if copied , pasted code here might find typo cause of problems this... otherwise, try putting whole file path in...

c# - TableAdapter error - namespace not found -

i trying insert data database through dataset. database table called users , dataset called userdataset. getting error says the type or namespace name 'userdataset' not found (are missing using directive or assembly reference?) also connecting datasets in correct way, not sure how check if connection correct. i using this msdn reference. usertableadapters.userstableadapter = new usertableadapters.userstableadapter(); user.usersdatatable usertable = us.getdata(); userdataset.usersrow newusersrow; newusersrow = userdataset.users.newusersrow(); newusersrow.username = textbox1.text; newusersrow.password = textbox2.text; this.userdataset.users.rows.add(newusersrow); this.userstableadapter.update(this.userdataset.users);

JavaFX 2.x: Translate mouse click coordinate into XYChart axis value -

Image
in javafx 2.x, using xychart , want display (x,y) axis coordinate values of chart mouse move across chart. setup event handler on chart handle setonmousemoved events. however, not sure how convert mouseevent's getx() value chart's coordinate value? use axis.getvaluefordisplay(displayposition) determine location of mouse in axis value coordinates: xaxis.getvaluefordisplay(mouseevent.getx()), yaxis.getvaluefordisplay(mouseevent.gety()) here sample reports co-ordinates on mouse hovering in line chart. screen capture doesn't capture mouse cursor - you'll have imagine there ;-) import javafx.application.application; import javafx.collections.fxcollections; import javafx.event.eventhandler; import javafx.geometry.insets; import javafx.geometry.pos; import javafx.scene.*; import javafx.scene.chart.*; import javafx.scene.control.label; import javafx.scene.input.mouseevent; import javafx.scene.layout.vbox; import javafx.stage.stage; public class linecha...