Posts

Showing posts from May, 2011

wpf - XAML - MergedDictionaries throwing XmlParseException "item has already been added". Why? -

i have following, easy reproduce problem: i'm creating xaml application uses resources file. way go create mergeddictionaries-tag merge local , global resources, this: <window> <window.resources> <resourcedictionary> <resourcedictionary.mergeddictionaries> <resourcedictionary source="path.to.xaml.file"/> <resourcedictionary> <style targettype="{x:type border}" x:key="typeblock"> </style> <style targettype="{x:type border}" x:key="setblock"> </style> </resourcedictionary> </resourcedictionary.mergeddictionaries> </resourcedictionary> </window.resources> .... </window> this little piece of code crash if run it: item has been added. key in dictionary: 'system.windows.controls.border' key being added: ...

python - Scripting HTTP more effeciently -

often times want automate http queries. use java(and commons http client), prefer scripting based approach. quick , simple. can set header, go page , not worry setting entire oo lifecycle, setting each header, calling html parser... looking solution in language, preferable scripting have @ selenium . generates code c#, java, perl, php, python, , ruby if need customize script.

performance - What is the fastest way to remove nodes from a large XML file using .net -

i working working large xml files (100s of mbs). tree simple <items> <item> <column1>abc</column1> <column2>def</column2> </item> <item> <column1>ghi</column1> <column2>klm</column2> </item> </items> i need parse document, , remove <item> elements. far, best peerformance achieved using xmlreader, caching each <item> in memory , writing using xmlwriter out if meets criteria, , ignoring if doesn't. there anyting can make faster? you might able save step implementing subclass of xmlreader read method skips on item elements you're not interested in. right now, seem have 2 steps: reading , filtering document xmlreader , using xmlwriter write presumably read from. subclassing xmlreader eliminates second step; use subclassed xmlreader input xslt transform or xmldocument or whatever, , never builds intermediate representation of filtered x...

java - How much data can a List can hold at the maximum? -

how data can added in java.util.list in java @ maximum? is there default size of arraylist? it depends on list implementation. since index arrays int s, arraylist can't hold more integer.max_value elements. linkedlist isn't limited in same way, though, , can contain amount of elements.

performance - what mysql query is better? -

