Posts

Showing posts from April, 2013

Silverlight vs WPF - Treeview with HierarchialDataTemplate -

so, following easy enough in wpf, how in silverlight? please note trick here display both groups, , entries on same level. additonally dont know how deep entries nested, might on first, or nth level. hard in silverlight because lack datatype="{x:type local:group}" property in h.datatemplate (or datatemplate). building own custom datatempalteselector didnt work, because hierarchial itemssource gets lost. (which gave me new idea investigate shortly) example: group1 --entry --entry group2 --group4 ----group1 ------entry ------entry ----entry ----entry --entry --entry group3 --entry --entry your classes: public class entry { public int key { get; set; } public string name { get; set; } } public class group { public int key { get; set; } public string name { get; set; } public ilist<group> subgroups { get; set; } public ilist<entry> entries { get; set; } } your xaml: <treeview name="groupview" grid.row=

internet explorer 7 - CSS drop-down being overlapped by content in IE7 -

i'm having issue in ie7 drop down. whenever hover on dropdown goes hover on element on top of content. http://www.legrandconfectionary.com/gift-boxes/ i thought position: relative on header solve problem on pages truffle flavors have tooltip effect goes under nav if done so. i'd appreciate on this. thanks! there several ways can fix this. here's two: set a tag display: block , , make hover events based on a instead of li . or specify height other auto or 100% li 's

ruby - Rails ActiveRecord::Migration - writing a textfile contents to the database -

i'm doing unorthodox here, in i'm populating database via migration, , using contents of textfile. i'm using following method doesn't import entire file, can suggest solution this?: class addchapters < activerecord::migration def self.up chapter.create!(:title => "chapter 1", :body => file.open("#{rails.root}/chapters/chapter1.txt").gets) chapter.create!(:title => "chapter 2", :body => file.open("#{rails.root}/chapters/chapter2.txt").gets) chapter.create!(:title => "chapter 3", :body => file.open("#{rails.root}/chapters/chapter3.txt").gets) end def self.down chapter.all.each |chapter| chapter.delete end end end there number of problems @ work here. the first 1 check body field in table has sufficient length hold contents of text files. also, gets might not you're after. rdoc: reads next ``line’’ i/o stream; lines separated sep_

jquery - Create Rails Proxy for JSON -

i want asynchronously query foursquare api, not allow old $.get(). short term solution make helper gets data so: def foursquare_info_for(venue_id) res = net::http.get_response("api.foursquare.com", "/v1/venue.json?vid=#{venue_id}") data = json.parse(res.body) info = hash.new info["mayor_name"] = "#{data['venue']['stats']['mayor']['user']['firstname']} #{data['venue']['stats']['mayor']['user']['lastname']}" info["mayor_photo_src"] = "#{data['venue']['stats']['mayor']['user']['photo']}" info["checkins"] = "#{data['venue']['stats']['checkins']}" info end that works, i'd rather make proxy can jquery ajax request after page loads speed things bit. i'm pretty sure helper close need proxy working, i'm not sure need put proxy

How do I modify my Python image resizer code to do this? -

when resize picture smaller desired, want image not resized...but instead in center, white padding around it. so, let's have icon that's 50x50. want resize 100x100. if pass function, return me same icon centered, white padding 25 pixels on each side. of course, i'd work images of width/height, , not square example above. my current code below. i don't know why did if height=none: height=width ...i think because worked when did before. def create_thumbnail(f, width=200, height=none): if height==none: height=width im = image.open(stringio(f)) imagex = int(im.size[0]) imagey = int(im.size[1]) if imagex < width or imagey < height: return none if im.mode not in ('l', 'rgb', 'rgba'): im = im.convert('rgb') im.thumbnail((width, height), image.antialias) thumbnail_file = stringio() im.save(thumbnail_file, 'jpeg') thumbnail_file.seek(0) return thumbnail_file

Host a Delphi 7 application process in .net -

