Posts

Showing posts from May, 2012

dictionary - extending built-in python dict class -

i want create class extend dict's functionalities. code far: class masks(dict): def __init__(self, positive=[], negative=[]): self['positive'] = positive self['negative'] = negative i want have 2 predefined arguments in constructor: list of positive , negative masks. when execute following code, can run m = masks() and new masks-dictionary object created - that's fine. i'd able create masks objects can dicts: d = dict(one=1, two=2) but fails masks: >>> n = masks(one=1, two=2) traceback (most recent call last): file "<stdin>", line 1, in <module> typeerror: __init__() got unexpected keyword argument 'two' i should call parent constructor init somewhere in masks. init probably. tried **kwargs , passing them parent constructor, still - went wrong. point me on should add here? you must call superclass __init__ method. , if want able use masks(one=1, ..) syntax have u

java - Wizard not redrawing/revalidating jframe -

i'd create wizard app in java. came point draw frame 3 different layouts, each containing label , 'next' button, when click button on first frame see empty frame instead. import java.awt.borderlayout; import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.imageicon; import javax.swing.jbutton; import javax.swing.jframe; import javax.swing.jlabel; public class mainframe extends jframe implements actionlistener{ private borderlayout layout; public mainframe() { super("mywizz"); setsize(500, 500); setresizable(false); setdefaultcloseoperation(jframe.exit_on_close); setvisible(true); setlocationrelativeto(null); } protected imageicon createimageicon(string path, string description) { java.net.url imgurl = getclass().getresource(path); if (imgurl != null) { return new imageicon(imgurl,

css - element on right side of window overlapped on window resize -

i have 2 sets of (jquery mobile) buttons on left , right hand side of page. when shrink window left side, left hand set of buttons moves expected, keeping space between , window border. when shrink form right side, window overlaps set of buttons on side. how can avoid this? have both sets of buttons retain percentage horizontal position whether shrink screen right or left. (wheni shrink bottom, both sets of buttons retain space top border of window). css: #mainpage{ position:relative; } .submenuclass{ /* right side */ display: none; position: absolute; z-index: 10000; top: 2%; left:85%; } .mainmenuclass{ /*left side*/ display: none; z-index: 10000; position:absolute; top: 2%; left: 5%; } .submenuclass{ /* right side */ display: none; position: absolute; z-index: 10000; top: 2%; right:5%; /*change this,you may need adjust value*/ }

java - Design pattern for import and update actions -

i have small component required application. component loads csv file , updates customer records based on data finds. there single csv file every customer update. checks file location csv files for each csv file finds, load csv file, parse , update customer data updated data thats it. however im torn between couple of ways this. have single updater() class everything. have update() class representation of loaded csv data, knows how parse csv etc. , have updater() class responsible updating customer records. update() class have updater() which of these correct solution or there other better solutions this? if thinking of real general design, consider following: class updateset : list of updates. csv file if want. interface updateinstance : different types of updates, request point of view. csv line if want. class insertinstance : implements updateinstance . insert request. class deleteinstance : implements updateinstance . delete request.

join - One-to-many mapping in hibernate -

my levelterm.hbm.xml file is: <hibernate-mapping> <class name="com.entity.levelterm" table="level_term" catalog="test"> <id name="levelid" type="java.lang.integer"> <column name="level_id" /> <generator class="identity" /> </id> <property name="level" type="int"> <column name="level" not-null="true" /> </property> <property name="term" type="int"> <column name="term" not-null="true" /> </property> <property name="session" type="int"> <column name="session" not-null="true" /> </property> <list name="list_course"> <key column="level_id"/> <one-to-many column="course_code&qu

linux - How to execute a command inside a screen session -

i know how execute command inside screen session. searched , found : screen -s nameofscreen -x stuff "command" when type this, command typed inside screen not executed. queston how press enter using command. in bash shell can use ctrl-v explicitly put non-printable characters string. try ctrl-v ctrl-l ctrl-v ctrl-m @ end of command before " .

ios - SDWebimage to load image in custom UITableViewCell, but when scroll the image load in other cell random -