i got 2 mysql queries, retrieve same data?, 1 think better use , why? taking account standards, , better code etc. sorry if stupid question, im curious cat! here goes: query 1: select * (( select u.username, u.picture, m.id, m.user_note, m.reply_id, m.reply_name, m.dt relationships r join notes m on m.user_id = r.leader join user u on r.leader = u.user_id r.listener ='2' ) union ( select u.username, u.picture, m.id, m.user_note, m.reply_id, m.reply_name, m.dt notes m join user u on m.user_id = u.user_id u.user_id ='2' )) d d.dt < '2010-09-20_131830' order d.dt desc query 2: select u.username, u.picture, m.id, m.user_note, m.reply_id, m.reply_name, m.dt notes m inner join user u on m.user_id = u.user_id (m.user_id = '2' or m.user_id in ( select r.leader relationships r r.listener ='2')) , dt < '2010-09-20_131830' order dt desc i find union all version easier understand (...

cakephp swiftmailer config -

hi using swiftmailer component in app , looking way have separate config (perhaps in config folder?) swiftmailer checks debug mode using , uses different settings? case 1: on production mode use simple smtp server without auth. case 2: on debug mode use gmail settings or other settings since developing locally is possible? the settings code case 1: $this->swiftmailer->smtphost = ''; the settings code case 2: $this->swiftmailer->smtptype = ''; $this->swiftmailer->smtphost = ''; $this->swiftmailer->smtpport =; $this->swiftmailer->smtpusername = ''; $this->swiftmailer->smtppassword = ''; i think quickest way be: <?php configure::load('swiftmailer'); $this->swiftmailer->smtptype = configure::read('swiftmailer.'.configure::read().'.smtptype'); $this->swiftmailer->smtphost = configu...

switch statement - Switching activities back and forth in Android -

i'm starting on android , got beginner question on switching between multiple activities. i understand can go between 2 activities invoking intent , returning setresult(). want know how jump between multiple activities. want learn process life-cycle. understand how every activity started ar oncreated(), i'm not sure how implement onresume() or onrestart() when want come back. so have 3 activities: activity1, activity2 , anctivity3. i start activity1 , invoke activity2 intent, , activity2 invokes activity3. using buttons. want come activity1 activity3. same thing here too. make intent , call startactivity(activity1_intent). gives runtime error. i think need implement onresume() or onrestart(), i'm not sure how this. in oncreate() make gridview, when come back, need make gridview again? if give small explanation of refer tutorial great. thank much. in manifest file set android:launchmode="singletop" activity1. then call activity1 use: int...

wpf - How to use the text of a routed command as button content -

i have button on view bound via routeduicommand command defined in viewmodel. the xaml code excerpt view: <button content="login" command="{binding login}" /> in view's codebehind add command binding viewmodel view's binding collection: this.commandbindings.add( viewmodel.logincommandbinding ); the viewmodel implements command: public class loginviewmodel:viewmodelbase { public icommand login { get; private set; } public commandbinding logincommandbinding { get; private set; } public loginviewmodel( ) { this.login = new routeduicommand( "login", "login", typeof( window ) ); this.logincommandbinding = new commandbinding( login, logincommandhandler, canexecutehandler ); } void logincommandhandler( object sender, executedroutedeventargs e ) { //put code here } void canexecutehandler( object sender, canexecuteroutedeventargs e ) { r...

internet explorer 7 - Elements disappearing on IE7 window resize -

i coding web page. http://www.nomizine.com/misc/tbs/default.html it renders everywhere except ie7. when resize browser window, top navigation, compass on left , subscribe block on right disappears. any idea how fix it? btw, have tried haslayout tricks zoom:1, clear:both etc nothing seems work. i believe issue fact compass absolute positioned container (the td in case) not absolute or relative positioned.. since absolute positioned elements positioned in relation nearest relative or absolute positioned parent, ie7 messes when trying reclculate (due resize) put element.. i suggest wrap #compass div div has position:relative [edit] ok culprit #header_bg rule in css file.. remove position:relative , normal :) #header_bg{ background: url(../images/header_bg.png) no-repeat center top; /*position:relative;*/ }

Simple Question on CruiseControl.Net and MSBuild -

i have had first successful build using cc.net + msbuild on legacy project. took 8 hours. my newb question is: output? my artifactdirectory empty. did go? did specify thoughtworks.cruisecontrol.msbuild.dll logger in msbuild-task? did have xmllogger publisher? edit: looking : results/logs goes dashboard , mail or website/dll/program built? post project configuration? edit2: website/dll built located in outdir specified in msbuild task. if didn't override either outdir or outputpath property (in msbuild task or msbuild build script) website should located in webproject\bin\release (or debug)_publishedwebsites , dlls should located in every project_dir\bin\release (or debug). if want common output need specify overriding outputpath or baseoutputpath (see here http://msdn.microsoft.com/en-us/library/bb629394.aspx ).

What language to learn after Haskell? -

as first programming language, decided learn haskell. i'm analytic philosophy major, , haskell allowed me , correctly create programs of interest, instance, transducers natural language parsing, theorem provers, , interpreters. although i've been programming 2 , half months, found haskell's semantics , syntax easier learn more traditional imperative languages, , feel comfortable (now) majority of constructs. programming in haskell sorcery, however, , broaden knowledge of programming. choose new programming language learn, not have enough time pick arbitrary language, drop it, , repeat. thought pose question here, along several stipulations type of language looking for. subjective, intended ease transition haskell. strong type system. 1 of favorite parts of programming in haskell writing type declarations. helps structure thoughts individual functions , relationship program whole. makes informally reasoning correctness of program easier. i'm concerned correctnes...

ruby - RUBY_LIBRARY cmake variable when building Qpid -

im trying build qpid . when running cmake printed log: could not find ruby (missing: ruby_library) [ ... more stuff cut brevity ] cmake error @ src/cmakelists.txt:96 (include): include not find load file: c:/qpid/0.6/qpid/build/src/rubygen.cmake it seems failing because couldnt find file thats supposed have been generated. hasn't since couldn't locate ruby. but seems @ least partially find ruby since bunch of other ruby_* variables have been set in cmake ruby_executable , ruby_include_dir. what ruby_library , supposed set to? ruby installed in c:\ruby192. according /usr/share/cmake-2.8/modules/findruby.cmake : # ruby_library = full path ruby library i see you're on windows. guess link against dll, you'd either point @ ${ruby_dir}\lib\msvcrt-ruby191.lib or ${ruby_dir}\bin\msvcrt-ruby191.dll (i'm using names ruby 1.9.1 binary grabbed ruby-lang.org). link against static library, you'll want ${ruby_dir}\lib\msvcrt-ruby-19...

css backgrounds images -

hi have 1px png file,which trying set background image 2 divs adjacent each other horizontally.the html , css under:- <div id='one'>hi</div> <div id='two'>hello</div> the css this div { width: 50%; height: 50% } #one, #two { background-image: url(/images/image.png); background-repeat: repeat; } now problem here in between 2 divs black border automaticaly appears when image set. dont want 2 divs seen separate blocks.please help. totally new css , need help:-)! i'd willing bet image using has alpha transparency (that is, image partially transparent), , you're seeing one-pixel overlap between 2 divs. either make sure container number of pixels wide, or put divs inside container , use background on instead.

android - A project with that name already exists in the workspace eclipse -

Image
i'm new eclipse/java/android i have created project, wanted start over. deleted helloandroid folder workspace folder restarted eclipse now can't create project same name, because finish greyed out, , gives me following message: a project name exists in workspace eclipse how can delete old hellowandroid project eclipse? you need open project explorer view (it may open) , delete project within there.

c# - Filtering a query in Entity Framework based upon a child value -

i've got model set in entity framework (ef) there 2 tables, parent , child, in 1 many relationship. having trouble writing query linq trying retrieve single instance of parent while filtering upon field in parent , field in child. listed below: var query = c in context.parenttable c.isactive == true && c.childtable.name = "abc" select c; unfortunately when try fails because no field named "name" appears available via intellisense when type c.childtable. any guidance appreciated. that correct because c.childtable not of child type entitycollection<child> . in order make query work, need modify this: var query = p in context.parenttable c in p.childtable p.isactive == true && c.name == "abc" select p;

data binding - Combine my Attributes on a Linq to SQL Entity Property -

i have linq sql dbml.cs file in it: [global::system.data.linq.mapping.columnattribute(storage="_pantsname", dbtype="varchar(248)")] [global::system.runtime.serialization.datamemberattribute(order=3)] public string pantsname { { return this._pantsname; } set { if ((this._pantsname != value)) { this._pantsname = value; } } } i made new .cs file , put in because want add custom attribute, build exception "the type mydal.pants contains definition 'pantsname;". want add attributes linq sql binding stuff. i don't want edit dbml.cs directly because blown-away next time regen db. public partial class pants { [mycustomattribute( mybool = true )] public string pantsname { { return this._pantsname; } set { if ( ( this._pantsname != value ) ) { this._pantsname = value; } } } } how can “merge” 2 properties ms-wizard-made attributes own? thanks.

Running ant in eclipse (sql2java) - no output to the console -

i configuring sql2java first time myself. extracted zip-archive , imported files eclipse java project. don't know if correct, because when run ant build file through eclipse ant function ("run ant build...") there no output on console. i don't know problem located, sql2java, ant, eclipse? fresh , clean install of eclipse galileo. how can sql2java / ant work? how information can me locate problem? there way use eclipse's ant installation run build file console? any appreciated. in advance. the problem may related anthome definitions, should same eclipse plugin directory. goto windows/preferences menu on left tree-menu choose ant/runtime on right screen edit anthome variable, set eclipse installition ant plugin directory forexample : ..\eclipse-jee-galileo win32\eclipse\plugins\org.apache.ant_1.7.1.v20090120-1145 hope works

php - Remove every <br /> except one per line? -

how can turn this: ...<br /> <br /> ...<br /> ...<br /> <br /> <br /> ...<br /> into using php : ...<br /> ...<br /> ...<br /> ... please notice deletion of first , last if it's mentioned once. in middle keep 1 preg_replace('#<br />(\s*<br />)+#', '<br />', $your_string); this replace instances of more 1 <br /> , optionally whitespace separating them, single <br /> . note <br /> in pattern matches that. if wanted more defensive, change <br[^>]*> allow <br> tags have attributes (ie. <br style="clear: both;" /> ) or don't have trailing slash.

How to create xcode project for iPhone Light version app? -

what recommended way create light version of iphone app? i have x-code project of iphone app want charge money it. in addition app, deploy additional "light" version of app free of charge of course have limitations. best way can think of adding new 'light' configuration in existing xcode project , define constant light_version in configuration tested in code. will solution work? or have create new 'light' project pointing sources , resources of original project? yes can define preprocessor macro light_version. use with #ifdef light_version #endif an disable/enable features. more information please at: stackoverflow - xcodebuild - how define preprocessor macro?

c++ - Any cross platform way to build cpp skeleton from a header? -

this question has answer here: creating .cpp files .h files visual studio 5 answers i'm tired of copy pasting header cpp file hacking @ until in correct form. has made program read header file , make corresponding cpp skeleton? need cross platform or bare minimum works on linux. vim plugin acceptable. example class { public: int dosomething( int number ); } would produce following file int a::dosomething( int number ) { ; } http://www.vim.org/scripts/script.php?script_id=2624

onkeyup - jquery: do this on keyup, unless the person is in a textarea or input -

my script works don't understand how make not launch functions when in textarea/input , keys pressed. aka: launch event when user presses key, unless user in textarea/input. $('body').keyup(function (event) { var direction = null; if (event.keycode == 37) { $('#wrapper').fadeout(500) } else if (event.keycode == 39) { $('html,body').animate({scrolltop: $('body').offset().top}, {duration: 1500, easing: 'easeinoutquart'} ) return false; } }) just check event.target: $('body').keyup(function(event) { if ($(event.target).is(':not(input, textarea)')) { ... } }); in case still have 1 event handler (attached body) filter elements recieves event

.net - BindingList<T> datasource for DataGridView -

i have bindinglist use datasource on datagrid view. added datagridview1 , button 1 form. when press button, nothing shows on datagridview. if use datatable data source works fine. must missing simple. public partial class form1 : form { bindinglist<classificationinfo> boundlist; classificationinfo item; private void button1_click(object sender, eventargs e) { boundlist = new bindinglist<classificationinfo>(); item = new classificationinfo(); item.bexclude = 1; item.icolor = 123456; item.szdescription = "test line 1"; boundlist.add(item); item = new classificationinfo(); item.bexclude = 0; item.icolor = 7890123; item.szdescription = "test line 2"; item.iorder = 2; boundlist.add(item); datagridview1.datasource = boundlist; } public class classificationinfo { public int icolor; public int i...

.net - Does WPF DatePicker allow you to specify a time zone? -

i'm using wpf toolkit's datepicker select date. set datetime after selecting date @ end of selected date. since converting utc time need able specify user's time zone. since tool running on our machine's cannot use current machine's local time. when selecting date in datepicker possible specify time zone date corresponds to? no, if want convert datetime local time utc, need call: ((datetime) selectedtime).touniversaltime(); make sure read on caveats of method: http://msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx

c# - Is there a .NET library that can do string permutations or string expansion? -

what i'm looking library or code of classes can used expand construction strings variations , permutations. following (syntax mine, may different): construction string: [ff]oo [bbß]ar|f(oo|oe) output strings: foo bar foo bar foo bar foo bar foo ßar foo ßar foo foe while wouldn't hard build myself, if it's around, why bother reinventing wheel? this doesn't follows syntax, use in projects , runs smooth: permutations, combinations, , variations using c# generics

How can I delete empty arrays/refs from a Perl hash? -

lets have following perl hash: %hash = ( 'a' => { 'b' => ['c', 'd', 'e'], 'f' => { 'g' => [], 'h' => [] }, 'i' => [] } ); and i'd rid of [] 's hash result below: %hash = ( 'a' => [ 'b' => ['c', 'd', 'e'], 'f' => [ 'g', 'h', 'i' ] ] ) (i hope got {} , [] balanced, apologies if not, but) i'd make no empty arrays/ref's exist. i'm sure possible/simple, i'm not sure whether delete() work, or if there's better method or perl module out there. can steer me in right direction? it appears data might nested arbitrarily, , want walk through recursively, rewriting patterns others. that, i'd using data::visitor . use data::visitor::callback; use list::moreutils 'all'; $visitor = data::vis...

runtime - Inspect Groovy object properties with Java reflection -

i have expando class need inspect properties java. in groovy: def worker = new expando() worker.name = "john" worker.surname = "doe" in java: introspector.getbeaninfo(groovyobject.getclass()) is possible compile @ runtime class object in groovy? the expando dynamic. not generate bytecode getters or setters , therefore cannot used javabean. need use bean introspector for? may able implement logic using expando directly if write in groovy.

c# - Pass arguments to running application -

i making image uploader (upload image image hosting website) , i'm having issues passing argument (image location running application) first of let's myapp.exe running whenever right click on image have added item in default windows context menu says "upload image". when that's clicked needs pass location running application. my program.cs: static class program { [dllimport("user32.dll")] static extern intptr findwindow(string lpclassname, string lpwindowname); [dllimport("user32.dll")] static extern intptr sendmessage(intptr hwnd, uint msg, uintptr wparam, intptr lparam); [dllimport("user32.dll", setlasterror = true, charset = charset.auto)] static extern uint registerwindowmessage(string lpstring); [stathread] static void main(params string[] arguments) { if (arguments.length > 0) { //this means the upload item in context menu clicked //here method ...

algorithm - Finding three elements in an array whose sum is closest to a given number -

given array of integers, a 1 , a 2 , ..., a n , including negatives , positives, , integer s. need find 3 different integers in array, sum closest given integer s. if there exists more 1 solution, of them ok. you can assume integers within int32_t range, , no arithmetic overflow occur calculating sum. s nothing special randomly picked number. is there efficient algorithm other brute force search find 3 integers? is there efficient algorithm other brute force search find 3 integers? yep; can solve in o(n 2 ) time! first, consider problem p can phrased equivalently in different way eliminates need "target value": original problem p : given array a of n integers , target value s , there exist 3-tuple a sums s ? modified problem p' : given array a of n integers, there exist 3-tuple a sums zero? notice can go version of problem p' p subtracting s/3 each element in a , don't need target value anymore. clearly, if test po...

php - Can you configure a single folder in a WordPress install that will allow directory list contents -

i have wordpress installation. have 1 folder in file structure url show files , folders , allow browse , download there. can done? seth you need make separate .htaccess file directory want viewable. careful directories deeper 1 in .htaccess works downstream/cascades. more info. via: http://www.wise-women.org/tutorials/htaccess/ allow directory browsing there may times when want or need allow visitors browse directory. example, may need allow access files in directory downloading purposes on server configured not allow it. many servers configured visitors cannot browse directories. in case visitors not see contents of directory instead error message. can override servers settings , allow directory browsing line: options +indexes

asp.net - css help, displaying image with div -

edit: its confirmation div box when user click on save button, typicall see confirming have receivied inqury. and div box this: "[image] got email, , should hear within 24 hours." below code using display div image whats happening that, when page loads see image first , after save image see div msg , image , div disappears (as suppose to) <div id="divstatus"></div> <style type="text/css"> #divstatus { background:transparent url(../images/ico_confirmation_sml.gif) no-repeat scroll 0 0; padding-left: 22px; min-height: 27px; } scriptmanager.registerclientscriptblock(this, this.gettype(), key, "$(function() { $('#divstatus').html('" + msg + "').show().fadein(800).fadeout(9000); });", true); i have updated code bit, check demo http://jsfiddle.net/69f6h/2/ #divstatus { background:url("http://www.lancs.ac.uk/~lubbs/images/home.gif") no-repeat; padd...

MySQL ORDER BY optimization in many to many tables -

tables: create table if not exists `posts` ( `post_n` int(10) not null auto_increment, `id` int(10) default null, `date` datetime not null default '0000-00-00 00:00:00', primary key (`post_n`,`visibility`), key `id` (`id`), key `date` (`date`) ) engine=myisam default charset=utf8 collate=utf8_bin; create table if not exists `subscriptions` ( `subscription_n` int(10) not null auto_increment, `id` int(10) not null, `subscribe_id` int(10) not null, primary key (`subscription_n`), key `id` (`id`), key `subscribe_id` (`subscribe_id`) ) engine=myisam default charset=utf8 collate=utf8_bin; query: select posts.* posts, subscriptions posts.id=subscriptions.subscribe_id , subscriptions.id=1 order date desc limit 0, 15 it`s slow because used indexes "id", "subscribe_id" not index "date" ordering slow. is there options change query, indexes, architecture? possible improvements: first, you'll gai...

javascript - How to custom text prompt in input tag? -

is there way ( languages css, html or javascript ) custom text prompt in input tags ? for text prompt mean vertical flashing line in input tags. i assume prompt mean 'enter full name' html5 forms support default message attribute. if want use css, check out overlabel approach found in this article . if neither of meet fancy, user old fashion javascript focus , blur events. need logic ensure user has not entered text , clear our value (on focus) or put default text (on blur). sure can find code via google search.

python - Connecting signals in GTK+: anonymous way? -

after reading "using signals" wondering if possible connect signals "sinks" in "anonymous" way? in order words, if example following (snippet reference above): acar = car() acar.connect('engine-started', mycallback) is possible connect mycallback signal engine-started sources in 1 go? along lines of: gbus.connect('engine-started', mycallback) of course gbus here example. yes, can use gobject.add_emission_hook ( g_signal_add_emission_hook ).

doing a plyr operation on every row of a data frame in R -

i plyr syntax. time have use 1 of *apply() commands end kicking dog , going on 3 day bender. sake of dog , liver, what's concise syntax doing ddply operation on every row of data frame? here's example works simple case: x <- rnorm(10) y <- rnorm(10) df <- data.frame(x,y) ddply(df,names(df) ,function(df) max(df$x,df$y)) that works fine , gives me want. if things more complex causes plyr funky (and not bootsy collins) because plyr chewing on making "levels" out of floating point values x <- rnorm(1000) y <- rnorm(1000) z <- rnorm(1000) myletters <- sample(letters, 1000, replace=t) df <- data.frame(x,y, z, myletters) ddply(df,names(df) ,function(df) max(df$x,df$y)) on box chews few minutes , returns: error: memory exhausted (limit reached?) in addition: warning messages: 1: in paste(rep(l, each = ll), rep(lvs, length(l)), sep = sep) : reached total allocation of 1535mb: see help(memory.size) 2: in paste(rep(l, each = ll), rep(lvs...

c# - A class definition for a date class that contains three integer data members:month,day,year -

i not sure asking here. example great. here complete list of requirements. working through exercise in book have been reading have read chapter on , on cant make sense out of it. a class definition date class contains 3 integer data members:month,day,year one constructor assigns date 1/1/2000 new object not recieve arguments. one constructor thats accepts month , day arguements , uses default year of 2004 one constructor thats accepts month, day,and year arguements each constructor should output message user stating constructor being used. a method displays values in date object. public class weirdrequirements { int m_year, m_month, m_day; public delegate void messageprinter(string message); public messageprinter printmessage = console.writeline; public weirdrequirements() { m_year = 2000; m_month = 1; m_day = 1; printmessage("default"); } public weirdrequirements(int month, int day) { ...

python - Local test server for PHP similar to Django's runserver -

as python developer using django, i've grown accustomed have built-in test server projects, spares me setting apache every single project i'm working on local development machine. there similar php let's me "serve directory php project on localhost:8080"? i'm not looking all-in-one-solution xampp or wamp. looks php 5.4 added capability: http://www.php.net/manual/en/features.commandline.webserver.php

iPhone Objects from NSDictionary PList -

in app have section load saved plist has 2 nested dictionaries this: <?xml version="1.0" encoding="utf-8"?> <!doctype plist public "-//apple//dtd plist 1.0//en" "http://www.apple.com/dtds/propertylist-1.0.dtd"> <plist version="1.0"> <dict> <key>1</key> <dict> <key>color</key> <string>yellow</string> <key>lang</key> <string>us</string> <key>name</key> <string>peter</string> <key>uid</key> <string>1</string> </dict> <key>2</key> <dict> <key>color</key> <string>blue</string> <key>lang</key> <string>us</string> <key>name</key> <string>josh</string> <key>uid<...

php - How iterate through controls in a form? -

i'm pretty new php , i'm working on first php website. have need display (and add/edit) rows in table in single form. what i'm going row in form each row in table plus 1 blank row user can add more items table. when click save button want existing rows update , new row (if data present) insert. is there easy way can iterate through controls in form or of sort? you can iteratore through $_post array using foreach construct, not forget validate key names against column names (or row names, can't grasp database design, because woke up). foreach($_post $key => $value) { // stuff } and if it's first php website, don't forget sql injection .

sql - Time range with overlapping --- without temporary table result is OK otherwise wrong -

below working sql query calculation of time differences overlapping. reasons need create view - therefore cannot use temporary table tempalmdb. instead view begins select x.alarmgroup , have use created view qv_alarms . in case output different version temporary table. the original view contains following colums: alarmgroup, alarmon, alarmoff, priority, ... alarmon , alarmoff arrival , returning time of alarm. calculation done each alarm group. reduce calculation time per query included clauses alarmgroup , priority (in temporary table). clause group possible in second part . my questions: 1. why different , wrong results when use part 2 (having replaced 4 times tempalmdb qv_alarms)? 2. how possibly include clause priority in part 2? -- part 1: temporary table if exists(select * information_schema.tables table_name = 'tempalmdb') drop table tempalmdb select top 500 alarmgroup, alarmon, alarmoff tempalmdb qv_alarms alarmgroup = 'a1_1_alarms' order ...

Communication between C# applications - the easy way -

i have 2 c# programs , want send data , forth between them. (and check if data arrived other application.) 2 programs run on same computer, no networking capability required. i've read questions similar topics here, i'm not entirely sure right method me. (wcf, remoting, etc.) what want know, 1 easier implement beginner in c#? (i don't want complicated anyway, it's few integers , text want send.) if there isn't real difference in difficulty, advantages 1 have on other? i'd appreciate simple example code well. thanks in advance. wcf packages various methods of communication between applications (web services, remoting, msmq etc) in single package, programmatically same in way used, , detail of method used left configuration of binding between. slight simplification perhaps, it's about. it worth getting wcf if need inter-process communication, , advice way go this. it's worth looking @ idesign , produce number of articles on subject...

Order files by creation time to the millisecond in Bash -

i need create list of files located on hard disk in order of when arrived on hard disk. so, have used following: ls -lat which lists files in date/time order, however, orders them nearest second. problem here there thousands of files , every often, few of them come clumped in same second. need exact correct ordering. i'm guessing easiest way creation time milli (or perhaps nano) second. this, have tried using following: stat $myfile to @ modification time, shows hour:minute:second.00000000000. is there way this? thanks, rik the accuracy depends on file system using, high accuracy file system such ext4, standard implementation of stat uses time_t has 1 second resolution. if have access source of program spitting out files, try setting timestamp part of filename instead , sort on filename rather modification time.

navigation - Retain content on Page1 after navigating to Page2 and back to Page1 in WPF -

on page1 have textbox , combobox , hyperlink control. textbox has value "abc" , combobox has value "123". when click on hyperlink on page1 navigate page2. on page2 click on button takes me page1. i can see values. cannot see values when controls on page1 bound data source. if have xaml this: <textbox: x:name="txtname" text="{binding path = uname}" /> then in page1 navigation page2 , not retaining values in textbox , combobox . is kind of intended behaviour or bug? have remembered set keepalive="true" in page1 xaml?

.net - Domain Event Design Pattern -

i've been reviewing example of domain event design blogged mike hadlow , created udi dahan . currently publishing static events on our domain objects , subscribing them directly within our services, or via our plugin model (we locate , initialize our plugins @ runtime using structuremap). what advantage of using udi's design? it helps avoid memory leaks caused not deregistering event handlers when using c# built-in events.

iphone - How do I call - (void) viewDidAppear:(BOOL)animated from another method? -

it possible call 1 method inside another. i've implemented function - (void)pickanddecodefromsource:(uiimagepickercontrollersourcetype) sourcetype i want call following method inside above one. - (void) viewdidappear:(bool)animated i think understand you're asking... question is.. not there. nonetheless: what think you're asking: "how call viewdidappear within method...?" - (void)pickanddecodefromsource:(uiimagepickercontrollersourcetype)sourcetype { ... [mycontroller viewdidappear:yes]; //simply call on whatever instance of controller have ... } if question "how override viewdidappear?" it: - (void)viewdidappear:(bool)animated { [super viewdidappear:animated]; //your stuff //goes here }

r - Most representative instance of a cluster -

after performing cluster analysis dataset (a dataframe named data.matrix ), added new column, named cluster , @ end (col 27) containing cluster name each instance belongs to. what want now, representative instance each cluster. tried find instance having smallest euclidean distance cluster's centroid (and repeat procedure each 1 of clusters) this did. can think of other -perhaps more elegant- ways? (assume numeric columns no nulls). clusters <- levels(data.matrix$cluster) cluster_col = c(27) (j in 1:length(clusters)) { # subset cluster j data = data.matrix[data.matrix$cluster == clusters[j],] # remove cluster column data <- data[,-cluster_col] # calculate centroid cent <- mean(data) # copy data data.matrix_cl, attaching distance column @ end data.matrix_cl <- cbind(data, dist = apply(data, 1, function(x) {sqrt(sum((x - cent)^2))})) # instances min distance candidates <- data.matrix_cl[data.matrix_cl$dist == min(d...

php - MySQLi equivalent of mysql_result()? -

i'm porting old php code mysql mysqli, , i've ran minor snag. is there no equivalent old mysql_result() function? i know mysql_result() slower other functions when you're working more 1 row, lot of time have 1 result , 1 field. using lets me condense 4 lines 1. old code: if ($r && mysql_num_rows($r)) $blarg = mysql_result($r, 0, 'blah'); desired code: if ($r && $r->num_rows) $blarg = $r->result(0, 'blah'); but there no such thing. :( is there i'm missing? or going have suck , make everything: if ($r && $r->num_rows) { $row = $r->fetch_assoc(); $blarg = $row['blah']; } php 5.4 supports function array dereferencing , means can this: if ($r && $r->num_rows) { $row = $r->fetch_assoc()['blah']; }

Payment gateway with "purchase credits/tokens" to integrate in a php+mysql website? -

do know payment gateway "purchase credits" integrate in php+mysql website? if not clear mean system can buy 50 credits (ala facebook) , can spend them playing games or accessing website restricted content? is has done on side or company sells gateway complete package? the payment gateway doesn't care you're selling. interested in fund transfers card you. you'd have build system manage how many credits user has, how different 'games' cost in credits, etc. basically, payment gate way ask "how charge user?" , when give them detail, they'll come "yes, we've charged x amount" you'll need write script calculate how many credits equals , assign them account. paypal cheapie gateway, if don't know volumes expect (they don't charge monthly fee of rest).

objective-c code formatting -

what way format piece of code? uibarbuttonitem *prev = [[uibarbuttonitem alloc] initwithtitle:@"prev" style:uibarbuttonitemstylebordered target:self action:@selector(setdaterangeclicked:)]; taking question meaning, best way format code use xcode. highlight code format, to edit -> format -> re-indent , have code in "standard" xcode formatting. i've mapped keyboard shortcut alt-cmd-[ used textmate. it's buried under lots of menus, keyboard shortcut handy this. if use textmate, click inside block format , press ctrl-q. textmate has problems style of formatting though.

How can I use jar libraries in Android compiled with packages that Android doesn't have -

i need import couple of jars compiled under full implementation of java. know android doesn't use packages java has offer. question is: possible import them without creating errors? there tool can convert jars android jars? if so, can examples provided. appreciated. is possible import them without creating errors? if jars refer classes android not have, no. is there tool can convert jars android jars? there no such thing "android jars". if have source code jars in question, between modifying source code , modifying copies of missing classes apache harmony, may able stuff working. however, cannot put java.* or javax.* classes in project -- have refactor them new packages. also, depending on classes missing, may take thousands of developer-months accomplish (e.g., reimplementing swing using 2d canvas apis).

Python and SQLite: insert into table -

i have list has 3 rows each representing table row: >>> print list [laks,444,m] [kam,445,m] [kam,445,m] how insert list table? my table structure is: tablename(name varchar[100], age int, sex char[1]) or should use other list? here actual code part: record in self.server: print "--->",record t=record self.cursor.execute("insert server(server) values (?)",(t[0],)); self.cursor.execute("insert server(id) values (?)",(t[1],)) self.cursor.execute("insert server(status) values (?)",(t[2],)); inserting 3 fields separately works, using single line like self.cursor.execute("insert server(server,c_id,status) values (?,?,?)",(t[0],),(t[1],),(t[2],)) or self.cursor.execute("insert server(server,c_id,status) values (?,?,?)",(t),) does not. conn = sqlite3.connect('/path/to/your/sqlite_file.db') c = conn.cursor() item in my_list: c.execut...

html - putting spacing between the leftmost and rightmost cells and the table border -

i making table in html , not want borders of leftmost , right cells extend way till table border. example: | _ ___ | so in above example, while cells have contiguous top border border not extend way till outer table border. great if can give me tips on how this. put div in cell , style border/padding on div instead of table.

language agnostic - Real world use cases of bitwise operators -

what real world use cases of following bitwise operators? and xor not or bit fields (flags) they're efficient way of representing state defined several "yes or no" properties. acls example; if have let's 4 discrete permissions (read, write, execute, change policy), it's better store in 1 byte rather waste 4. these can mapped enumeration types in many languages added convenience. communication on ports/sockets involves checksums, parity, stop bits, flow control algorithms, , on, depend on logic values of individual bytes opposed numeric values, since medium may capable of transmitting 1 bit @ time. compression, encryption both of these heavily dependent on bitwise algorithms. @ deflate algorithm example - in bits, not bytes. finite state machines i'm speaking of kind embedded in piece of hardware, although can found in software too. these combinatorial in nature - might literally getting "compiled" down bunch of logic ...

java - What's the point of package annotations? -

i understand purpose of class annotations, how , annotations used in java? . purpose of package annotations, described in blog post , §7.4.1 of java language specification ? why want associate metadata package? kinds of things do? bnd tool (and maven-bundle-plugin) makes use of package annotations. putting @version , @export annotation in package-info.java allows generate osgi metadata. javadoc uses package annotations. jaxb uses package-level annotations, for example , specify mapping of java type xml schema type package-wide. package annotations used in jboss's xml binding. struts 2 convention plugin uses an annotation specify default interceptor actions in package. there package-level hibernate annotations . example of annotations' usage can found here .

jquery - Javascript Memory Usage -

in following code: $(document).ready(function() { var content = ""; (var = 0; < 1000; i++) { content += "<div>testing...</div>"; } $("#load").click(function() { $("#mydiv").empty(); $("#mydiv").append(content); return false; }); }); load simple link , mydiv simple div. in each major browser tested in, when click on link multiple times, see memory usage go in task manager. in ie, goes each time , stays up. in ff, goes each time, once in while comes down (i think means memory being reclaimed or garbage collected - sign). in chrome, goes each time , stays up. first, code cleaning dom correctly? if so, why memory usage increase every click? note: tried make example simple possible, similar problem having in app. wrap around div tag. immensely , use native innerhtml (its faster). $(document).ready(function() { var content = ""; (var ...

computer vision - how to remove background image and get fore image -

there 2 images alt text http://bbs.shoucangshidai.com/attachments/month_1001/1001211535bd7a644e95187acd.jpg alt text http://bbs.shoucangshidai.com/attachments/month_1001/10012115357cfe13c148d3d8da.jpg 1 background image 1 person's photo same background ,same size,what want remove second image's background , distill person's profile only. common method subtract first image second one,but problem if color of person's wear similar background. result of subtract awful. can not whole people's profile. have idea remove background give me advice. thank in advance. if have estimate of image background, subtracting image person first step. first step. after that, have segment image, i.e. have partition image "background" , "foreground" pixels, constraints these: in foreground areas, average difference background image should high in background areas, average difference background image should low the areas should smooth. outline le...

Is there an official logo of C#? -

i'm working on presentation involves c# (and .net). there kind of official logo of programming language? if so, know of free image source? tried google no avail. i don't know of official logo c# language, however, there logo general "world" of .net. the current .net logo is: alt text http://i49.tinypic.com/2v9xn3b.png this introduced sometime around end of 2008. here's blog post microsoft's scott hanselman details this: pdc 2008: new .net logo however, regarding using logo yourself , please see stack overflow question (and accepted answer): can use .net framework logo on personal calling card? in short, answer no. :(

objective c - iPhone : Getting a value back from views -

from view open view b contains categories in uitableview, when select category open view c contains subcategories category (using coredata persistence ) in uitableview, when select subcategory open view d contains product (using coredata persistence ), when select the product, how can set value view a? avoiding leaks of course... a(mainwindow)->b(uitableview category)->c(uitableview subcategory)->d(uitableview products) d->c(with selected product)->b(with selected product)->a(with selected product) i hope i'm enough understable :d thank you this approach assumes using uinavigationcontroller stack of uiviewcontroller instances, each of having managed object context instance part of core data application. set ivar , @property in application delegate header holds value selected product (an nsmanagedobjectid* , example): nsmanagedobjectid *selectedproduct; ... @property (nonatomic, retain) nsmanagedobjectid *selectedproduct; synthesize iva...

android - Using SharedPreferences and/or class variables in an Activity -

just random question. i'm learning bit of android right now, , in examples, seems lot of common items (such buttons, editboxes etc) requested within each function using (cast) findviewbyid() . is considered or bad practice store result of in activity's member values? simple example: public class myactivity extends activity { private edittext mytext; public void oncreate(blah blah) { // blah this.mytext = (edittext) findviewbyid(r.id.mytext); } } and use mytext field there on. think it'd performance (depending on findviewbyid's inner workings, i'm quite sure it's fast), haven't seen encouraged yet. also, wouldn't first time encountered situation 'caching' leads problems (had case database connections weren't released because remembered connectionmanager or in fashion). secondly, related, if want remember across methods in activity (and later on too, when activity restarted later), wiser keep both class fi...

memory management - How to create pool allocator for abstract base class in C++? -

have run bug glibc's malloc(): http://sourceware.org/bugzilla/show_bug.cgi?id=4349 , thinking work around until updating later version of glibc pooled allocation small objects have many instances coming , going. the small objects derived abstract base class. i'd find pattern (using boost ok) provide pool allocation automatically in base class , have work many derived classes. would done defining operator new() in abstract base class? how organize having different pools each derived class have different actual memory size? one obvious starting point boost pool library. unfortunately, model want 1 doesn't provide yet, although listed sole item under "future directions". otoh, library hasn't been updated in while now. chances of being updated include model seems remote (at least me).

ActiveRecord select a string field has a certain length in Rails 3? -

i've got series of posts , select posts title size lesser 30, how that? posts.where("len(title) < 30")? this should work: post.where("length(title) < 30") you're correctly using #where shorthand :conditions in rails 3. can pass in snippet works in local sql directly. just remember activerecord model classes singular convention.

Silverlight Application Project Structure - How much is too much? -

my team working on creating our first silverlight 4 application. first of give bit of detail on actual project. silverlight 4 designed run out-of-browser , using wfc data services our own implementation of dataobjects. (no entity framework, linq-to-sql, etc). have few consultants in recommending solution structure contains more 11 individual projects. there doesn't seem reason it, can see justification why following might needed? project.client - assets, styles, views project.common - converters, helpers project.data - unknown purpose (client project) project.infrastructure - commands, constants, interfaces, logging project.majorfunctiona - "business logic major function of application" project.majorfunctionb - "business logic major function of application" project.majorfunctionc - "business logic major function of application" project.models - abstracted access wcf services project.uicontrols - custom controls ui project.unittests...

php - Compare given date with today -

i have following $var = "2010-01-21 00:00:00.0" i'd compare date against today's date (i.e. i'd know if $var before today or equals today or not) what function need use? strtotime($var); turns time value time() - strtotime($var); gives seconds since $var if((time()-(60*60*24)) < strtotime($var)) will check if $var has been within last day.

c# - Problem invoking custom membershipprovider from aspx page deployed in Sharepoint -

i've implemented custom membershipprovider , roleprovider use forms auth on sharepoint site. this works fine, , sharepoint invokes methods on both custom providers without problems. i'm trying use membership.createuser new aspx page deployed sharepoint fails "the membership provider name specified invalid. parameter name: providername" (i've tried deploying page under \12 folder , in content db site collection). i've tried invoking membership.creatuser custom roleprovider, , works fine. the membershipprovider configured in web.config , default provider. do need special access membership aspx page deployed in sharepoint custom pages deployed _layouts don't use web.config under inetpub. need add membership provider web.config in _layouts/ folder (in 12 hive) - best practices dictate create subfolder this: 12/templates/layouts/(myapp)/mypage.aspx (web.config goes here membership/role stuff configured). make sense? -oisin

ajax - Does an HTTP Status code of 0 have any meaning? -

it appears when make xmlhttprequest script in browser, if browser set work offline or if network cable pulled out, request completes error , status = 0. 0 not listed among permissible http status codes. what status code of 0 mean? mean same thing across browsers, , http client utilities? part of http spec or part of other protocol spec? seems mean http request not made @ all, perhaps because server address not resolved. what error message appropriate show user? "either not connected internet, or website encountering problems, or there might typing error in address"? i should add see behavior in firefox when set "work offline", not in microsoft internet explorer when set "work offline". in ie, user gets dialog giving option go online. firefox not notify user before returning error. i asking in response request "show better error message". internet explorer good. tells user causing problem , gives them option fix it. in order ...