Posts

Showing posts from May, 2011

language agnostic - When should I consider the performance impact of a function call? -

in recent conversation fellow programmer, asserted "if you're writing same code more once, it's idea refactor functionality such can called once each of places." my fellow programmer buddy instead insisted performance impact of making these function calls not acceptable. now, i'm not looking validation of right. i'm curious know if there situations or patterns should consider performance impact of function call before refactoring. "my fellow programmer buddy instead insisted performance impact of making these function calls not acceptable." ...to proper answer " prove it. " the old saw premature optimization applies here. isn't familiar needs educated before more harm. imho, if don't have attitude you'd rather spend couple hours writing routine can used both 10 seconds cutting , pasting code, don't deserve call coder.

What is the correct way to transfer/pass an xml document/string to php from javascript or jquery -

i obtaining xml remote server using jquery. i creating xml document using $.parsexml() in jquery, (which new version 1.5 of jquery) that side of things works well, not sure best way pass xml document php file contents can saved mysql database. it doesnt seem possible pass xml php variable via method. does xml document need serialized? should using $.parsexml() prior sending php script or not? there must correct way this? any discussion on welcome? post it. http://api.jquery.com/jquery.post/

c# - Amazon SimpleDB high latency on first request -

i'm using simpledb in desktop application (c#, .net 2.0) , have problem high latency. first time make request db (query, insert values - doesn't matter) response after 10-20 seconds. happens first time, rest of responses pretty fast (haven't measured, under 300ms sure). doesn't happen when create db client, when first request. normal authentication slow? (i presume on first request authentication done). thanks in advance. edit when run first time selectresponse response = dbservice_.select(request); in output panel get: 'photoexchange.vshost.exe' (managed (v2.0.50727)): loaded'c:\windows\assembly\gac_msil\system.data.sqlxml\2.0.0.0__b77a5c561934e089\system.data.sqlxml.dll' 'photoexchange.vshost.exe' (managed (v2.0.50727)): loaded 'system.xml.xsl.compiledquery.1' 'photoexchange.vshost.exe' (managed (v2.0.50727)): loaded 'system.xml.xsl.compiledquery' first chance exception of type 'system.io.filen...

sql - MySQL query finding values in a comma separated string -

i have field colors (varchar(50)) in table shirts contains comma delimited string such 1,2,5,12,15, . each number representing available colors. when running query select * shirts colors '%1%' red shirts (color=1), shirts who's color grey (=12) , orange (=15). how should rewrite query selects color 1 , not colors containing number 1? the classic way add comma's left , right: select * shirts ',' + colors + ',' '%,1,%' but find_in_set works: select * shirts find_in_set('1',colors) <> 0

Objective-C convenient manners -

i spent time objective-c , see it's religious (especially experienced) programmers. , catch manners. can tell me can find these holy rules? for example i'm confused of naming constants, or keys. should kname or namekey or namekey ? or... i noticed ivars declared _ or __... want clear code. thanks! check these articles cocoa , objective-c style , conventions: http://cocoadevcentral.com/articles/000082.php http://cocoadevcentral.com/articles/000083.php http://cocoawithlove.com/2009/06/method-names-in-objective-c.html

To delete the directory(folder) in the linux server using php code? -

i want delete folder in linux server using php ?? scenario:: when user uploads images , new folder created based on name...when delete user account,his named folder should deleted.. use unlink , rmdir. calling unlink($file) delete file filename $file , non recursive (it deletes 1 file @ time, , won't delete directory if not empty). there tons , tons of examples recursively delete directory here : http://fr2.php.net/unlink

php - Setting default setting for all jQuery-UI datepicker instances -

i using jquery-ui datepicker (via zendx view helper) select dates. set default settings (setdefaults) sets default setting datepicker instances. this how form looks like: <form method="post" action="/hello/world"> <?php echo $this->datepicker("dp1",'',array( 'defaultdate' =>date('y m d',time()), 'showweek' => 'true', 'firstday' => 1, 'dateformat' => 'dd.mm.yy', 'changeyear' => 'true', 'changemonth' => 'true' )); echo $this->datepicker("dp2",'',array()); ?> <input type="submit" value="submit...

batch file - What does %~dp0 mean, and how does it work? -

i find %~dp0 useful, , use lot make batch files more portable. but label seems cryptic me... ~ doing? dp mean drive , path? 0 refer %0 , path batch file includes file name? or weird label? i'd know if documented feature, or prone deprecated. calling for /? in command-line gives syntax (which can used outside for, too, place can found). in addition, substitution of variable references has been enhanced. can use following optional syntax: %~i - expands %i removing surrounding quotes (") %~fi - expands %i qualified path name %~di - expands %i drive letter %~pi - expands %i path %~ni - expands %i file name %~xi - expands %i file extension %~si - expanded path contains short names %~ai - expands %i file attributes of file %~ti - expands %i date/time of file %~zi - expands %i size of file %~$path:i - searches directories listed in path environment variable...

machine learning - The Role of the Training & Tests Sets in Building a Decision Tree and Using it to Classify -

i've been working weka couple of months now. currently, i'm working on machine learning course here in ostfold university college. need better way construct decision tree based on separated training , test sets. come idea can of great relief. thanx in advance. -neo you might asking more specific, in general: you build decision tree training set, , evaluate performance of tree using test set. in other words, on test data, call function named c*lassify*, passing in newly-built tree , data point (within test set) wish classify. this function returns leaf (terminal) node tree data point belongs--and assuming contents of leaf homogeneous (populated data single class, not mixture) have in essence assigned class label data point. when compare class label assigned tree data point's actual class label, , repeat instances in test set, have metric evaluate performance of tree. a rule of thumb: shuffle data, assign 90% training set , other 10% test set.

entity framework 4 - EF 4: Referencing Non-Scalar Variables Not Supported -

i'm using code first , trying simple query, on list property see if contains string in filtering list. running problems. simplicity assume following. public class person { public list<string> favoritecolors { get; set; } } //now code. create , add dbcontext var person = new person{ favoritecolors = new list<string>{ "green", "blue"} }; dbcontext.persons.add(person); mydatabasecontext.savechanges(); //build var filterby = new list<string>{ "purple", "green" }; var matches = dbcontext.persons.asqueryable(); matches = p in matches color in p.favoritecolors filterby.contains(color) select p; the option considering transforming json serialized string since can perform contains call if favoritecolors string. alternatively, can go overboard , create "color" entity thats heavy weight. unfortunately enums not supported. i think problem not collection, reference matches ....

api design - API Endpoint Semantics -

is api endpoint 'method', https://api.foursquare.com/v2/venues/ or full url including non-query-string parameters https://api.foursquare.com/v2/venues/5104 in other words, these 2 separate endpoints or considered same endpoint? http://myapi.com/somemodel/1 http://myapi.com/somemodel/2 according this wikipedia article , endpoint web service, defined wsdl file, and does nothing more define address or connection point web service. typically represented simple http url string. microsoft uses term endpoint in various contexts , amount same thing: endpoint entire interface, not 1 particular method. in context of rest endpoint, endpoint contain requisite get, put, post , delete methods (as applicable).

Developing for Silverlight using Javascript - is this possible? -

my tech lead told me possible develop silverlight apps solely javascript. did googling , binging; likes primary development method developing pre silverlight 2.0. seems have lost favor c# of sl 2.0. is still possible develop silverlight apps solely javascript? know silverlight , browser have extensive scripting capabilities , can scripted via js; can build sl app it? it still possible, though experience different. must load initial root visual element via source property on silverlight object referencing xaml file on server, after have full access visual tree via javascript. the below test.html , root.xaml files produce testable page if placed in same folder. note differences "standard" (i.e. *.xap source) scenario - 'source' parameter on sl object tag set .xaml file instead of .xap file. .xaml file different in default sl application in vs: x:class="myapp.mainpage" missing root element, , root element grid (or visual element) instead of...

java - Why does the same code work in a servlet but not in a Spring controller? -

this code works in servlet: picasawebservice service = new picasawebservice("picasa test"); picasawebclient picasaclient = new picasawebclient(service); list<albumentry> albums = picasaclient.getalbums("cgcmh1@gmail.com"); for(albumentry album: albums){ resp.getwriter().println(album.gettitle().getplaintext()); list<photoentry> photos = picasaclient.getphotos(album); req.setattribute("photos", photos); } so tried putting in spring controller using model.addattribute (below) instead of req.setattribute (above): picasawebservice service = new picasawebservice("picasa test"); picasawebclient picasaclient = new picasawebclient(service); list<albumentry> albums = picasaclient.getalbums("cgcmh1@gmail.com"); (albumentry album : albums){ logger.warn("albums:" + album.gettitle().getplaintext()); list<photoentry> photos = picasaclient.getphotos(album); model.addattribute("...

ajax - jquery: auto reload/update page element? -

hey guys, want upgrade specific page element every minute. i know how use jquery load() function reload element on page this. $('.mostliked').load("http://mypage.com" + " .mostliked >*", function() { //callback }); that works fine because .mostliked element in sidebar. however need update element can not grab it's content other page in sidebar example. var reload = 60000; setinterval(function() { $('ul.rating').each(function() { //simply reload element every minute }) //update sidebar widget $('.mostliked').load("http://mypage.com" + " .mostliked >*", function() { //callback }); }, reload); how can solve problem? thank you check under heading "loading page fragments" on page: http://api.jquery.com/load/ in order "reload" ul.rating elements, need fetch current page in background (using load or method), , ca...

c++ - Programmatic way to find the Windows OS volume? -

i understand not recommended assume drive letter c: reserved os volume. there straightforward way answer question - volume windows os reside on?. volume can drive letter or volume guid or other way volumes identified. note looking os partition not same system partition. getwindowsdirectory() , break path _splitpath . edit: changed getsystemdirectory getwindowsdirectory. in practice results should same.

php - mybb - how to check for new private messages -

i'm trying build chrome app/extension website mybb forum. wondering if knows how check see if user has new pm's or maybe new posts on thread? maybe js, ajax, or php as far events go, pm's there field in database called 'read', false if haven't opened it, , true if have. on page load, check see if there messages user 'unread', , if so, load them, , use jquery make pop saying short description of them. have small ajax script periodically check this. as far new posts go, traditional way i've seen done (but no means best way) keep timestamp of when user last visited site. on page load, every new post/topic created after timestamp, serialize data , store in database, or in cookie (if serialized data exists, unserialize it, merge 2 , reserialize it). if user visits topic, data serialized entry matches (ie, in same topic, or post number) , remove serialized data. again on page load or using ajax script, check periodically if have 'unread...

asp.net - Help Me Understand AutoMapper -

what point of automapper? give me simple example? i have watched video on it, not clicking. sam typically automapper great @ mapping between data entities , business models. e.g., lets instance, have data domain type, call personentity , , has array of properties: firstname , surname , gender etc. don't want expose data domain type through consuming application, can define business domain types, e.g. person , person type can contain additional business logic, such getrelatedpersons , etc, may not functionality tied data domain. in case, have 2 types, personentity , person @ point have write boilerplate code copy properties 1 other. variety of ways, could: 1.copy constructor: public person(personentity entity) { 2.generalised mapping method: public person createperson(personentity entity) { 3.implicit/explicit conversion: public static implicit operator person(personentity entity) { but automapper allows do, create mapping process between 2 types...

sql - Does defining foreign keys and table relationships have any effect on writing queries? -

i putting table in mysql workbench , defining many-to-one relationships , keys foreign keys etc, , know put in actual create script. i'm wondering, make sure data model logical behind scenes point of view, or can relationships used in queries @ all? if can be, operations involve them? (brief example code wonderful) i'm building sqlite database in sqlitemanager firefox plugin. has no options define these things, , i'm wondering if should care. (i've done pretty straightforward queries point). in reality, can create join between 2 tables columns. whole reason of having primary , foreign keys enforce relationship between 2 tables. in word, in order add row in child table, need have parent table's primary key serve foreign key in child table. otherwise, insertion fail. another reason using foreign key allow parent table perform cascade delete. way, don't have manually delete rows child table first, delete parent table.... if have cascade delete set ...

asp.net - Windows phone 7 consume from Controller -

i have been reading adding webservice mvc project , how might conflict mvc structure. added webservice , works windows phone 7, receives number, (it's simple application). added webservice right clicking controller folder , selecting add new item->webservice. using soap support integrated in visual studio. wondering if there way instead of adding webservice windows phone 7 receives , sends data directly controller. windows phone 7 communicates right clicking on solution explorer , adding service reference. thanks! i read asp.net mvc & web services if you're wanting use "add service reference" in wp7 project you'll need expose wcf web service project. if you're prefer create simpler rest based discussed in asp.net mvc & web services won't able use "add service reference" can still use service either through building own client on top of webclient, there few libraries this. recommend hammock .

Java SystemTray icon -

Image
there a simple tutorial on implementing system tray icon . the problem is, can see icon in tray if run app eclipse, can't see if export , run runnable jar file. have other images in app work fine form same folder. the tray working (left , right click on it) doesn't show image, can see in image (the jar file on top, eclipse on bottom): why? thank , sorry english! edit : found solution image need accessed whit: image img = toolkit.getdefaulttoolkit().getimage(myclass.class.getresource("/images/asd.png")); the problem way include image file. will have include image in jar when create it, , have access image in different manner: try { inputstream = classloader.getsystemclassloader().getresourceasstream("wing16.png"); bufferedimage img = imageio.read(is); } catch (ioexception e) {} you can used img variable set image in jar. update: take of class files & images , go command line: jar -cvfm test.jar manifest.mft *....

security - Secure Ajax with Flash -

in order secure ajax requests, ran bar-zik sugested "create small flash file receive data, salt , encrypt md5. sent server. attacker able see data encrypted." has done want share code world? :-) mr ran bar-zik mistaken. security system has proposed violates cwe-602 , "(in) security though obscurity ". in short problem server providing data client side application. client can whatever pleases. can modify javascript code or intercept , modify communications using tamperdata or burp proxy. flash application can decompiled , secrets stored in memory can obtained debugger ollydbg . there no solution problem.

Why are C and C++ different even after compilation? -

i guessed still surprised see output of these 2 programs, written in c , c++, when compiled different. makes me think concept of objects still exist @ lowest level. add overhead? if impossible optimization convert object oriented code procedural style or hard do? helloworld.c #include <stdio.h> int main(void) { printf("hello world!\n"); return 0; } helloworld.cpp #include <iostream> int main() { std::cout << "hello world!" << std::endl; return 0; } compiled this: gcc helloworld.cpp -o hwcpp.s -s -o2 gcc helloworld.c -o hwc.s -s -o2 produced code: c assembly .file "helloworld.c" .section .rodata.str1.1,"ams",@progbits,1 .lc0: .string "hello world!\n" .text .p2align 4,,15 .globl main .type main, @function main: pushl %ebp movl %esp, %ebp andl $-16, %esp subl $16, %esp movl $.lc0, 4(%esp) movl $1, (%esp) c...

c# - IOException File Copy unhandled. When uploading image from a picturebox -

help! can't figure out how close file. gives me ioexception file, it being used process here's code private void uploadpic_btn_click(object sender, eventargs e) { open_dialog = new openfiledialog(); open_dialog.title = "open picture"; open_dialog.filter = "jpeg (*.jpg;*.jpeg;*.jpe;*.jfif)|*.jpg"; if (open_dialog.showdialog() != dialogresult.cancel) { uploadpic_pb.backgroundimage = image.fromfile(open_dialog.filename); uploadpic_pb.backgroundimagelayout = imagelayout.stretch; uploadpic_pb.borderstyle = borderstyle.fixedsingle; } } private void savebtn_click(object sender, eventargs e) { string targetpath = path.combine(path.getdirectoryname(application.executablepath), "\\pictures"); string destfile = path.combine(targetpath, "copied.jpg"); if (!directory.exists(targetpath)) { directory.createdirectory(targetpath); } file.copy(open_dialog.filename...

linux - Count function calls by name or signature. Gcc, C++ -

i have c++ written package. linux, gcc. can modify compilation process (change makefile, flags, etc.), can not change c++ source code. one runs package different parameters, job , exits. how count : 1) number of calls of function specific name? 2) number of calls of functions specific signature? 3) number of calls of functions 1 of parameters of specific type i.e. std::string (type specified signature)? 4) , extra number of calls of functions of stl objects, i.e. std::string copy constructor? (i mean count number of calls during run. ) i thought gdb, found tough (1) , have not found how (2)-(4) @ all. all acceptable answers write here humanity. you can try running dtrace under linux. it's great tool trying accomplish.

iis - localhost and IP Address issue -

i have irritating problem on web development. have issue regarding usage of http://localhos t , ip address http://10.xxx.xx.x . if access website using localhost 127.0.0.1, renders good, when access on other workstation, rendering bad. tried use ip address, looks same others can see. developer first time encountered because first time using iss web servers. dont know if iis problem or me. hehe.. 1 thing im using server side program im updating , seems when use ip address, update has not been displayed. took day or 2 update it. there here experience same problem , fixed it. or there iis guru's here can me. dont know do. im having inconsistent website. :( thank in advance. check through html , check urls point resources within site. make sure start / instead of http://localhost/ or http://127.0.0.1/ . example, replace http://localhost/images/logo.png /images/logo.png it great if add more details question. also, might try using firebug extension firefox determine i...

c# - Catching an exception and clearing it before ELMAH gets it -

i have problem have exception being thrown capturing in global.asax. part of exception handling redirect user specific page because of exception. i have elmah error handling email module plugged in. not want receive emails exception. don't want add type of exception elmahs ignore list, in case want granular work around exception (i.e., if matches properties, happens on pages) i want to: write application_onerror redirects user page (i know how part, more procedure i've left here) in application_onerror stop elmah receiving error after i've caught it i calling server.clearerror() inside app_onerror method, still receiving these emails. as per elmah documentation i put leave application_onerror method in global.asax add following global methods: void errorlog_filtering(object sender, exceptionfiltereventargs args) { filter(args); } void errormail_filtering(object sender, exceptionfiltereventargs args) { filter(args); } void filter(ex...

OpenCV cvMatchTemplate same image size -

i trying find normalized cross correlation between 2 1-by-1 images. in order this, i'm using cvmatchtemplate. after using cvminmaxloc, maxval returns 1.00000 2 1-by-1 images. so tried bypass trying use cvmatchtemplate on 6-by-3 image , 3-by-3 image. each original pixel, expanded out 6-by-3 , 3-by-3 see if provide better results. doesn't. maxval still returns 1.000000. there better way find ncc between 2 pixels? cvsetimageroi(img, cvrect(curwidth, curheight, 1, 1)); iplimage* temproi = cvcreateimage(cvsize(1, 1), img->depth, img->nchannels); cvcopy(img, temproi); cvresetimageroi(img); iplimage* currentroi = cvcreateimage(cvsize(6,3), img->depth, img->nchannels); (int = 0; < 3; i++) { (int j = 0; j < 6; j++) { cvsetimageroi(currentroi, cvrect(j, i, 1, 1)); cvcopy(temproi, currentroi); cvresetimageroi(current...

html - jQuery coin slider plugin -

i trying implement jquery coin slider plugin on web page. downloaded requisite coin slider script here. http://workshop.rs/projects/coin-slider/ though should have been working not getting images on webpage. here's full html of page trying this. http://pastebin.com/s60ju1cf is thing wrong in here? why not getting images on webpage? cipher, think need double check work. link included plugin has easy follow examples. i've worked many 3rd party plugins , appears did job of showing how make work.

How to save jquery selector for later use -

i have following code... $('#item_' + code + ' .delete').hide(); $('#item_' + code + ' .deleting').show(); $('#item_' + code).slideup(400, function() { $(this).remove(); $('#top .message').html('item has been deleted'); }); i want save selector i'm using in variable , use perform operation instead of searching dom everytime. so save selector this... var saved = $('#item_' + code); but how change rest of code? i'm not familiar jquery, hence wondering how can done. work... $(saved).(' .delete').hide(); $(saved).(' .deleting').hide(); $(saved).slideup(400, function() { $(this).remove(); $('#top .message').html('item has been deleted'); }); i'll add alternative $('.delete', saved).hide(); $('.deleting', saved).show() ...

html - How to check radio button on drop select -

i have radio input selected when user select drop down. radio input has name "rbutton" , id same. clarify, using html forms. thanks. try using small bit of javascript. here onclick action on drop down menu calls selectradio function creates checked radio button. <script type="text/javascript"> function selectradio(){ document.getelementbyid('span1').innerhtml = '<input type="radio" checked="true"/>'; } </script> <form> <p><span id='span1'><input type="radio"/></span> radio button</p> <p>choose option:</p> <select onclick='selectradio()'/> <option>1</option> <option>2</option> <option>3</option> </select> </form>

android - intent pass the same values to service class -

i have pass intent values service class every time intent take same value took @ first time need every time different intent values. intent alarmintent = new intent(appointmentactivity.this, alarmservice.class); alarmintent.putextra("appdate", appdatestring); alarmintent.putextra("apptime", appoint_time); alarmintent.putextra("appdesc", appoint_desc); alarmintent.putextra("appremind", appoint_remind); sender = pendingintent.getservice(appointmentactivity.this, 0, alarmintent, 0); alarmmanager = (alarmmanager) getsystemservice(alarm_service); am.set(alarmmanager.rtc_wakeup, calendar.gettimeinmillis(), sender); replace pendingintent.getservice to: sender = pendingintent.getservice(appointmentactivity.this, 0, alarmintent, pendingintent.flag_update_current); see if works. the flag important , 0 might not allowed value.

html - width of floated div pushed down -

i have floated 2 divs left div on right has huge text(without br s) , pushed down what should in css such make sure right div not push down i had tried giving width width not take rest of screen different computers have different screen sizes... http://jsfiddle.net/4zgmj/ thanks pradyut you have set width @ least 1 element. example: http://jsfiddle.net/4zgmj/6/

Search text for specific keywords at start and end in php -

i have following string $url_part = 'p=link&u=shuja&sort=recent'; i want string start p= , end & in such way, $page = 'link'; and may exist anywhere in $url_parts. remove same that $url_part = 'u=shuja&sort=recent'; $url_part = 'p=link&u=shuja&sort=recent'; $params = array(); parse_str($url_part, $params); $page = isset($params['p']) ? $params['p'] : null; unset($params['p']); $url_part = http_build_query($params);

What's the difference between these two enum declarations - C? -

i've started learning c , have reached point of enums. enum preferred alternative define / const int , correct? what's difference between these 2 declarations? #include <stdio.h> // method 1 enum days { monday, tuesday }; int main() { // method 1 enum days today; enum days tomorrow; today = monday; tomorrow = tuesday; if (today < tomorrow) printf("yes\n"); // method 2 enum {monday, tuesday} days; days = tuesday; printf("%d\n", days); return 0; } an enumeration should preferred on #define / const int when want declare variables can take on values out of limited range of related , mutually exclusive values. days of week good example, bad example: enum aboutme { myage = 27, mynumberoflegs = 2, myhousenumber = 54 }; going code example; first method declares type called enum days . can use type declare many variables like. the second method de...

In Linux shell do all commands that work in a shell script also work at the command prompt? -

i'm trying interactively test code before put script , wondering if there things behave differently in script? when execute script has own environment variables inherited parent process (the shell executed command). exported variables visible child script. more information: http://en.wikipedia.org/wiki/environment_variable http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm by way, if want script run in same environment shell executed in, can point command: . script.sh this avoid creating new process shell script.

c# - ASP.Net GridView - fire datarow click event except on checkbox selection -

i'm implenting functionality of inbox have gridview , code follows: <asp:gridview width="100%" id="grdinbox" autogeneratecolumns="false" allowpaging="true" runat="server" onrowcommand="grdinbox_rowcommand" gridlines="none" cssclass="mgrid" pagerstyle-cssclass="pgr" alternatingrowstyle-cssclass="alt" onrowdatabound="grdinbox_rowdatabound"> <columns> <asp:templatefield> <itemtemplate> <asp:checkbox id="mailselector" runat="server" /> </itemtemplate> </asp:templatefield> <asp:boundfield datafield="sender" headertext="sender" sortexpression="sender" /> <asp:boundfield datafield="subject" headertext="subject" sortexp...

c# - Use DBML model but different connection string for same model on different machine -

i hope title isnt confusing. here plan do: say have 10 individual servers located in 10 individual sites across country. have database , front end desktop application. now have website have same database structure/model 10 servers hold on it. use linq sql set queries change connection string datacontext before executing query. so have database on webserver serve shell if can create relational queries based on webserver database , send updated information whichever server changing connection string of datacontext. as mentioned database structure same across individual database , webserver database. using dbml structure have created locally in code update data , change connection string. make sense? wanting confirm if missing anything we have situation that. simplified, our web.config file contains entries like: <appsettings> <add key="server1_connectionstring" value="data source=myserveraddress;..."/> then in code, can: ...

c# - split a string in to multiple strings -

123\r\n456t\r\n789 how can split string above in multiple strings based on string text .split has on load takes char :( string.split has supported overload taking array of string delimiters since .net 2.0. example: string data = "123text456text789"; string[] delimiters = { "text" }; string[] pieces = data.split(delimiters, stringsplitoptions.none);

objective c - Problem calling class methods (Q:1) -

i'm trying convert old 'c' program containing static methods obj-c i'm having few problems getting compile. in header file i've got: @interface anneal : nsobject ... ... +(float)approxinitt; -(costtype)simulatedannealing; ... and in implementation file, 2 problem methods (also cut-down brevity): @implementation anneal +(float)approxinitt { float t=0.0; int m2=0; ... if(m2==0) t = t_lifesaver; else t = t / m2 / log(initprob); return t; } -(costtype)simulatedannealing { float t; ... if(tset) t=initialt; else t=[self approxinitt]; // error:incompatible types in assignment } unfortunately i'm getting "incompatible types in assignment" error though 't' , return class method both of type 'float'. while code contains multiple source files (from i'm expecting hit few more problems in next few days), they're both in same one. problem caused erro...

c - Seg fault with time and ctime, when porting from Linux to OSX -

i getting errors compiling code designed (i believe) linux on osx. have tracked down issue section of code: timeval = time(null); char* timestring = ctime(&timeval); timestring[24]=' '; fprintf(log, "[ %20s] ", timestring); is there reason why might case? have included <time.h> . ctime using statically allocated buffer of size, first problem you're appending string without knowing size. timestring[24]=' '; this might cause segfault on it's own if buffer 24 bytes. cause might if zero-termination happens @ index 24, made string unterminated, , fprintf continue reading until hits memory it's not allowed read, resulting in segfault. use ctime_r preallocated buffer if want modify it, , make sure buffer large enough hold data, , zero-terminated after you're done it. if ctime_r isn't available, strncpy own buffer before modifying. hth edit i'm not sure you're trying do, assuming code posted ta...

Silverlight debugging; not attaching process -

Image
i use google chrome default browser prefer use internet explorer debugging silverlight applications. therefore set web project properties , check silverlight debugger option. this has worked fine ages since returning vacation find iexplore.exe process running silverlight no longer attached debugger , must attach manually. when not debugging app can check debug | attach process... dialog , see there no instances of iexplore.exe running. hit f5 , start debug session , again, after there 2 instances, 1 of attached, not 1 running silverlight. once attach other too, debugging works fine , can hit breakpoints , step through code no problem. any ideas on i'm missing debugger attaching correct process appreciated. chrome default os browser, use ie sl debugging. what find aspx page in hosting web project in solution view of visual studio. right-click file , select browse with . you'll presented dialog. select ie list of browsers , press set default button. cancel...

jquery - What is the easiest way to replicate the tags textbox that is used in the stackoverflow questions page -

i building asp.net-mvc website , want support tagging on each page. want replicate inteface , ui used on stackoverflow (include both behavior , layout, css). what easiest way leverage this. there jquery plugin used or homegrown? this jquery plugin seems pretty close: http://code.drewwilson.com/entry/autosuggest-jquery-plugin update link : https://github.com/drewwilson/autosuggest

math - Intersection between line and Grid resources -

i using 2-dimensional grid system x, y coordinates. closest example using can found in here . i can find length of each segment of line in each multiplied value (could elevation, or other number) of cell. the question is: want mathematical formula represents process. if have references or similar works, please refer them me.

flash - How to call a function that is declared into the main SWF from a loaded .as script? -

i have 2 functions declared on timeline of .fla; xmlloader1 , randomnumber . now, need execute command: xmlloader1.load(new urlrequest("http://67.23.233.236/~champate/djsoftlayer/reporte/estado.php?playa=489&nocache="+randomnumber())); .as script loaded, logic, compiler gave me error because function not exist on .as. so, how can modify command in order tell .as script need search functions on .fla ??? thanks! in 1 of classes in swf file loading second swf can have this: private var loader:loader; private var secondswf:displayobject; private function loadsecondswf():void { loader = new loader(); // should handle error events... loader.loaderinfo.addeventlistener(event.complete, loader_completehandler); loader.load(new urlrequest('path/to/second/file.swf'); } private function loader_completehandler(event:event):void { secondswf = loader.content; if (secondswf.hasownproperty('xmlloader1') { var xml...

css - html div floating and sizing -

i want make web page uses 100% of screen space. have 2 divs: 1st - menu fixed width (~250px) 2nd - whats left the misleading part me menu div not in 2nd div. both in wrapper div (100% width). problem if write 100% width 2nd div, goes below menu. if write less %, cannot sure how displayed in smaller resolutions. is there negative sizing or something? atm. 1st div floats left , 2nd div float right. udpate: here code: div.main { width: 100%; } div.1st { width: 250px; float: left; } div.2nd { width: 100%; #here should space left in main div# float: right; } <div class="main"> <div class="1st">menu</div> <div class="2nd">content</div> </div> problem: content wide needs if string or objects in big enough 2nd div goes below 1st. menu width fixed. update #2: if leave content width empty goes below menu since content wide enough take @ post, there have correct solution: http://w...

sql server - SQL - Audit log table design - Which would you prefer? -

for project company i'm working on setting up, in need of auditing (storing logs) various of tasks (changes made tables in system) users perform. currently, there 3 different types of tasks. may grow in future. my suggestion following schema table's , relationships (example): table auditlog ------------------------------ id | pk description created and every task: table exampletaskauditlog ------------------------------ exampletaskid | fk pk auditlogid | fk pk and: table anotherexampletaskauditlog ------------------------------ anotherexampletaskid | fk pk auditlogid | fk pk basically, every kind of task need audit, have new table holding relationship. what developer suggested, following: table auditlog ------------------------------ id (pk) description created exampletaskid | nullable anotherexampletaskid | nullable type | (an integer id indicates whether "example task" or "another example task"). basically, if create log "examp...

c++ - Does hash_map.erase invalidate all iterators? -

std::hash_map not part of c++ standard part of extensions standard library. example defined vs2005 . std::hash_map.erase invalidate iterators std::hash_map ? presumably, memory can reallocated smaller array when elements removed optimize memory usage. so hash_map.erase invalidate iterators? it looks specified in vs2005 example in documentation: each element contains separate key , mapped value. sequence represented in way permits lookup, insertion, , removal of arbitrary element number of operations independent of number of elements in sequence (constant time) -- @ least in best of cases. moreover, inserting element invalidates no iterators, , removing element invalidates iterators point @ removed element.

yahoo - YQL equivalent of MySQL's 'INTERVAL'? -

i have job postings board i'm running in php/mysql , thinking of trying run in yql , google docs instead. have line of mysql fetches job postings have been posted in last 60 days only: $sql = "select * `job` curdate( ) <= date_add( `postdate` , interval 60 day ) order `postdate` desc;"; is there yql equivalent of this? (the format of timestamp column in spreadsheet of form submissions in google docs is: 2/11/2011 10:23:37 yql doesn't have option of custom functions within queries, curdate() , date_add() , etc. out of question. however, there no reason why not craft queries like: select * job postdate > $date order postdate desc; where $date integer timestamp (if available in google doc?). or, select * job interval = 60; this latter query need bespoke data table interpret query parameter(s) , format query against google doc. advantage of crafting own table able use javascript (in <execute> block) perform server-side processi...

iphone - iOS - Rotation with a Nav Controller -

it's small annoying issue. i'm using navigation controller , not rotate. using code before without navigation controller , rotating beautifully. isn't calling "-(bool)shouldautororatetointerfaceorientation..." i'm @ bit of loss. thanks in advance. edit: , yes have "-(bool)canbecomefirstresponder" set. edit2: have calling "-(bool)shouldautororatetointerfaceorientation..." when app first runs , @ point screen rotated when shows navcontroller sets portrait mode... there's problem uiwindow propagating these events view controllers other root one. if you're adding controller directly uiwindow , isn't first 1 you've added, add root view instead. otherwise, you'll need take @ implementing own rotation transformations. i've got uiviewcontroller subclass heavy lifting on github here .

java - Close ModalWindow on keypress -

i able close modalwindow when user presses key, in case esc. i have javascript listener keypress calls click event of cancel button's id: jquery("#"+modalwindowinfo.closebuttonid).click(); is correct way it? i wondering because works in chrome not in ff, due specific implementation. the 'right' way call server, close response. can ajax behavior: modaltestpage.java public class modaltestpage extends webpage { public modaltestpage(pageparameters parameters) { super(parameters); final modalwindow modal = new modalwindow("modal"); modal.setcontent(new fragment(modal.getcontentid(), "window", this)); add(modal); add(new ajaxlink<void>("link") { @override public void onclick(ajaxrequesttarget target) { modal.show(target); } }); add(new closeonescbehavior(modal)); } private static class cl...

c# - Free WPF obfuscator / protect from reverse engineering? -

possible duplicate: obfuscator supports wpf properly i looking free wpf obfuscator protect code inside application, includes api key. i have seen dotfuscator understand free version not include obfuscating wpf applications. how should go protecting application reverse engineering? thanks the question has been asked around here several times before. have look: https://stackoverflow.com/questions/805549/free-obfuscation-tools-for-net anyhow, seems eazfuscator : http://www.gapotchenko.com/eazfuscator.net choice. update: eazfuscator.net not obfuscate wpf xaml, knowledge, don't know free tool does. paid version can though; see http://www.preemptive.com/products/dotfuscator/compare-editions

c# - Testing a repository with MSTest and Moq - .Verify not working -

i looking @ writing unit tests basic execution timer moq. there function called when timer stopped adds timings database , need test insert has been called. have used similar kind of test test inserts via homecontroller being done directly. // calls addtolog() iterates through list // adding entries database _timer.stop(); _repository.verify(x => x.insert(timerobject)); the error receiving is: expected invocation on mock @ least once, never performed: x => x.insert(.splittimer) performed invocations: itimersrepository.insert(ef.domain.entities.timer) itimersrepository.insert(ef.domain.entities.timersplit) itimersrepository.save() the addtolog() method defiantly being called , calling .insert repository. i'm not sure why comes not being called? any ideas great. thanks _timerrepository.verify(x => x.insert(it.isany<timer>())); this trick needed. checks see if insert has been triggered type of timer , not specific (since cant object creat...

java - Where to get the Oracle Security Developer Tools -

i want use methods of oracle security developer tools crypto java api. for example http://download.oracle.com/docs/cd/b31017_01/security.1013/b25378/index.html . but didn´t found can (download / buy) them. tell me stupid, please tell me also, can them. i searched half day in web , found api reference never link download it. sorry, if obviously, don´t see it. well, on assumption have valid oracle installation, from docs : the oracle security developer tools installed oracle application server in oracle_home. if don't have access install, ask hosting team them you. few quick searches on usual jar-finding sites seem indicate oracle security tools pay-for-play , aren't legally available outside of oracle purchase.

c# - How can subclasses share behavior when one already derives from a different base class? -

i have 2 classes implement isomebehavior. want them share functionality. replace isomebehavior abstract class, somebehaviorbase. problem 1 of subclasses derives class, , other class isn’t software own. (this c#, multiple inheritance isn't option.) subclass, derives 3rd party class, has no implementation. derives 3rd party class, , implements isomebehavior, 3rd party class can treated same way other subclasses implement isomebehavior. what i've done, moment, implement extension method on isomebehavior. consuming code can call method. problem approach want force calling code use extension method. can't remove somemethod() interface, because extension method has call it. any ideas on how let 2 classes elegantly share same behavior, when 1 of them derives another, third party, class? note: strategy design pattern sounds makes sense here, pattern used when behavior varies among subclasses. behavior here doesn't vary; needs shared. is there reason can't...

objective c - How should I specify the path for an sqlite db in an iPhone project? -

after adding resource, database file in project root. i've been able open specifying full path os x sees it, i.e., "/users/louis/documents/test project/test.db". but of course there no such path on iphone. i think should define path "application root/test.db" don't know how, or if work anywhere else besides development machine. thanks ideas. to path of file you've added in xcode use pathforresource:oftype: mainbundle. nsstring *path = [[nsbundle mainbundle] pathforresource:@"yourdb" oftype:@"sqlite"]; but can't change files in mainbundle. have copy location. example library of app. you this: nsstring *librarypath = [nssearchpathfordirectoriesindomains(nslibrarydirectory, nsuserdomainmask, yes) lastobject]; nsstring *targetpath = [librarypath stringbyappendingpathcomponent:@"yourdb.sqlite"]; if (![[nsfilemanager defaultmanager] fileexistsatpath:targetpath]) { // database doesn't exist...

.net - How to display a table inside a table cell using Rdlc report -

is there way display table inside table cell using rdlc report? if please guide me new rdlc reports. regards b dharmaraju depending of issue, can try 2 ways of doing : the easiest way use subreports. check msdn here : http://msdn.microsoft.com/en-us/library/ms160348.aspx another way maybe harder generate dynamically report (rdlc file). don't forget it's xml file. can make 1 want business intelligence studio , generate own tool.

silverlight - MEF: One region, multiple views to display at the same time -

i'm trying build modular application contains shell application , subsequent modules. i'd define navigation area modules display hyperlink button. i've called region 'navigationregion' in shell's view: <itemscontrol name="navigationregion" prism:regionmanager.regionname="navigationregion" /> inside each module's initialize method, i'm calling navigation region's add method: public void initialize() { regionmanager.regions["navigationregion"].add(new views.navigation()); } the modules loaded in bootstrapper using aggregatecatalog.catalogs.add method: this.aggregatecatalog.catalogs.add(new assemblycatalog(typeof(orders.ordermodule).assembly)); this.aggregatecatalog.catalogs.add(new assemblycatalog(typeof(people.peoplemodule).assembly)); the problem is, 1 of views shows , first assembly added catalog's view. how views added navigation region show up? or there other method should using show ...

android - How to get ascender/descender and x height for a given font -

i need ascender / descender , x-height .. by using following code can find descender , total height: descender_height = paint.descent(); total_height = descender_height - paint.ascent(); //ascender = ?; equal descender height? //x_height = ?; total_height - 2*descender_height ? thanks i think ascender , descender height typically same, wouldn't depend on every font. don't see direct way x-height, trick use below. also, total height, talking absolute distance highest ascender lowest descender? i've included below. haven't tested these myself, should work (but let me know if i'm misinterpreting you've said): // assuming textpaint/paint tp; rect bounds; // retrieve bounding rect 'x' tp.gettextbounds("x", 0, 1, bounds); int xheight = bounds.height(); paint.fontmetrics metrics = tp.getfontmetrics(); int totalheight = metrics.top - metrics.bottom;

javascript a function to replace some words on my webpage -

i need javascript replaces words on web page other words. when page loads, words specify replaced else for example, if "hello" found replace "hi" if "one" found replace "two" etc. how can that? <div id="mydiv"> hello there name tom there hello there </div> <button onclick="replacetext()">click me!</button> with js: function replacetext(){ var thediv = document.getelementbyid("mydiv"); var thetext = thediv .innerhtml; // replace words thetext = thetext.replace("word", "replace"); thetext = thetext.replace("one", "fish"); thetext = thetext.replace("tom", "drum"); thediv.innerhtml = thetext; } you can insert regular expression in first parameter of replace function if want avoid ruining tag markup (if reason replacing words 'div' or 'strong'). function work fine pla...

Seek for help about Android Programming -

i want know how control system resources , services bluetooth, sms, phone contacts etc. honestly, want know how or control sms usage based on user behavior, block incoming call or change auto vibrate mode without user noticed that. actually, want assignment context aware access control paper. choose android implementation afraid couldn't submit paper in time if study android beginning , myself. no offense want avoid errors. feel head becomes swollen whenever "force close error" show need urgent. as willytete said developer site best 1 you there can find application fundamentals download android sdk , start programing the first program tutorial can start hello world notepad tutorial give lot of ideas list of sample apps , there lot of codes getting samples , explain how use this. you information developer site needed, while move beginner expert

preprocessor - How to set ISPP defines based on default Inno Setup variables? -

i trying to: #define commonappdata {commonappdata} but yields: compiler error [ispp] expression expected opening brace ("{") found. how achieve inno setup preprocessor? {commonappdata} cannot expanded @ compile time, i.e. when pre-processor runs because known @ runtime: identifies common application data directory on machine compiled installer run . maybe if clarify how intend use define might able help. if example you're interested in not common app data directory on target machine 1 on developer machine, can use this: #define commonappdata getenv("commonappdata") if intend use define populating inno properties capable of expanding constant @ runtime should use this: #define commonappdata "{commonappdata}" hope helps.

How can I get virtualenv to produce Python executables with the correct sys.path using the Enthought Python Distribution? -

i installed enthought python distribution version 7.0 on mac, easy_installed pip, did pip install virtualenv. when try create virtual environment, get: > virtualenv test new python executable in test/bin/python error: executable test/bin/python not functioning error: thinks sys.prefix '/library/frameworks/epd64.framework/versions/7.0' (should '/users/anand/test') error: virtualenv not compatible system or executable` and test/bin not contain activate script. how can virtualenv working? thanks help! this question discussed on epd developers mailing list. among others mentioned epd not put virtualenv in mind , has it's bugs sometimes. however, posted link summarized solution i'm trying out myself now: https://gist.github.com/845545 hth, michael

cocos2d convertToWorldSpace -

i'm not sure converttoworldspace works. i have spritea parent. i set position 40,40 example , add scene. i have second spriteb set @ position 80,80. i add spriteb spritea. i print out position of spriteb: 80,80. i print [self converttoworldspace:spriteb.position]. and, still 80,80. shouldn't spriteb position different here? in case if want know position of spriteb in current world must call "converttoworldspace" methods parent (the spritea) : [spritea converttoworldspace:spriteb.position]; the "converttoworldspace:" method applies node's transformation given position. should call methods parent's sprite.

End of file reading in c -

my program reading last line of data infile twice. when execute program, last line of data being printed twice. please me! here code, while ( !feof ( in ) ) { //fread(); } i hope happens because of feof functionality. i don't want use fgets or getline . there other way? please direct me. thanks responded me! got solution this! did fgetc , unfgetc in side do loop. here code: int ch; ch=fgetc(fp); { ungetc(ch,fp); //fread(); ch=fgetc(fp); } while( (ch = fgetc(fp)) != eof && ch != '\n' ); this post talks problem facing.

java - How to find which Class is causing OutOfMemory for the JVM? -

oflate our weblogic server crashing outofmemory error. there way can monitor jvm find out classes are hogging memory , have maximum number of objects? yes. way did configure jvm create heap dump on oom, pulled heap down , ran thru jvisualvm. can compute retained sizes (took long time) clear offender is. you can attach jvisualvm running instance, need configure jvm accept connection. way can watch heap grow in real time. see this; jboss should similar: https://wiki.projectbamboo.org/display/btech/visualvm+profiler i think easier answer after have heap dump though, when watch in real time things garbage collected , whatnot. edit -- here startup configs. -xx:+printgcdetails -xx:+printgctimestamps -xloggc:/path/to/memlogs/memlog.txt -xx:+printtenuringdistribution -xms1024m -xmx2048m -xx:maxpermsize=128m -server -dcom.sun.management.jmxremote -dcom.sun.management.jmxremote.port=xxxx -dcom.sun.management.jmxremote.ssl=false -dcom.sun.management.jmxremote.au...

Python - Remove a row from numpy array? -

hi wan't should simple here..i want remove row numpy array in loop like: for in range(len(self.finalweight)): if self.finalweight[i] >= self.cutoffoutliers: "remove line[i self.wdata" i'm trying remove outliers dataset. full code os method like: def calculate_outliers(self): def calcweight(value): pfinal = abs(value - self.pmed)/ self.pdev_abs_med gradfinal = abs(gradient(value) - self.gradmed) / self.graddev_abs_med return pfinal * gradfinal self.pmed = median(self.wdata[:,self.ycolum-1]) self.pdev_abs_med = median(abs(self.wdata[:,self.ycolum-1] - self.pmed)) self.gradmed = median(gradient(self.wdata[:,self.ycolum-1])) self.graddev_abs_med = median(abs(gradient(self.wdata[:,self.ycolum-1]) - self.gradmed)) self.workingdata= self.wdata[calcweight(self.wdata)<self.cutoffoutliers] self.xdata = self.workingdata[:,self.xcolum-1] self.ydata = self.workingdata[:,self.ycolum-1]...

asp.net mvc 2 - When to cache the results from a web service? -

in section web application information http://www.geonames.org/ ( web service method ) , http://data.un.org/ ( xml files stored on our application ) i'm new @ , questions are: when cache information geonames ? what method use cache ? it ok if cache xml files or same performance ? i use asp.net mvc 2 c# caching way improve performance, consider it, if current performance not acceptable, otherwise there no need worry. one way cache data set database table clob field, date time of when stored , of course fields identify object (such webservice parameters used obtain object). you've decide policy expire old objects, instance set query run daily delete objects older week. example, can't tell how long cache, depends on size of data can keep , on how gets updated. to questions in more detail: .1. when cache information geonames ? i'm not sure if understand correctly, normally: you'd value in cache, if it's found return cache, if it...

graphics - What would be a good library to draw to the screen in c++? -

i creating simulation models how gas behaves in container. have collision checking set up, draw data on screen make sure working correctly all need simple way draw simple shapes such circles screen using c++. these shapes not have great, function. may want move simulation 2d 3d in future - library has 3d capabilities good. remember looping through , drawing several hundred gas molecules, fast good. i new c++ language go easy. ide/compiler vs 2010 professional. i have used google - can not find installation guide installing library. installation guide big plus look @ sdl sdl_gfx . can switch sdl/opengl 3d.

security - Tricky question for good understanding of CSRF -

my friend , have pari beer. from wikipedia: requiring secret, user-specific token in form submissions , side-effect urls prevents csrf; attacker's site cannot put right token in submissions the atacker can use browser cookies indirectly, can't use them directly! that's why can't put cookies link using document.write() let how logout link generated. secure way? can request faked? function logout(){ echo '<a href="?action=logout&sid='.htmlspecialchars($_cookie['sid']).'>logout</a>'; } sid session id, generated every session on server side, following checking performed: $_get['sid']==$_cookie['sid'] absolutely not ! never use session identifiers csrf protection. as far why? well, answer simple. doing opens door session hijacking attacks. imagine copies , pastes link reason email or onto web. now, person on other end of email has session identifier of session....

ruby on rails - Missing Rspec Core -

here message have been getting when running rspec: /home/patrick/.rvm/gems/ruby-1.9.2-p136@rails3tutorial/gems/rspec-core-2.5.1/lib/rspec/core/configuration.rb:386:in load: no such file load -- /spec (loaderror) my .gemfile looks this: source 'http://rubygems.org' gem 'rails', '3.0.3' gem 'sqlite3-ruby', '1.3.2', :require => 'sqlite3' gem 'gravatar_image_tag', '1.0.0.pre2' gem 'will_paginate', '3.0.pre2' group :development gem 'rspec-rails', '2.3.0' gem 'annotate-models', '1.0.4' gem 'faker', '0.3.1' end group :test gem 'rspec', '2.3.0' gem 'rspec-rails', '2.3.0' gem 'webrat', '0.7.1' gem 'spork', '0.8.4' gem 'factory_girl_rails', '1.0' end as can see appears trying load rpsec 2.5.1, have specified version 2.3.0. i w...