i have insert in uitableview custom uitableviewcell sdwebimage project, , load image: [cell.img_cell setimagewithurl:[self.url objectatindex:indexpath.row] placeholderimage:[uiimage imagenamed:nil] completed:^(uiimage *image, nserror *error, sdimagecachetype cachetype) {...}]; but when scroll uitableview image in 1 cell, goes in cell example doens't have loaded yet image, , continue effect cell scroll, , if scroll tableview fast cell have loaded right image first, change random said above, how can fix it? your table cells being reused scroll. means when image load finishes, cell might not "belong" original url anymore. what should set image nil in tableview:cellforrowatindexpath: clear out reused images , then cancel pending requests in tableview:didenddisplayingcell: , doesn't make efficient use of network bandwidth. a better approach move image loading code table controller (using sdwebimagemanager ) , have wait

Scala reflection and Squeryl -

i'm working on first substantial project using scala, scalatra, , squeryl, , happened upon following problem: wanted have abstract base class daos provided simple implementation of basic crud operations (create, read, update, delete), needed way said abstract base class aware of table reference. with squeryl, map data classes actual tables in singleton object extends squeryl.schema, , daos companion objects each class. i came following solution using type tags: first, excerpt of base class daos inherit (note: dbrecord sub of squeryl's keyedentity): abstract class crudops[s <: dbrecord](implicit tt: typetag[s]) { def create(item: s)= { intransaction{ val result = atschema.recordtable.insert(item) } } next, recordtable function in atschema: object atschema extends schema { val users = table[user] def recordtable[t <: dbrecord](implicit tt: typetag[t]): table[t] = tt.tpe match { case t if t =:= typeof[user] => users.asinstanceof

windows - Error installing apache with msiexec -

when installing httpd-2.2.25-win32-x86-openssl-0.9.8y.msi command: msiexec /i apache.msi installdir=c:\apache all works ok. command msiexec /i apache.msi installdir=c:\apache \qn it breaks. appears apache monitor, service not in there. same \qb , \quiet any idea? finally got work msiexec /i apache.msi /passive allusers=1 serveradmin=admin@localhost servername=localhost serverdomain=localhost serverport=80 installdir=c:\apache

java - Does the OpenJDK JVM have cache/buffers that may look like a memory leak? -

Image
i'm developing application runs on openjdk jvm , tracking memory usage. resident set size seems increasing on time. i'm wondering if there might buffering or caching going on inside jvm this, , if there is, how account figure out whether application leaking? this graph showing statistics collected on time. 1 causes alarm white 1 (it's plotted against right axis): graph of derivative of processes's memory usage. it's positive, means memory usage growing.

python - Continuously looping, unable to work out what's going wrong -

my code below isn't working how want to, i've tried comment little make easier. basically, want try maximum of 3 times access website , if successful exit loop , continue, if fails 3 times exit out of function. import random import urllib2 import httplib import urllib import mechanize def test(): ## 3 attempts... in range(0, 3): ## while in 3 attempts... while true: ## try... try: print "trying" ## proxy list proxy_list = {"no proxy": "none"} ## randomly chosen proxy proxy_number = random.choice(proxy_list.keys()) ## url post in order data. post_url = "" browser = mechanize.browser() browser.set_handle_robots(false) browser.addheaders = [('user-agent', 'firefox')] parameters = {""

Disable font smoothing with C# -

is there way enable/disable font smoothing in c#? mean 1 @ start -> display , performance options -> smooth edges of screen font. i need custom ocr code , enable while program running. well, know possible if create own fonts basing them on gdi log fonts. don't have actual c# code you, mention font class has ability use log font -- see various fromlogfont related methods. care, because using log fonts way this, following c++ q&a show changing font smoothing application alone , not global windows font smoothing settings

database design - How is this login table structure? -

the structure follows: for main login user: user_id | email_id | username | password | is_active | is_banned | last_login user_detail: uname | fname | lname | phone_no should move is_active , is_banned user_detail , checked once? i suggest follow asp.net's membership table structure. has 1 table holding user input (username, real name, phone, email, etc), , 1 table back-end login system (password, active, banned, etc). this way have tables divided out between functionality: 1 handles user account, other handles how/if can log in. however, reasonable keep user information in users table. for more information, see database normalization .

asp.net mvc - Issues converting types to new selectitemlist -

vs'12 asp.net c# mvc4 ef code first in controller var usernames = roles.getusersinrole("admin"); var adminusers = db.userprofiles .where(x => !usernames.contains(x.username)).tolist(); list<userprofiles> mylist = adminusers.tolist(); ienumerable<userprofiles> myenumerable = mylist; viewbag.ddlroles = myenumerable; the error coming view states the viewdata item has key 'ddlroles' of type 'system.collections.generic.list'1[[og.models.userprofiles, og, version=1.0.0.0, culture=neutral, publickeytoken=null]]' must of type 'ienumerable<selectlistitem>'. and have been trying convert query ienumerable<selectlistitem> crazy, if can me convert right way i'd appreciate alot. also if did not make clear, i'm doing taking list of users linq query not of "admin" roles , trying display them inside of dropdrownlist edit: the view @model og.models.userprofiles then later @

jquery - How to locate attachment of mouseover event Chrome Debugger -

i have ajax call refreshes product including image element. after refresh, product image magnifier not work. think because need reattach event on mouse on of image element. so, locate code mouse on event attached @ load time, can reuse code reattach event after ajax refresh. have little experience on client side programming , tools chrome developer. using chrome dev tool , event listener breakpoints/load, able stop code onload, however. info still unable locate callback function or location in code event being attached image element initially. how that? should for? there better tool or approach accomplish this? have @ visual event , sprymedia. implemented bookmarklet portable , can used on projects not have convenient access source files. from docs - visual event shows: which elements have events attached them the type of events attached element the code run event triggered the source file , line number attached function defined (webkit browsers , opera only).

algorithm - How to increment all values in an array interval by a given amount -

suppose have array of length l. given n intervals(i,j) , have increment values between a[i] , a[j].which data structure suitable given operations? intervals known beforehand. break intervals start , end indexes: s_i , e_i i-th interval starts including s_i , ends excluding e_i sort s_i -s array s sort e_i -s array e set increment 0 start linear scan of input , add increment everyone, in each loop if next s_i current index increment increment if next e_i index decement increment inc=0 s=<priorityqueue of interval startindexes> e=<priorityqueue of interval endindexes> for(i=0;i<n;i++){ if( inc == 0 ){ // skip adding zeros i=min(s.peek(),e.peek()) } while( s.peek() == ) { s.pop(); inc++; } while( e.peek() == ) { e.pop(); inc--; } a[i]+=inc; } complexity(without skipping nonincremented elements): o(n+m*log(m)) // m number of intervals if n>>m it's o(n) complexity when skipping elements: o( min

MongoDB - does document size matter when updating - pushing item to array? -

does document size matter when updating (pushing new item) nested array in document? i mean, have document historical data , know, days document charged new items often. should split document "historical data" , "today data" documents? reading not frequent update operation in case. example 700 updates while 20 reading per day. adding new document move document in disk if there adjust self make slower. reading less , think ok. if outgrow space, must moved on disk larger area. creating document padding in case insert , ok. http://docs.mongodb.org/manual/core/record-padding/

html - css styling table issue -

this question has answer here: css3's border-radius property , border-collapse:collapse don't mix. how can use border-radius create collapsed table rounded corners? 19 answers i have question regarding table style. i want have table radius 8px seems codes don't work. can me it? thanks! //ps need border-collapse. my jsfiddle http://jsfiddle.net/vfbtn/1/ try border-spacing: 0; instead of border-collpase. demo

eclipse adt - How to create an android library project with no resources -

i want create library project java/android classes - no resources. contain helpers io etc. have manually deleted resources etc - project here - wonder if can done out of box - or way not proper nb: need android classes - creating regular java project not option (?) edit : if there no out of box way there catch in deleting (edit: contents of the) res/ folder , support library ? appreciate 1-2-3 procedure you need keep project structure, incl. having res/ foder drawable/ etc, these folders can empty. there's no requirement library reference drawable. others suggest it's mandatory "app icon" library not need <application> entry in manifest, not need icon. same applies values/ , layout/ folders. library project have have these folders (as required build process), having no file in them (so keeping them empty) fine , valid , meets requirements.

c# - Linq List of Objects GroupBy Multiple Property Equality -

i have list<reportobject> , want able combine elements of list single element based on equality of properties 1 element matching other properties second element in list. in case, want update first element values second element , return list collection of "first elements". perhaps groupby (or linq in general) isn't right solution here, seem lot cleaner doing traditional foreach loop , newing second list. want this: list<reportobject> thelist = new list<reportobject>() { new reportobject() { property1 = "1", property2 = "2" }, new reportobject() { property1 = "2", property2 = "3" } new reportobject() { property1 = "1", property2 = "3" } }; list<reportobject> newlist = new list<reportobject>(); for(int = 0; < thelist.count; i++) { for(int j = + 1; < thelist.count; j++) {

javascript - I can't get the JQuery fading permalink to to show up on my posts -

i'm making tumblr theme , code got tumblr blog. div.fade { display: none; } and jquery. <script> //jquery fader code $(document).ready(function(){ settimeout(function(){ // slow can number of ms $("div.fade").fadein('slow', function () { // nothing }); }, 2000); // fade in after 2000 ms (2 secs) }); </script> here's fade div. <div class="fade"> <a href="{permalink}"><time datetime="{timeago}">{timeago}</time>&nbsp;/&nbsp; {block:notecount}<a class="notecount" href="{permalink}#notes">{notecountwithlabel}</a>{/block:notecount}&nbsp;/&nbsp; {block:contentsource} <a href="{sourceurl}">{lang:source}:{block:nosourcelogo}{sourcetitle}{/block:nosourcelogo}</a>&nbsp;/&nbsp; {/block:contentsource} <div class="my-like" data-reblog="{reblogurl}" data

javascript - store google custom search results in variable - php -

this question has answer here: reading google search results using php? 2 answers i need display results google custom search engine webpage, want store result in json , display according mycode. i have googled no success, can provide sample code? googling question worked me. this question has been asked answered here: https://stackoverflow.com/questions/7221335/how-can-i-fetch-google-search-result-from-php

node.js - Doing update on MongooseJS Schema Array that is using Populate -

i using mongoose population join documents var usersschema = schema({ username: string, password: {type: string, select: false }, fname: string, lname: string, role: string, apps: [ { //using populate here app: {type:objectid, ref: "applications"}, pinned: boolean } ] }, { collection : 'user' }); this being called this findbyid: function(id, items, callback){ user.findbyid(id, items , function(err, doc){ callback(doc); }).populate("apps.app"); } this works groovy. problem when want push in new app value being populated. doing. client: $.ajax({ type: "put", url: userurl + userid, contenttype: "application/json", data: json.stringify({ "app": currentapp.attributes._id,

Install Ruby 2.0.0-p247 with rbenv and erro in /tmp/ruby -

i'm trying install ruby 2.0.0-p247 rbenv , keep getting same error no matter do. here's command , response: ➜ ~ rbenv install 2.0.0-p247 downloading ruby-2.0.0-p247.tar.gz... -> ftp://ftp.ruby-lang.org/pub/ruby/2.0/ruby-2.0.0-p247.tar.gz installing ruby-2.0.0-p247... build failed inspect or clean working tree @ /tmp/ruby-build.20130823153529.15739 results logged /tmp/ruby-build.20130823153529.15739.log last 10 log lines: ./tool/rbinstall.rb:242:in `each' ./tool/rbinstall.rb:242:in `install_recursive' ./tool/rbinstall.rb:397:in `block in <main>' ./tool/rbinstall.rb:758:in `call' ./tool/rbinstall.rb:758:in `block (2 levels) in <main>' ./tool/rbinstall.rb:755:in `each' ./tool/rbinstall.rb:755:in `block in <main>' ./tool/rbinstall.rb:751:in `each' ./tool/rbinstall.rb:751:in `<main>' make: ** [do-install-all] erro 1

c# - How send a command to command prompt from a console application -

this question has answer here: passing argument cmd.exe 5 answers i have console application project. in application need start command prompt , pass argument command prompt. i have tried system.diagnostics.process.start("cmd", "shutdown -s"); but nothing starts command prompt what want start command prompt , pass argument command prompt "shutdown -s" how do that?. you want launch process directly: process.start("shutdown", "-s");

c - pthread_create int instead of void -

i have following code: for(i = 0 ; < max_thread; i++) { struct arg_struct args; args.arg1 = file; args.arg2 = word; args.arg3 = repl; if(pthread_create(&thread_id[i],null,&do_process,&args) != 0) { i--; fprintf(stderr,red "\nerror in creating thread\n" none); } } for(i = 0 ; < max_thread; i++) if(pthread_join(thread_id[i],null) != 0) { fprintf(stderr,red "\nerror in joining thread\n" none); } int do_process(void *arguments) { //code missing } * how can transform (void *)do_process (int) do_process ?* that function returns important info , without returns don't know how read replies i following error: warning: passing arg 3 of `pthread_create' makes pointer integer without cast the thread function returns pointer. @ minimum, can allocate integer dynamically , return it. void * do_process (void *arg) { /* ... */ int *result = malloc(sizeof(int));

objective c - iOS Simulator for Xcode 4.5 not copying Resources over -

i using xcode 4.5 , ios simulator version 6*. added images xcode project when simulate iphone, not showing up. see following in syslog: springboard[33587] <error>: cgcontextdrawimage: invalid context 0x0. serious error. application, or library uses, using invalid context , thereby contributing overall degradation of system stability , reliability. notice courtesy: please fix problem. become fatal error in upcoming update. aug 23 15:04:18 new-host-22.home springboard[28968] <warning>: no file exists default image of name starting_image_i5_retina aug 23 15:04:20 new-host-22.home[28982] <notice>: bug in libdispatch: 12e55 - 866 - 0x2 aug 23 15:04:20 new-host-22.home[28982] <notice>: bug in libdispatch client: kevent[evfilt_vnode] add: "bad file no idea happening. have tried deleting app, clean builds, etc. go build phases under target , go "copy bundle resources" , click plus button , add file, clean build, delete app, , run in xc

javascript - How to apply a jQuery function to a child page in an iframe? -

here's brainteaser: i have iframe in window, , navbar links it: <div class="nav"> <a href="link.html" target="iframe-content" id='debug">#debug<a> </div> <iframe name="iframe-content" src="page.html"></iframe> i've got simple jquery function inset class when link in nav clicked. $(window).load(function() { $("#debug").click(function() { $('body').toggleclass("debug"); }); }); now question how toggleclass apply inline frame (page.html) , not parent page? change $('body').toggleclass("debug"); to $('#debug').contents().find('body').toggleclass("debug"); check out jquery documentation .contents()

visual studio 2008 - Encrypt strings in pure C in order to hide them in the executable -

i trying avoid literal strings appearing in executable. want put string encrypted in executable , decrypt , use @ runtime. read bit how hide string in binary code? , http://bytes.com/topic/c/answers/222096-hiding-string-compiled-code , not want. could done using macros? example, can declare wide char string using wchar_t str[] = l"value" or wchar_t *str = l"value" and magical l convert chars widechars. possible create magical l make encrypted strings? e.g: enc"value" for moment defining encrypted strings macros: #define sample_string "ftnurd eru etrth" /*random chars imitating encryption*/ and passing them normal function like char *decstr(char *data) is there easier method this? i using windows xp sp3 visual c++ 2008 express. why not create encryption , decryption function? write like char *hidden_password = my_encrypt("passw0rd"); puts(hidden_pasword); // "acud5ttei23w8

Subprocess module from python fails to run bash commands like "<cmd1> | <cmd2>" -

the following python script: #!/usr/bin/env python import os cmd = "echo hello world | cut -d' ' -f1" test=os.system(cmd) print(test) it runs ok (the output hello ). when use subprocess module one: #!/usr/bin/env python import subprocess cmd = "echo hello world | cut -d' ' -f1" process = subprocess.popen(cmd.split(), stdout=subprocess.pipe) test = process.communicate()[0] print (test) is not ok. output hello world | cut -d' ' -f1 , expect hello . how can correct it? i saw in general subprocess module fail when i'm using bash command like: <cmd1> | <cmd2> this: echo hello world | cut -d' ' -f1 … not command, it's fragment of shell script. need have shell execute it. you can adding shell=true popen constructor. the documentation explains how works. explains better ways same thing without shell . example: p1 = popen(['echo', 'hello', 'world'], stdout

cordova - Phonegap 3.0 iOS Generic Push Plugin -

i trying make phonegap 3.0 application push notifications cannot plugin everywhere telling me use work. generic push plugin here: http://phonegap.com/blog/build/introducing-genericpush-plugin/ i have added javascript index when try , run .register function not work. please help. i expect plugin not yet ready phonegap 3. i'd suggest use phonegap 2.9 until is. as running ios, i'd recommend follow tutorial: http://www.adobe.com/devnet/phonegap/articles/apple-push-notifications-with-phonegap.html and setting push settings in app use one: http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1 don't forget, have use app on real device, push notifications don't work in emulator.

dynamic - Is device memory allocated using CudaMalloc inaccessible on the device with free? -

i cannot deallocate memory on host i've allocated on device or deallocate memory on device allocated on host. i'm using cuda 5.5 vs2012 , nsight. because heap that's on host not transferred heap that's on device or other way around, dynamic allocations unknown between host , device? if in documentation, not easy find. it's important note, error wasn't thrown until ran program cuda debugging , memory checker enabled. problem did not cause crash outside of cuda debugging, would've cause problems later if hadn't checked memory issues retroactively. if there's handy way copy heap/stack host device, that'd fantastic... hopes , dreams. here's example question: __global__ void kernel(char *ptr) { free(ptr); } void main(void) { char *ptr; cudamalloc((void **)&ptr, sizeof(char *), cudamemcpyhosttodevice); kernel<<<1, 1>>>(ptr); } no can't this. this topic covered in programming guide here

multithreading - Java - Filling an ArrayList of Threads with loop -

this question pretty easy answer don't it. reduced problem until little piece of code left in order find "origin" of problem: i'm trying fill arraylist of threads loop. public static int u=0; public void test(){ while (u <10) { synchronized(threadlist){ threadlist.add(u, new thread(){ @override public void run(){ system.out.println("thread @ index: " + u); } }); } u++; } threadlist.get(2).start(); } with last line wanted test loop above starting thread @ index '2'. i'm expecting console show "thread @ index: 2" instead shown: "thread @ index: 10" no matter integer write in ".get(int)"-method, receive index '10'. why that? , how fix this? the creation of threads seems work...so integer 'u' problem? i

Deployed Scaffold rails app to Heroku. "heroku open" gives "page you were looking for doesn't exist" -

windows 7, re-installed latest rails version railsinstaller.org today. "heroku push" successful. db migration successful. "heroku open" gives "page looking doesn't exist" i've deployed before using rails 4 , didn't have problems. today. please help! thanks log: 2013-08-23t21:15:17.504964+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/content_length.rb:14:in `call' 2013-08-23t21:15:17.504964+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/webrick.rb:60:in `service' 2013-08-23t21:15:17.504807+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/railties-4.0.0/lib/rails/rack/logger.rb:38:in `call_app' 2013-08-23t21:15:17.504807+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/railties-4.0.0/lib/rails/rack/logger.rb:21:in `call' 2013-08-23t21:15:17.504964+00:00 app[web.1]: vendor/bundle/ruby/2.0.0/gems/actionpack-4.0.0/lib/action_dispatch/middleware/request_id.rb:21:

javascript - Jquery: Toggle not working -

i have html page structure this: <div class="editable>content <span class="multiple-users">span-content</span> <span class="multiple-users">span-content2</span> <span class="multiple-users">span-content3</span> </span> when click on span element class "multiple-users", want replace in div of class "editable" content of clicked span. , when click on content of clicked span, want revert original form, replacing in div. here have: $(document).ready(function () { $('span.multiple-users').click(function () { var id = $(this).text().match(/[0-9]+/); var old_html = $(this).closest('div.editable').html(); var instructor_obj = $(this).closest('div.editable'); instructor_obj.html("<span id=" + id + " >instructor id: " + id + "</span>"); $('#' + id).clic

c++ - QGLWidget maximum size -

i have qt application using opengl drawing qglwidget , on mac os. on mbp works well, when trying on 30" screen, noticed there window size limit. if increase window size beyond limit, qglwidget 's content disappears , greyish memory junk visible. i changed code put qglwidget on screen. repaint event setting background black in each iteration. issue still visible: when resizing widget, black surface disappears , gets replaced memory junk, when size of widget reaches size. interesting facts: when decrease window size, gl surface comes live again i have several other gl applications (not qt) running in maximized window, issue not opengl driver/video card it seems area of window (nr of pixels) matters, if make window wide, it's height limited , vica versa, if windoe maximized in height, width must small i found while instantiating qglwidget using qglformat(qgl::nosamplebuffers) instead of qglformat(qgl::samplebuffers) solves issue.

xaml - How can i use ListPicker with Page that use App Bar? -

when try use "app bar" page had "listpicker" , listpicker disappearing ?! list picker: <toolkit:listpicker x:name="listpicker" itemtemplate="{staticresource pickeritemtemplate}" fullmodeitemtemplate="{staticresource pickerfullmodeitemtemplate}" header="sound" fullmodeheader="choose item" cachemode="bitmapcache" /> app bar : <phone:phoneapplicationpage.applicationbar> <shell:applicationbar isvisible="true" ismenuenabled="true"> <shell:applicationbariconbutton iconuri="/images/appbar/save.png" text="add" click="applicationbariconbutton_click"/> </shell:applicationbar> </phone:phoneapplicationpage.applicationbar> can bit more specific problem is? it's not clear. if you're talking listpicker not showing up, it's issue rest of xaml , how inserted items. knowledge t

debugging - Equivalent of a debug macro in Java -

this question has answer here: #ifdef #ifndef in java 7 answers i'm writing program reads structures file. debugging purposes, convenient if have compile-time toggle prints names , values of read disabled better performance/code size in production version. in c, use preprocessor such accomplish this: #ifdef debug #define read(name, in) { name = read(in); printf("#name: %d\n", name); } #else #define read(name, in) { name = read(in); } #endif void myreader(mystream_t *in) { int a, b, c; read(a, in); read(b, in); read(c, in); } is there way can reproduce construct? thought this: private static final boolean debug_enabled = true; private int debugread(myinputstream in, string name) { int val = in.read(); if (debug_enabled) { system.out.println(string.format("%s: %d", name, val)); } return val;

strange behaviour of procmail when piping content to c++ executable -

i have working procmail config. rc.filters : :0 w :a.lock * ^from:(.*\<)?(try@gmail\.com)\> | $home/executable/a.out this file compiles , works, procmail delivers mail, , executable writes content output file. #include <stdlib.h> #include <iostream> #include <fstream> using namespace std; int main(void) { ofstream myfile; myfile.open ("output.txt"); string line; while (getline(cin, line)) { myfile << line << endl; } myfile.close(); return exit_success; } the problem need cin object content pass constructor of mimetic library. need executable work: #include <stdlib.h> #include <iostream> #include <fstream> #include <mimetic/mimetic.h> using namespace std; using namespace mimetic; int main(void) { ofstream myfile; myfile.open ("output.txt"); mimeentity me(cin); const header& h = me.header(); string subjectstring = h.sub

php - How to only allow certain number of forward slashes using regular expression? -

i'm routing application , i'd allow maximum of 2 directory subpaths following directory path of tags/ . hyphens , alnums allowable characters. the following validate , bolded below returned router single match: tags/ how-to-bake tags/ how-to-bake/cookies if there more 2 subpaths (or 2 or more slashes, in other words) router should return no match. my server redirects on trailing slashes (to non-trailing slash url) don't need taken consideration. i'm using tags/([\w+\-\/]+)$ allow infinitely many subpaths, , forced check subpath length (forward slash count) after router returns match. i'm not sure how can allow 0 or 1 forward slashes in character set wrote, while having word characters possibly follow, , have them returned single match. is possible regular expression? barmar's solution answers question perfectly... version taking in account trailing slash in path's expression: (tags\/[-\w]+\/?(?:[-\w]+)?(?<!\/)\/?)$ re

windows - C++ executable size using MinGW -

i writing in c sizecoding demo-making competition (64kb) considering moving c++. under mingw g++ have trouble .exe-size. (before using executable-packers, have down <100 kb.). i have looked @ this: how reduce size of executable produced mingw g++ compiler? already using mingw/g++ 4.8.1 , -s -os ... see below (and 4.8.1 too: unrecognized option '-shared-libstdc++' , cannot find -lstdc++_s ). this little helloworld has 10 kb (which ok): #include "windows.h" int main() { messageboxa(0, "test", "test", 0); return 0; } however when add: #include <string> ... std::string asdf; it becomes 193 kb and when add: #include <iostream> then becomes 756 kb. i using these flags: -std=c++11 -wall -s (or -wl,-s) -os -dndebug -fno-exceptions -fno-rtti (note: removed no effect) there has way link use. missing? optional 1: possible -shared-libstdc++ or -lstdc++_s working in mingw/g++ 4.8.1?

how to run a java program at background from chef recipe -

i chef rookie. want create recipe run jar @ background. bash 'run_jar' code <<-eoh wget https://github.com/kiwiwin/jar-repo/releases/download/kiwi/helloworld-1.0.jar -o hello.jar java -jar hello.jar & eoh end the helloworld-1.0.jar program first print "hello world", execute while(true) loop. i expect when login chef-client machine. should indicate there jar running using "jps" command. there no such jar running. and can see hello.jar downloaded indicates code block has been executed already. what's wrong recipe? you best advised configure code run service. several wrappers available, example: http://wrapper.tanukisoftware.com/doc/english/app-hello-world-server.html once done can configure chef manage new service: service "myapp_service" supports :status => true, :restart => true start_command "/usr/lib/myapp/bin/myapp start" restart_command "/usr/lib/myapp/bin/m

node.js - My model isn't creating objects and failing silently -

i'm running standard geddy setup mongo . routes: router.get('/submit').to('urls.add'); router.post('/create').to('urls.create'); controller: // invokes form submitting new url // sends form output create function this.add = function (req, resp, params) { this.respond({params: params}); }; // creates new url object , saves database this.create = function (req, resp, params) { var self = this; var timestamp = new date().gettime(); var url = geddy.model.url.create({ title: params.title, url: params.url, score: 0, created: timestamp }); url.save(function(err, data) { if (err) { params.errors = err; self.transfer('add'); } else { this.redirect({controller: 'url.index'}); } }); }; model: var url = function () { this.defineproperties({ title: {type:'string', required:true}, u

PHP String: remove "\newline" after "\end{Figure}" -

i've php string of around 4000 chars; if anywhere in php string $input1, $input2 or $input3 identified, want replace same $output string. in summary want remove "\newline" after "\end{figure}" $input1 = "\end{figure}\newline"; $input2 = "\end{figure} \newline"; $input3 = "\end{figure}\newline " required output: $output = "\end{figure}"; can please suggest how achieve required output? your question not clear, perhaps looking for: $result = preg_replace('~\\\end\{figure}\k( )?\\\newline(?(1)| )~', '', $text); pattern details: ~ # pattern delimiter \\\ # backslash (must double escaped inside quotes) end\{figure} \k # reset begining of match ( )? # optional capturing group n°1 \\\newline (?(1)| ) # if capturing group n°1 exists there nothing else space ~

node.js - How to prevent race conditions in a distributed nodejs web servers architecture backed by mongodb -

here' s description of problem: i have x web workers written in nodejs (express.js) behind load ballancer. these workers write data mongodb (mongoose.js) i've setup endpoint y such @ point in middleware chain of handler i'm doing following logic: if requesting user exists in database, fetch it, update fields store back. if doesn't exist, insert in mongo. note! i'm unable use mongoose's findandupdateone() - atomic - due domain specific logic, ie. if user exists update value, else insert value. the problem is, quite often, 2 requests same user (who doesn't yet exist in db) hit 2 different workers. when user processing middleware kicks in, both workers determine user doesn't exist , attempt insert update it. naturally causes errors, eg. validation errors: i've setup unique email per user validation , others. how can prevent this? you can use $set , $setoninsert update operators achieve that. from mongodb $setoninsert docs :

linux - Copying file from ssh server to mac? -

this question has been repeated many times , know copy file ssh server mac should follow this: copy file "foobar.txt" remote host local host $ scp your_username@remotehost.edu:foobar.txt /some/local/directory but want know how can copy local machine after connecting remote ssh. meant after connecting ssh means in terminal connect ssh , copy them pc. want 1 time connect ssh , enter password , operation. why? because writing user friendly program ask password 1 time , don't want user enter every time or save password. you're trying reuse existing ssh connection. add ~/.ssh/config set automatical connection sharing: controlmaster auto controlpath ~/.ssh/control:%h:%p:%r now, if do scp your_username@remotehost.edu:foobar.txt /some/local/directory and if have connection established in terminal wont ask password , connection established quickly.

html5 - Unexpected entry in a <select> field! How did this happen? -

in 1 of forms on website, have <select> field this: <select name="doorno" required> <option></option> <option>01</option> <option>02</option> <option>03</option> <option>04</option> <option>05</option> <option>06</option> <option>07</option> <option>08</option> <option>09</option> <option>10</option> <option>11</option> <option>12</option> <option>13</option> <option>14</option> <option>15</option> <option>16</option> <option>17</option> <option>18</option> <option>19</option>