hi! i'm trying host delphi 7 vcl application in .net wpf application. works great except modal dialogs not behave modal dialogs, parent window isn't disabled. code far: class mysimpledelphihost : hwndhost { private process _appproc; public intptr hwndhost; protected override handleref buildwindowcore(handleref hwndparent) { _appproc = new process(); _appproc.startinfo.windowstyle = processwindowstyle.hidden; _appproc.startinfo.filename = @"mysimpledelphiapplication.exe"; _appproc.start(); thread.sleep(1000); hwndhost = win32api.findwindow("tmainform", null); int oldstyle = win32api.getwindowlong(hwndhost, win32api.gwl_style); win32api.setwindowlong(hwndhost, win32api.gwl_style, (oldstyle | win32api.ws_child) & ~win32api.ws_border); win32api.setparent(hwndhost, hwndparent.handle); win32api.showwindowasync(hwndhost, win32api.sw_

android - How should I be using .setAdapter here? /How do i get around not extending ListActivity? -

i have class extending tabactivity can't extend listactivity. this hasn't problem until needed use method: private static int[] = { r.id.catitem, r.id.budgetamount, }; private void showbudgetoutcome(cursor cursor) { //set data binding simplecursoradapter adapter = new simplecursoradapter( this, r.layout.itemsforbudgetlist, cursor, from, to); setlistadapter(adapter); } obviously setlistadapter undefined. found snippet of code searching so mlistview.setadapter(new arrayadapter<string>(this, r.layout.list_item, countries)); but don't understand parameters. tried altering suit me: incomeview.setadapter(new simplecursoradapter<string>(this, r.layout.itemsforbudgetlist, adapter??)); i see mlistview users listview replaced that, , layout resource defining how each item in list looks guess. rest i'm not sure about. figure maybe want simple/cursoradapter since i'm working sqlite (see method)? have no idea countries meant , not sure data type n

iphone - is it allowed for location based app to transmite location data to remote server while working on the background? -

i read in iphone 4 book location based apps not allowed transmite location data remote server while working on background, true ? , information in apple term of service or documentation ? these 2 questions may : nsurlconnection , multitasking in ios iphone background network connection timer

c# - Could not load assembly exception when using Assembly.LoadFile -

here's scenario: i have 3 projects: 2 dlls , 1 console application, let's name them foo.dll, bar.dll , console.exe. console.exe loads foo.dll using assembly.loadfile(@"c:\foo.dll"). foo.dll's project has reference bar.dll , makes use of class. console.exe loads foo.dll fine, problem occurs when foo.dll tries use bar.dll's class. "could not load assembly: "bar.dll" blah blah exception. some points: all projects strong named would prefer not use gac bar.dll in c:\bar.dll so in same local directory, correct dlls being referenced (via project properties, , i've used reflector make sure assembly versions correct). if install bar.dll gac works expected. i think has assembly.loadfile call, , making hop second dll, i'm not sure. thanks time , input. assembly.loadfile() should ever used in special circumstances. assembly doesn't have loading context, that's why bar.dll cannot found. real use case tooling, pr

asp.net mvc - automapper, On Create action on the controller. Confused -

i have everthing set automapper work. attribute working fine , filling dto. controller create action looks below [httppost] [automap(typeof(user), typeof(usercreatedto))] public actionresult create(user user) { if (modelstate.isvalid) { _repository.create(user); return redirecttoaction("details", new { id = user.userid }); } return view("edit", user); } i have dataannotation set on user object entity object , passed repository interface via implementation , using user object everywhere. what want below using same above code. [httppost] [automap(typeof(user), typeof(usercreatedto))] public actionresult create(usercreatedto userdto) { if (modelstate.isvalid) { _repository.create(userdto); return redirecttoaction("details", new { id = userdto.userid }); } return view("edit", userdto); } question: dataannotation on usercreatedto limit want validate. once validation

arrays - How to use a variable list as a target in a Makefile? -

suppose working on makefile , have following variable declaration @ top: files = file1.cpp file2.cpp file3.cpp now suppose want compile each of special command without specifying each target this: file1.o : file1.cpp custom_command file1.cpp file2.o : file2.cpp custom_command file2.cpp file3.o : file3.cpp custom_command file3.cpp is there better way using $(files) variable declared above? something like: $(files:.cpp=.o) : $(files) custom_command $(files) ...only needs each file in $(files) variable. yes. there known pattern rules . example easiest understand: %.o: %.cpp $(cc) -c $(cflags) $(cppflags) $< -o $@ (remember makefiles require tabs). rule describes how make object file cpp file. if not want such broad rule, can use called static patterns: objects = file1.o file2.o file3.o all: $(objects) $(objects): %.o: %.cpp $(cc) -c $(cflags) $(cppflags) $< -o $@ here's section on static pattern rules , pa

Merge two object literals in javascript -

i have 2 object literals: var animal = { eat: function() { console.log("eating..."); } } var dog = { eat: "this has replaced when merged", nroflegs: 4 } need merging function this: dog = somemergingfunction(animal, dog); that produces: { eat: function() { console.log("eating..."); }, nroflegs: 4 } one of object literals has replace identical properties. how do in javascript? // usage merged = somemergingfunction(a, b, c, d, ...) // keys in earlier args override keys in later args. // somemergingfunction({foo:"bar"}, {foo:"baz"}) // ==> {foo:"bar"} function somemergingfunction () { var o = {} (var = arguments.length - 1; >= 0; --) { var s = arguments[i] (var k in s) o[k] = s[k] } return o }

c++ - How to detect const reference to temporary issues at compile or runtime? -

i've found of errors in c++ programs of form following example: #include <iostream> class z { public: z(int n) : n(n) {} int n; }; class y { public: y(const z& z) : z(z) {} const z& z; }; class x { public: x(const y& y) : y(y) {} y y; }; class big { public: big() { (int = 0; < 1000; ++i) { a[i] = + 1000; } } int a[1000]; }; x get_x() { return x(y(z(123))); } int main() { x x = get_x(); big b; std::cout << x.y.z.n << std::endl; } output: 1000 i expect program output 123 (the value of x.y.z.n set in get_x()) creation of "big b" overwrites temporary z. result, reference temporary z in object y overwritten big b, , hence output not expect. when compiled program gcc 4.5 option "-wall", gave no warning. the fix remove reference member z in class y. however, class y part of library have not developed (boost::fusion recently), , in addition situation more complicated example i've given. this

app engine task queue wait limit -

how long can task sit in task queue waiting processed before happens? if not forever, somethings might happen? can add large number of tasks queue has low processing rate , have them processed on course of days/weeks/months? are tasks ejected queue if they're waiting turn long? task queue quota , limits says maximum countdown/eta task:30 days current date , time i think that's talking intentionally/programatically setting eta in future, not how long task allowed wait turn. there's no limit on how many tasks can have in queue, other amount of storage have allocated storing tasks. there's likewise no limit how long can wait execute, though point out, can't schedule task eta more 30 days in future.

asp.net - How to set always default value for first record in list view in aspx page? -

i have aspx page uses simple form perform search , results presented in listview. i have added radio button 1 of columns , have set value records flightno. set default value first record in list view. what need allow user select row require list view selecting radio button. use "groupname" property of radio button control make dynamic radio buttons work group. can add client script select row on 'click'.

google app engine python log level noise reduction -

does know how reduce verbosity of logging output dev_appserver.py ? the noise level of these logs driving me crazy. know how kind of config in java log4j, lost here on google app engine python. solution 1. you can instruct logging library log statements @ or above given level logging.setlevel() . if set level threshold higher level contains messages don't want you'll filter out unwanted messages dev_appserver. to make log messages show up, need 1 of following: ensure logging messages logged @ least @ filtering out threshold set above (probably warn ). configure , use own custom logger . can control logging level logger independently of root logger used dev server. solution 2. the workaround above little annoying because either have avoid debug , info levels, or have use create own logger. another solution comment out offending log messages dev_appserver.py (and related modules). quite pain hand, i've written tool replaces logging calls i

lisp - Error Emacs slime: eval-buffer: Symbol's function definition is void: define-slime-contrib -

i'm using emacs lisp (using slime) short time...this work today when run appear message: eval-buffer: symbol's function definition void: define-slime-contrib means slime contrib folder not found? my .emacs disaster..sorry this...i search inside folders , well... ;; slime ================================================== ' ;; orden: m-x slime (setq inferior-lisp-program "/usr/bin/clisp") ; (add-to-list 'load-path "/usr/share/emacs/site-lisp/slime/") ;;(require 'slime-autoloads) (add-to-list 'load-path "/etc/emacs/site-start.d/") ;; review folders , (add-to-list 'load-path "/usr/lib/emacsen-common/packages/install/") ;; address (add-to-list 'load-path "/usr/share/doc/slime/") (add-to-list 'load-path "/usr/share/emacs/site-lisp/") (add-to-list 'load-path "/usr/share/emacs/site-lisp/slime/") (add-to-list 'load

stream - On-the-fly video streaming over http? -

i'm building application serve video files users on variety of different platforms. such, need ability set server serve video files might need transcoded number of different formats. basically, want replicate functionality tversity provides. the ideal solution allow me access video stream via http, specifiying sort of transcoding parameters in call. anyone have ideas? thanks! chris http not streaming protocol. have @ progressive download - there lots of php implementations / flash players available. ffmpeg tool converting formats / size / frame rates etc.

actionscript 3 - How to load image in Action Script? -

how load image in action script ? i have used following code image not loaded.`var ldr:loader = new loader(); var url:string = "d:\blackberry\workspace\soundtest\blackberry-tablet-icon.png.bmp"; var urlreq:urlrequest = new urlrequest(url); ldr.load(urlreq); addchild(ldr); stage.nativewindow.visible = true;` please ? you need check errors loader gives: ldr.contentloaderinfo.addeventlistener(ioerrorevent.io_error, onerror); ldr.contentloaderinfo.addeventlistener(httpstatusevent.http_status, onstatus); function onerror(e:ioerrorevent):void{ trace(e); } function onstatus(e:httpstatusevent):void{ trace(e); } now can filter errors out , search on web specific arrow loader gives. i guess security error. flash prevents load images outside domain(exception debug version in flash cs5) http://help.adobe.com/en_us/flashplatform/reference/actionscript/3/securityerror.html

cross browser - How to embded a SWF on a HTML page? -

i trying while display correctly swf project in html file integration in browser. the swf there : http://bitbucket.org/natim/cip-qcu-editor/raw/4746bbb86427/qcu/swf/quiz.swf , tried using method : http://latrine.dgx.cz/how-to-correctly-insert-a-flash-into-xhtml , 1 : http://www.bobbyvandersluis.com/swfobject/generator/index.html without success. actually works not firefox 3.6 doesn't start animation. do have idea of how can make works ? thanks i finaly used swfobject : <html> <head> <title>qcu - cip utbm &copy; 2010</title> <meta name="author" content="rémy hubscher"/> <style type="text/css"> * { margin: 0; padding: 0; } html, body { width: 100%; height: 100%; background-color: #3f3fff; } div, object { width: 100%; height: 100% } </style> <script type="text/javascript" src="js/swfobject.js"></script> </hea

java - Log4j DailyRollingFileAppender vs ConsoleAppender performance -

we're using log4j v1.2.14. we're using org.apache.log4j.consoleappender , we've requirement/need have daily rotating logs in place. hence, we're planning use org.apache.log4j.dailyrollingfileappender have daily rotating logs. my question is, dailyrollingfileappender additional overhead/have performance impact on consoleappender, because has additionally check whether file has rotated/rollover in each print statement? any opinions/user experience appreciated. your arguments correct , logic dictates overhead/performance impact exists. how much? should measure if you're afraid of performance hit. it depends on how many logging statements have. lots of debugging statements worst because can impact performance, unless using guards of type logger.isdebugenabled() . if can afford it, i'd suggest switching slf4j logback underlying implementation. logback's main focus speed , seems go great lengths make sure it's faster other logging s

java - What code changes are automatically reflected in eclipse in debug mode? -

i use eclipse (to write, debug ) ide. in debug mode when make changes,like initializing local variable, reflected automatically. but other changes changing value of static variable; message saying need restart vm , don't. now question sort of changes automatically reflected , doesn't. i use remote debugging, there difference when running program eclipse? it not ide feature, vm feature of remote debugging. vm can handle simple changes in logic inside methods of variable initializers, can't treat changed class structure. the reloading treated normally, when class structure doesn't change: don't remove or add members, methods or inner classes, because adding members or inner classes changes size of allocated class memory. methods doesn't change memory size, changes structure. here can find explanations.

c++ - Opening database in invalid location causes memory leak -

i using qt 4.5.3 access sqlite database, : class db : private boost::noncopyable { public: db( qstring file ) : filename( file ), realdb( null ), theconnectionestablished( false ) { } ~db() { if ( null != realdb.get() ) { realdb.reset( null ); } if ( theconnectionestablished ) { qsqldatabase::removedatabase( "connname" ); } } void open() { realdb.reset( new qsqldatabase( qsqldatabase::adddatabase( "qsqlite", "connname" ) ) ); theconnectionestablished = true; // open db realdb->setdatabasename( filename ); if ( ! realdb->open() ) { const qsqlerror dberror = realdb->lasterror(); const qstring errordesc = "error opening database : " + filename + "\ndatabase error : " + dberror.databasetext() + "\ndatabase driver er

erlang - Ordering of mnesia events -

we’re developing application multiple processes on different nodes in distributed system subscribe mnesia events. table written 1 single process on 1 of nodes. however uncertainty has arose if can sure receive events in same order operations on table. e.g: mnesia:delete(tab1, somerec), mnesia:write(tab1, someotherrec) if delete event after write event our design not work , have create other kind of notification mechanism. also, how operations on different tables (from same process)? mnesia:write(tab1, somerec), mnesia:write(tab2, someotherrec) can sure event tab1 before 1 tab2? on processes , nodes? thanks, jens for erlang whole, sending of messages process a process b guaranteed in order. however, messages between more 2 processes, can not guarantee messages sent a b arrive before messages sent c b , if a 's messages globally sent first. scheduler, network latency or network problems (especially if a , c aren't on same node) might examples o

setInterval not working for ajax call -

i have getjson call webservice , works fine, i'm trying make request every 10 sec. using setinterval callback function fire alert pop up. can't make work. here's code: function ajxcall(){ $.getjson('http://api.tubeupdates.com/?method=get.status&lines=all&return=name,status,messages,status_starts&jsonp=?', function (result){ $.each(result.response.lines, function(i, item){ $('#status').append("<p>"+item.name + " - " + item.status + " <br><b>" +item.messages + "</b> " + item.status_starts + "</p>"); }); }); } setinterval(ajxcall(), (10 * 1000), function(){ alert('called!') }); what doing wrong? thanks in advance, mauro setinterval(function() { ajxcall(); }, 10000); try that

objective c - Accidently deleted iPhone from Organizer in Xcode -

i accidently deleted iphone device section in organizer (in xcode). how back? thanks! does not re-appear when plug phone in? reboot , try again. ok have problem. :)

c# dllimport question -

i iporting method external dll , have following code: [dllimport("test.dll", charset = charset.unicode, setlasterror = true)] public static extern tabpage creategui(); and call this: tabcontrol1.tabpages.add(creategui()); i error saying creategui cannot located within dll. creategui method has been declared public , static within dll? ideas? thanks. if method returns tabpage .net method, hence .net assembly. should not import dllimport, add dll reference in project. edit: if want load .net assembly dynamically need load assembly.loadfile , find types assembly.gettypes .

iphone - Aligned pointer -

possible duplicate: what 'aligned pointer' ? please give me example of statement: a normal pointer type implicitly cast aligned pointer type. actually c language question i don't believe can cast them. pointers aligned normal . have declare __packed un-aligned. you should read on how arm processor works. alignment causes quick memory access. if need things packed further, recommend storing data blob in nsdata or using c-style byte[] array. also, see question/answer. , this one.

Advantage of 'one dimensional' hash over array in Perl -

i wondering efficiency of using 1 dimensional hash (i.e. keys, no values - don't care them anyway) on 1 dimensional array. the main reason wanted use hash purpose can use exists function see if 'entry' exists. hashes great not duplicating keys right? arrays, need set own checks involving grep i'm led believe slower. this hash/array iterated through operations. i'd love hear insight on this, , in advance! exists $hash{ $key } is nice, short expression, clear , easy use. !!grep { $_ eq $key } @array is not quite short, $key ~~ @array # smart match is shorter. since 5.10, syntactically easy test smart match exists . so guessing performance difference between arrays , hashes, can imagine smart match perform faster small list of items, hash by far outperform array lookup large list of items. however, should benchmark performance anyway. and why. on strawberry perl, list size 1, hash look-up outperforms string match: array_lookup

c# - Problem creating objects, class could not be found -

in blllanguage.cs class not able create dallanguage class's objects , vice versa. says dallanguage.cs / blllanguage.cs not found. whats wrong code below? blllanguage.cs using system; using system.data; using system.configuration; using system.linq; using system.web; using system.collections; using system.web.security; using system.web.ui; using system.web.ui.htmlcontrols; using system.web.ui.webcontrols; using system.web.ui.webcontrols.webparts; using system.xml.linq; using proj2; namespace proj2.bll.main.setting { public class blllanguage { public blllanguage() { //add constructor code here } #region properties /// <summary> /// properties /// </summary> private int intlanguageid; private string strdescription; private string strvalue; #endregion public int languageid { { return intlanguageid; } set { intlangu

iphone - How would you achieve a LED Scrolling effect? -

how achieve led scrolling effect example below? led sign - led ticker emulator iphone , ipad http://img.skitch.com/20101201-rsfh4p1bajb1wp94k466pdpiuj.preview.jpg sometimes remunerates comment in other posts :) have put code you, should implement font '8pin matrix' realistic feeling. uilabel *label; - (void)viewdidload { [super viewdidload]; label = [[uilabel alloc]initwithframe:cgrectmake(10, 50, 300, 20)]; label.font = [uifont fontwithname:@"courier-bold" size:16.0]; label.backgroundcolor = [uicolor blackcolor]; label.textcolor = [uicolor greencolor]; label.linebreakmode = uilinebreakmodecharacterwrap; // otherwise "…" label.text = @"this led text scrolled "; // blanks space between [self.view addsubview:label]; [nstimer scheduledtimerwithtimeinterval:0.12f target:self selector:@selector(scrolllabel) use

symfony1 - Symfony generation -

when generate module in symfony 1.4, creates (for example) 'new' , 'create' methods this: public function executenew(sfwebrequest $request) { $this->form = new someform(); } public function executecreate(sfwebrequest $request) { $this->forward404unless($request->ismethod(sfrequest::post)); $this->form = new someform(); $form->bind($request->getparameter($form->getname()), $request->getfiles($form->getname())); if ($form->isvalid()) { $res_object = $form->save(); $this->redirect('results_show', $res_object); } $this->settemplate('new'); } with --non-verbose-templates generates code below (i modified show creation part): public function executenew(sfwebrequest $request) { $this->forward404unless($request->ismethod(sfrequest::post)); $this->form = new someform(); if ($request->ismethod(sfrequest::post)) { $form->bind($request->getparameter($form->get

Python: NameError for no apparent reason? -

random import random def computer(): computer = 0 while computer < 21: val = int(random()*10)+1 if (computer + val) > 21: break else: computer += val print "ich habe ", computer, "!" return computer def player(): player = 0 loss = 0 while player < 21: hval = int(random()*10)+1 print "du hast ", hval, "...\nnoch eine mit y..." if raw_input == "y": player += hval if player > 21: print "du hast verloren!" loss = 1 break else: continue else: player += hval break return player return loss if __name__ == "__main__": player() if loss == 1

javascript - Can I stick extra stuff in HTML tags so that my JQuery can pick up on it? -

<div id="holder" rel="http://mysite.com/go.jpg" rel2="42pixels" rel3="gaga"> blah </div> is allowed? if possible, recommend using html5's custom data attributes achieve this: <div id="holder" rel="http://mysite.com/go.jpg" data-rel2="42pixels" data-rel3="gaga"> blah </div>

Even after uninstalling windows service, port number remains still occupied -

i installing windows service , works fine. now uninstalling same service. (to specific using installutil command installing uninstalling) service gets uninstalled when go command prompt , check status of port shows port still occupied. (using netstat command) due when try delete folder containing service of dlls not getting deleted , on trying delete them forcefully message in user. can guide on this. use netstat -b determine executable occupying port, kill using task manager "show processes users" option enabled.

facebook - How to add Single Sign On feature into FBGraph API in iPhone? -

i developing face book application. have implemented fbgraph api application. possible add single sign on feature graph api without using fbconnect library? check link: has detail explanation single sign on using facebook graph api , ios sdk. https://github.com/facebook/facebook-ios-sdk

php4 - Code not working in PHP 4 -

i have php script works fine in php 5, not in php 4. i've made small test case demonstrate (disclaimer: know below code written better, it's not used piece, rather 1 demonstrate i'm talking about): class messenger { var $messages = ''; function add($message) { $this->messages .= "$message\n"; } } function add($m) { if (! isset($globals['instance'])) $globals['instance'] = new messenger(); call_user_func_array(array($globals['instance'], 'add'), array($m)); } add("one"); add("two"); add("three"); var_dump($globals['instance']->messages); under php 5 messages property contains 3 messages, under php 4 empty. why? in php 4 , $this not seems work same way php 5 does. the $this pseudo-variable not defined if method in hosted called statically. not, however, strict rule: $this defined if method called statically within object. in cas

mySQL: Subquery to array? -

i working on slight complex (at least me) mysql query containing subquery , isn't going honest. select `products`.`id`, `product`.`price`, ( select `value` (`productvalues`) `productvalues`.`product` = 'product.id' ) values (`products`) where`product`.`active` = 1 the current result looks this: array ( [0] => array ( [id] => 1 [active] => 1 [price] => 1000 [values] => ) ) what want values element become array elements in values table matches ( where productvalues.product = product.id ). what doing wrong? select p.id, p.price, pv.`value` products p join productvalues pv on p.product_id=pv.product p.active = 1 order p.id; gives table 1 row each pv.value (btw, using reserved words 'value' not recommended). ordering output p.id ensures rows particular product together. so, in application layer, loop through rows, changing product each time p.id

html - Jquery element positioning and more -

hey guys, i'm pretty editing time thought i'd try new jquery. i'm trying create "3d" card page (similar this: http://activeden.net/item/xml-3d-video-showcase/83740?clickthrough_id=&redirect_back=true&ref=45 ) can't position elements , think codes wrong. here's js: $(document).ready(function() { //perform actions when dom ready var z = 0; //for setting initial z-index's var inanimation = false; //flag testing if in animation var imgloaded = 0; //for checking if images loaded $('.img').each(function() { z++; $(this).css('z-index', z); imgloaded++; }); function swapfirstlast(isfirst) { if(inanimation) return false; //if swapping pictures return else inanimation = true; //set flag process image var processzindex, direction, newzindex, indecrease; //change previous or next image if(isfirst) { processzindex = z; newzindex = 1; indecrease = 1; } else { processzindex = 1; newzinde

iphone - #import statements in .m or .h in objective-c? -

i ended having these in both of .h , .m files, first objective-c program i'd clarification can clean thins thing up. unless affects interface definition should put in .m file. if use class, use forward declaration: @class aclass; @interface bob : nsobject { aclass* a; } if implement something, import it: #import "someprotocol.h" @interface bob : nsobject<someprotocol> { } these kinds of thing "best practice" rather absolutely essential. objective c's #import directive means can't errors because include file multiple times, it's not technically problem, increase compile times.

php - Any Elegant Ideas on how to parse this Dataset? -

i'm using php 5.3 receive dataset web service call brings information on 1 or many transactions. each transaction's return values delimited pipe ( | ), , beginning/ending of transaction delimited space. 2109695|49658|25446|4|nsf|2010-11-24 13:34:00z 2110314|45276|26311|4|nsf|2010-11-24 13:34:00z 2110311|52117|26308|4|nsf|2010-11-24 13:34:00z (etc) doing simple split on space doesn't work because of space in datetime stamp. know regex enough know there different ways break down, thought getting few expert opinions me come airtight regex. if each timestamp going have z @ end can use positive lookbehind assertion split on space if it's preceded z as: $transaction = preg_split('/(?<=z) /',$input); once transactions, can split them on | individual parts. codepad link note if data has z followed space anywhere else other timestamp, above logic fail. overcome can split on space if it's preceded timestamp pattern as: $transaction

What is a good portable way to implement a global signalable event in a POSIX environment -

the usage case 1 application generates event , sends out signal application cares listen get. e.g. application updates contents of file , signals this. on linux done waiters calling inotify on file. 1 portable way listeners register well-known server, prefer simpler if possible. portable possible ideally means using posix features available. option using lock files you can locking file. signal emitter initial setup: create file well-known name , lock writing ( fcntl(f_setlk) f_wrlck or flock(lock_ex)`). signal receiver procedure: open file using well-known filename , try obtain read lock on ( fcntl(f_setlk) f_rdlck or flock(lock_sh) ). receiver blocks because emitter holding conflicting write lock. signal emission: signal emitter creates new temporary file signal emitter obtains write lock on new temporary file signal emitter renames new temporary file well-known filename. clobbers old lock file waiting receivers retain references it. signal

Saving property with HTML - encode on entry, or on display? -

i have system allows users enter html-reserved characters text area, post application. information saved database later retrieval , display. alarms (should be) going off in head. need make sure avoid xss attacks, because display data somewhere else in application. here options see it: encode before save db i can html-encode data on way in database, no html characters ever entered in database. pros: developers don't have remember html encode data when displayed on web page. cons: the data doesn't make sense desktop-based applications (or other html). stuff shows &lt; &gt; &amp; etc. don't html encode before saving db i can html encode data whenever need display on web page. pros: feels right because keeps integrity of data entered user. allows non-html based applications display data without having worry html encoding. cons: we might display data in lot of places, , we'll have make sure every developer knows when display

c++ - Help with this design issue -

i'm making game gui api. coming along nicely except 1 aspect. want themes similar how gtk works. way want work every gui element have default windows9x-like way of drawing themselves. if found theme set type of widget, drawn bitmaps. my original concept create theme class have getters , setters bitmaps. for example: thememanager.setbuttonhover(bitmap *bitmap); the problem this, is not flexable if want create new types of widgets. may want create superbutton use different theme button. flaw concept. concept i'm thinking of going each widget type has static methods set theme , constructor uses that. are there better ways of doing i'm not thinking of? since api, want avoid reading text files, reading theme text document not option. thanks may template superbutton on policy , have default policy default , user has option of providing different policy? policy define attributes of button (such hover image etc.) - describe make sense?

Equivalent to PostgreSQL array() / array_to_string() functions in Oracle 9i -

i'm hoping return single row comma separated list of values query returns multiple rows in oracle, flattening returned rows single row. in postgresql can achieved using array , array_to_string functions this: given table "people": id | name --------- 1 | bob 2 | alice 3 | jon the sql: select array_to_string(array(select name people), ',') names; will return: names ------------- bob,alice,jon how achieve same result in oracle 9i? thanks, matt tim hall has definitive collection of string aggregation techniques in oracle . if you're stuck on 9i, personal preference define custom aggregate (there implementation of string_agg on page) such have select string_agg( name ) people but have define new string_agg function. if need avoid creating new objects, there other approaches in 9i they're going messier postgresql syntax.

mysql - Database design: storing full transaction history AND quick lookup of current status? -

this pretty basic question, i'm beginner :) i'm building library database using django & mysql. database has concepts of books , users , , of transactions , user takes out or returns book. i need able to: get full list of transactions particular book - checked out , when get current status of book, quickly. i had thought of using tables this, there problems design? class book(models.model): name = models.charfield() class user(models.model): name = models.charfield() transaction_types = ( ('i', 'check in'), ('o', 'check out'), ) class transaction(models.model): book = models.foreignkey(book) user = models.foreignkey(user) type = models.charfield(max_length=1, choices=transaction_choices) date_added = models.datetimefield(auto_now_add=true) this work ok getting full list of transactions. if want current status of book, i'd have search through book's transactions , find recent. is s

Maven systemPath is not added to runtime classpath -

i need add jdk's tools.jar project dependency. setting normal dependency not working, because when installing maven repository, adds version number jar file. thereafter, when need needs tools.jar in classpath, fails. using system scope , setting path jar using < systempath > should solve problem. however, although in tests jar added classpath, @ runtime not. is there way around this? btw, i've added < usemanifestonlyjar >false< /usemanifestonlyjar > surefireplugin can see every file in classpath. is maven running in jdk? find out version of java it's running, mvn -ver set java_home env variable point jdk.

uiview - iPad orientation notifications lost when transition for keyWindow -

i have animation done on keywindow of app. [uiview beginanimations:kanimationlogin context:nil]; [uiview setanimationtransition:uiviewanimationtransitionflipfromleft forview:window_ cache:no]; [uiview setanimationcurve:uiviewanimationcurveeaseinout]; [uiview setanimationduration:1.0]; [window_ addsubview:splitviewcontroller_.view]; [uiview commitanimations]; [loginviewcontroller_.view removefromsuperview]; this works ok. then, if user logouts, transition reverse [uiview beginanimations:kanimationlogout context:nil]; [uiview setanimationtransition:uiviewanimationtransitionflipfromright forview:window_ cache:no]; [uiview setanimationcurve:uiviewanimationcurveeaseinout]; [uiview setanimationduration:1.0]; [window_ addsubview:loginviewcontroller_.view]; [uiview commitanimations]; [splitviewcontroller_.view removefromsuperview]; here problem. now, loginviewcontroller_ , splitviewcontroller_ don't receive orientation notifications. why? well, it's not

flash - How can I make a class constructor be callable as a function? -

some of top level classes can instantiated called function (e.x. new number() , number() , new boolean() , boolean() , new array() , array() ). usually used type conversion or shortcut instantiation. able same thing: public class foo { public function foo():void { //do } } public function foo():foo { //do stuff; return new foo(); } is possible? if so, how? edit clarify: what wanted create logging class interact flash/javascript, , cross-browser compatible. wanted able use log function alias of method in log class . got me wondering whether implement custom casting function because. i've realized it's not possible, fun play anyway. you can define classes: package [package name] { public class foo { public function foo():void { //do stuff } } } and can define functions: package [package name] { public function foo():bar { return new bar(); } } but classes , functions cannot have naming collisions.

Android appwidget, can i put buttons on it? -

i add twoo buttons on appwidget, set onclicklistener methods of this. is there way it? how? remoteviews views = new remoteviews(context.getapplicationcontext(), r.layout.main_view); intent intent = new intent(context, inputbroadcastreceiver.class); // receiver class intent.putextra(extra_id, id); // extras pendingintent pendingintent = pendingintent.getbroadcast(context, 0, intent,pendingintent.flag_update_current); views.setonclickpendingintent(r.id.my_button, pendingintent); then override onreceive method in inputbroadcastreceiver , enjoy inputs ;) broadcastreceivers explaining here .

mysql - Java application to make database dump -

i needing make backup database in mysql, schema anda data. know how or have tips? thanks try mysqldump , built-in program mysql backup purpose

Getting ANT view for Eclipse IDE for JavaScript Web Developers -

i use eclipse ide javascript web developers eclipse downloads page , discovered doesn't include ant view, eclipse classic version provides. how ant view "eclipse ide javascript web developers" version of eclipse? i installed eclipse classic, added eclipse web tools platform plugin.

svn - Using Subversion and Pushing to Staging and then Live Sever -

we want add staging server , version control our development pipeline. our site complex web application running on remote linux server php, mysql, , apache. set subversion on office lan , got working in dreamweaver cs5. our development machines run windows. the question how best add staging server set up. we're small team, 3 developers, don't need overly-robust/complex solution. don't understand how push changes our subversion repo (which located on 1 of developer's machines) staging server or live server. i read lot people writing hooks this, mean need install subversion on staging server , live server? i'd rather not this. i want upload files automatically staging server developers commit them subversion. how can done? then need automated process uploading files staging server live server. part don't understand. because don't want have subversion installed on live. how typically done? are files staging server pushed live? or there way push ones

gcc warning - Why does a "function name" evaluate to true in C and how to get warned on it -

i stumbled across following behaviour of gcc 3.2.2 writing c program: in if statement forgot braces of function , wrote: if(myfunc)... instead of if(myfunc())... this did not generate error neither warning although have pretty every warning turned on. it evaluated true . why writing legal code in first place ? because function exists/has address ? know how 1 avoid such mistakes or if there warning option overlooked ? issue better solved in later gcc versions ? here exact compiler call completeness: msp430-gcc -g -os -mmcu=msp430x1611 -wall -w -wfloat-equal -wundef -wshadow -wpointer-arith -wbad-function-cast -wcast-qual -wwrite-strings -wsign-compare -waggregate-return -wstrict-prototypes -wmissing-prototypes -wmissing-declarations -wredundant-decls -wnested-externs -wimplicit-function-declaration -werror (since i'm forced use gcc 3.2.3 there no -wextra) if (myfunc) equivalent if (&myfunc) , you're testing address of function, of course non-

how to use jQuery to handle specific types of html controls -

creating click event input easy $('input').click(function () { alert('adsf'); }); but how can selective previous code works on type checkbox or of type button, rather using generic 'input' selector? you can use built-in selectors :checkbox , :button find these elements easily. $('input:checkbox').click(function () { alert('checkbox'); }); $('input:button').click(function () { alert('button'); }); there's :radio , :submit , :text , , :input selectors, among others

c# 4.0 - Loop through attribute of a class and get a count of how many properties that are not null -

i wondering if there simpler way this? public int nonnullpropertiescount(object entity) { if (entity == null) throw new argumentnullexception("a null object passed in"); int nonnullpropertiescount = 0; type entitytype = entity.gettype(); foreach (var property in entitytype.getproperties()) { if (property.getvalue(entity, null) != null) nonnullpropertiescount = nonnullpropertiescount+ 1; } return nonnullpropertiescount; } how about: public int nonnullpropertiescount(object entity) { return entity.gettype() .getproperties() .select(x => x.getvalue(entity, null)) .count(v => v != null); } (other answers have combined "fetch property value" , "test result null". work - separate 2 bits out bit more. it's you, of course :)

How to catch http client request exceptions in node.js -

i've got node.js app want use check if particular site , returning proper response code. want able catch errors come domain name isn't resolving or request timing out. problem is errors cause node crap out. i'm new whole asynchronous programming methodology, i'm not sure put try/catch statements. i have ajax call goes /check/site1. server side calls function attempts make connection , return statuscode. it's simple function, , i've wrapped each line in try/catch , never catches anything. here is: function checksite(url){ var site = http.createclient(80, url); var request = site.request('get', '/', {'host': url}); request.end(); return request; } even each of lines wrapped in try/catch, still uncaught exceptions ehostunreach , on. want able catch , return ajax call. any recommendations on try next? http.createclient has been deprecated. here quick example of how handle errors using new http.request

javascript - I have a div with scrollbars. How can I detect if someone mousedowns on the scrollbar? -

i have div scrollbars. how can detect if mousedowns on scrollbar? you can use jquery scroll function .scroll() , pass function called when scrolling occurs. see here more info. example: $('#targetdiv').scroll(function(event) { //stuff when scrolled }); you might able use event data see if mouse button pressed.

regex - Regular expression for asp.net -

i need in regular expression. validating textbox text when updating records. when click update button, first 5 letters should equal cm000 or cm000. how validate using regular expression in asp.net. know validationexpression this. let me know . thanks you don't need regex - instead: bool isvalid = textbox.text.startswith("cm000", stringcomparison.ordinalignorecase); if must use regex (like validation control) use this: <asp:regularexpressionvalidator runat="server" id="someid" controltovalidate="textbox" validationexpression="^(?:cm|cm)000" errormessage="invalid input" />

c# - Literature suggestions for best practices / good coding techniques -

i mid level developer. work in c# asp.net have worked in php, classic asp, , tiny bit in java (would more in future). looking few suggestions on books me continue growing in coding techniques. basically book lots of best practices, coding tricks, used useful features , operators (e.g. ?? operator), stuff that. not looking book teach me specific language. don't particularly care language code samples in c or java best. suggestions don't need limited pure code objects either. books information database connection management ect. good. thanks suggestions. required reading: code complete .

In mercurial, how to see diff between in a merge changeset and one parent without changes from the other parent? -

consider trivial repo: mkdir temp cd temp hg init echo abc > file1 hg ci -a -m init echo def >> file1 echo hey > file2 hg ci -a -m hg -r0 echo ghi >> file1 echo hey > file3 hg ci -a -m b hg merge hg ci -m merge during merge, take "ghi" (doesn't matter side). the dag is: 0 - 2 - 3 \- 1 -/ hg diff -r1:3 shows file1 change , new file3. hg diff -r2:3 shows new file2. same hg log -p -r3 , hg st --change 3 , because 2 first parent. my question is: how can see changes between 1 , 3 minus changes in 2 , conceptually d(1:3) - d(0:2) ? i expect see file1 change. hg log -r3 -v shows "files: file1" (i guess because it's file in change ctx), curiously, hg log -r3 --debug shows "files+: file2". if run hg view (provided bundled hgk extension) , click on r3, shows file1. can't read tcl/tk code, seems trick in contmergediff function gets list of files in merge, in somehow omits file2. fwiw, tortoisehg differ

Cross platform (php to C# .NET) encryption/decryption with Rijndael -

i'm having bit of problem decrypting message encrypted php mcrypt. php code following: <?php //$iv_size = mcrypt_get_iv_size(mcrypt_rijndael_256, mcrypt_mode_cbc); $iv = "45287112549354892144548565456541"; $key = "anjueolkdiwpoida"; $text = "this encrypted message"; $crypttext = mcrypt_encrypt(mcrypt_rijndael_256, $key, $text, mcrypt_mode_cbc, $iv); $crypttext = urlencode($crypttext); $crypttext64=base64_encode($crypttext); print($crypttext64) . "\n<br/>"; ?> the encrypted message sent asp.net platform (c#). however, i'm having problem retaining order of decryption (base64 decode urldecode). code had in asp.net following (iv , key same in php): public string decode(string str) { byte[] decbuff = convert.frombase64string(str); return system.text.encoding.utf8.getstring(decbuff); } static public string decryptrj256(string cypher, string keystring, string ivstring) { string sret = "&qu

c# - How to handle Word close event from WinForms application? -

i have winforms application , looking way following: click link create word document blob in database , open it. block winforms application until word closed. handle when word closed, check if document changed, , persist changes database. the problem having not creating word document , opening it, hooking word process know when word has closed. there libraries @ doing or tutorials show how accomplish task? please see accepted solution, here code used complete task: protected static string filepath { get; set; } public static void displaydocument(byte[] documentbytes, string filepath) { filepath = filepath; if (documentbytes == null) return; if (!directory.exists(temp_file_directory)) directory.createdirectory(temp_file_directory); if (file.exists(filepath)) file.delete(filepath); try { filestream fs = new filestream(filepath, filemode.create); fs.write(documentbytes, 0, convert.toint32(documentbytes.length));