Posts

Showing posts from January, 2014

iphone - Is there any tool that converts Objective C code to java for Android -

possible duplicate: objective-c java cross compiler i have working iphone app , want convert android app minimal effort. can suggest ? i don't think so. you're best bet have been develop application scratch using platform appcelerator or phone gap . the commenter makes excellent point: platforms fundamentally different. straight conversion of code won't work. have convert framework/api calls , restructure of ui. not framework different, assumptions made platform totally different well. possibly best way reuse code (this isn't easiest, keep in mind) convert objective c code c or c++ , make use of android ndk. won't able reuse of ui code, might able reuse significant amount of application logic depending on application does.

recursion - SML currying question -

i have midterm coming next week , going on sml notes provided in class. came across currying example , not sure how worked. it simple function computes power of number. here function definition: fun pow 0 n = 1 | pow k n = n*pow(k-1)n i'm not sure how function works when pass following arguments: val x = pow 2 2 this way see it: =2*pow(1)2 =2*(2*pow(0)2)2 =2*(2*(1)2)2) the result should getting 4 don't see how result steps have carried out above. help please. thank-you. ah, standard ml of new jersey, how miss thee... anyway, let me go through step step. remember currying, unlike dinner in front of me (which incidentally curry dish), way of dealing 1 argument @ time return new function. in mind, apply first 2 given function. since 1 pattern matches, have new function -- let's call "curry": curry n = n * pow 1 n note have "inner" version of pow function address. doing so, again, 1 pattern matches. let's call inn

encoding - Is there a PHP function to fix this? -

"â€Å“excuse me, hope isn’t weird or anything," how can fix encoding on this? what you're running result of data being written in 1 encoding, , interpreted being another. need make sure you're requesting input in same format you're expecting in. recommend sticking utf-8 whole way through unless need avoid multibyte characters, in case might want @ forcing ascii. make sure you're telling php use utf-8 internally: ini_set('default_charset', 'utf-8'); and make sure telling browser expect utf-8 encoded text, both in headers… header("content-type:text/html; charset=utf-8"); …and in meta tags (html5 below)… <meta charset="utf-8"> setting tell browser sent utf-8 encoded content when form submitted, , it'll interpret results send utf-8 well. you should make sure both database storage , connection encoding in utf-8 well. long dumb data store (i.e. won't manipulating or interpreting data in

How to get calendar event updates on Android device? -

i want calendar event updates (when new event added or existing event deleted ) on android 2.2 devices ? in other words, program wants notifications calendar event changes anyone has thoughts regarding how this? whenever calendar update made,u can notification using content observer,u have register first observer using this.getcontentresolver().registercontentobserver(uri, true, observer); where uri the calendar uri "content://com.android.calendar/events" , observer object of class extending content observer overrides on change method,invoked when change occurs you have notify observer using this.getcontentresolver().notifychange(eventsuri, null) wherever u r performing changes in read or delete operation of calendar

javascript - Remove text from a p tag and add a class with jquery -

what i'm triying accomplish there's p tag word "border" on it remove text inside (the word border) , add class p. far works finding p , adding class. how can remove text? $('#main-body-content').find('p').filter(':contains(border)').addclass("border"); try this...... $('#main-body-content').find('p').filter(':contains(border)').text("").addclass("border"); demo

javascript - Why do Chrome & Firefox slowly render my home page using MathJax? -

this experimental site using mathjax . browse using chrome, firefox, , ie. notice ie renders slowly. chrome , firefox more slowly. :-) is there secret tip speed rendering? edit 1 i still uploading mathjax using filezilla remote server. needs time complete. even use development machine server mathjax libraries installed, result same did above in remote server. your site returning 404 requests these files: http://www.begolu.com/mathjax/fonts/html-css/tex/otf/mathjax_size4-regular.otf http://www.begolu.com/mathjax/fonts/html-css/tex/otf/mathjax_main-regular.otf- http://www.begolu.com/mathjax/fonts/html-css/tex/otf/mathjax_math-italic.otf http://www.begolu.com/mathjax/fonts/html-css/tex/otf/mathjax_size1-regular.otf http://www.begolu.com/mathjax/fonts/html-css/tex/otf/mathjax_main-bold.otf look @ net tab firebug

how to load .so file that are not in System/lib folder in android? -

i have file named libjsa.so in memory card in android , wanna load in application. how can load file using system.loadlibrary("libname"); ? things have tried:- try copy /system/lib . ---- not worked system.loadlibrary("/mnt/sdcard/folder/libjsa.so"); -------- not worked afaik, unless it's system library or on rooted device, can't load libraries outside signed apk bundle, meaning want can't done.

Android ListView and Keyboard -

i have created custom listview custom rows. work fine when using touchscreen; however, when attempt click on items in row keyboard d-pad nothing happens. mean onclicklistener not called. know of references or tutorials on how add keyboard support new custom rows in listview? use setonitemclicklistener instead of setonclicklistener edit use attribute on list item android:focusable="false"

php logical operator comparison evaluation -

here i'm trying achieve: if $x either of these 3 values: 100, 200 or 300 - something i'm doing this: if($x==("100"||"200"||"300")) { //do } but //do something executed if $x 400 i noticed works: if($x=="100"||$x=="200"||$x=="300") { //do } how first block of code different second block of code? doing wrong? the reason why code isn't working because result of expression: ('100' || '200' || '300') is true because expression contains @ least 1 truthy value. so, rhs of expression true , while lhs truthy value, therefore entire expression evaluates true . the reason why happening because of == operator , loose comparison. if used === , resulting expression false . (unless of course value of $x false-y.) let's analyze this: assuming $x equal '400' : ($x == ('100'||'200'||'300')) // ^

What does 'dataString' for the field 'data' in jQuery's .ajax API? -

for reason it's not listed in jquery website it's explaining .ajax api , want figure out 'datastring' defining because it's being used in ajax script i'm practicing with. if sending 'data' webservice or page that's data field for. example if want insert new user database via ajax page you're talking needs know information. for example: $.ajax({ url: "/ajax.asmx/addto_cart", data: "{qty:" + qty + ",id:" + id + "}", success: function (msg) { var response = msg.d; $("#ctl00_shoppingcartmenu1_cartsum").html(response); } }); and page being called: public string addto_cart(int qty, int id) { string dostuff ="lots of stuff done."; return dostuff; } this .net should idea.

Missing inlines in Django Admin -

see below models.py/admin.py when try change or add fashionmalemodel, inlines don't appear, in fashionfemalemodel. if change order in admin sites registered, putting male below female, inlines show in fashionmalemodel, , not fashionfemalemodel. why inlines showing in 1 or other? thanks! i've truncated these models because there's lot. also, fashionobject/fashionpage base classes i've created part of custom cms id, name, publish_date, etc. models.py: class fashionmodelrole(models.model): title = models.charfield(max_length=255,) class fashionmodelcontributor(models.model): role = models.foreignkey(fashionmodelrole) person = models.foreignkey(fashionmodelperson, related_name='contributions') class fashionmodel(fashionobject): gender = models.charfield(max_length=1,choices=(('f','female'),('m','male')), editable=false) class fashionexperience(models.model): model = models.foreignkey(fashionmo

c# - What is the difference between Index Out of Range Exception and Index Outside the Bounds of Array Exception? -

is there difference between "index out of range exception" , "index outside bounds of array exception"? they're same thing. indexoutofrangeexception name of exception class thrown. description given visual studio "index outside bounds of array." this exception thrown when attempt made access element of array index outside of bounds of array. note indexoutofboundsexception class not part of c# @ all, rather java language (or microsoft's implementation, j#).

jquery - validate dynamically created elements on select an option of combobox -

i using jquery validate() plugin . hava combobox in form when user select option on new element create dynamically . how validate new element according selected option of combobox . in fact want first check value of combobox it's new elements created . have solution ??? if create new element when user select option can validation right after that? (but shouldn't validate first , create new element?) http://jsfiddle.net/ggb6c/ <div id="test"> <select id="combobox1"> <option value="1">value 1</option> <option value="2">value 2</option> <option value="3">value 3</option> <option value="4">value 4</option> </select> </div> $("#combobox1").change(function() { var text = $('<input type="text"></input>'); $('#test').append(text); text

php - PHPExcel in CakePHP: error--excel file incompatible or corrupted -

i'm using cake; open excel file in browser function generate: i'm getting error microsoft excel: excel cannot open file 'groups list .xlsx' because file format or file extension not valid. verify file has not been corrupted , file extension matches format of file. i've tried removing spaces in filename after downloading browser , opened again, shows same error above. experienced , solved it? or clue what's going on? basically excel file opened empty due error above. i've read similar problem says removing space @ end of ?> tag in 1 of component files. don't know component file..? p.s. i'm using microsoft excel 2010, reason? phpexcel work a--"microsoft excel 2010" ? the phpexcel excel2007 writer should generate valid xlsx files can read excel 2007, excel 2010 , excel 2003 compatibility pack. of testing excel2010 , excel2003. first thing check if there spurious characters being echoed file opening

ide - Not able to handle iframe and new window activity -

i not able handle iframe popups. in application when click on buttons or link open iframe pop up. activity on iframe popup not recorded in selenium ide. select window command not work. when click on link open in second window same title. not able handle new window's activity. please provide me solution if have. you need use command select frame , not select window.

ruby on rails - What would be a good way to separate different types of user account? -

supposing various type of users, 'normal', 'medium' , 'premium' each 1 different permissions. a kind of permission on permission. for example: only registered users can post a normal user can post 1 post per month a medium user can post 5 posts per month a premium user can post unlimited posts per month and other attributes. what suggest? i suggest @ can can .

Java Variable type and instantiation -

this has been bugging me while , have yet find acceptable answer. assuming class either subclass or implements interface why use parent class or interface type i.e. list list = new arraylist(); vehicle car = new car(); in terms of arraylist gives me access list methods. if have method takes list parameter can pass either list or arraylist arraylist list. within method can use list methods can't see reason declare it's type list. far can see restricts me methods i'm allow use elsewhere in code. a scenario list list = new arraylist() better arraylist list = new arraylist() appreciated. using interface or parent type recommended if need functionality of parent type . idea explicitly document don't care implementation, making easier swap out concrete class different 1 later. a example java collection classes: if use list , set etc. instead of e.g. arraylist , can later switch arraylist linkedlist if find gives e.g. better performance. that, chan

postgresql - saving pdf in postgres -

is possible save pdf in postgres database? if so, how? you can use datatype bytea store pdf. option large object , that's not easiest thing use.

php - SEO friendly alternative for an iframe? -

i have content share other websites. currently via iframe: <iframe width=“540”; height=“700” frameborder=“0” src=“http://www.energiekostencalculator.nl/forms/frame_tabs.php?first=yes&product=1&links=1&css=http://www.energiekostencalculator.nl/forms/susteen.css”></iframe> this has 2 problems. it not seo friendly. links on content of iframes not count inbound links since page hosted on server. it (on server anyway) not possible link outside css stylesheets content of iframe. objective allow other websites link stylesheet content. who has solution these issues? perhaps using jquery (see below), i'm not sure google parse , "see" links... <html> <head> <script src="/js/jquery.js" type="text/javascript"> </head> <body> <div id='include-from-outside'></div> <script type='text/javascript'> $('#include-from-outside').load('http://example.com/

scala - Why do some collection classes have an "empty" instance method additionally to the class method? -

both exist example here: map.empty[int, int] map(1 -> 41).empty set().empty set.empty but here class methods existing: list.empty //ok list(1,2,3).empty //doesn't exist array.empty //ok array("a").empty //doesn't exist isn't empty perfect case class method (and shouldn't instance method empty deprecated therefore)? or should empty instance method added classes missing it? is there language point of view makes difficult having empty class method (e. g. type inference, higher-kinded types, ...). ps: suggested maps default values harder achieve without instance method empty : map[int, int](1->2, 21->42).withdefault(_*2).empty what think? that's true, empty method on class instance. reason why it's required sets , maps because implement builders using method. guess reason why wasn't included elsewhere because wasn't typical use case.

javascript - Google Map in User control not working for multtiple instances -

i have created user control contains google map . code in user control follows <script type="text/javascript" language="javascript"> var map; function intialize(){ map = new google.maps.map(document.getelementbyid("map_canvas"), mapoptions); //set default center map.setcenter(mylatlng); //set default zoom map.setzoom(initialzoom); //set map type map.setmaptypeid(google.maps.maptypeid.satellite); } </script> html code: <div id="map_canvas" style="float: left; width: 100%; height: 300px; border: solid 1px black;" > </div> call initialize() function code behind(.ascx.cs) using me.page.clientscript.registerstartupscript(me.gettype(), "functioncall", "initialize();") everythings works fine when single instance user control used in parent page (.aspx page). when tried used user control multiple times in page ,only map 1st instance showing

math - Estimate the rate of height growth of humans in km/ hr? -

someone asked me question during interview. how go this? not random bs question has math behind it. profile analytic position wanted math skills. couldn't figure out way of calculating this. here data collected after interview might helpful: height growth depends on genetic factors, diet, standard of life etc. human grow rate fastest @ birth rapidly declining between 0 & 2, tapering declining rate & rapid rise @ puberty 13 gives second maxima followed steady decline 0 @ age 18. you may use data or make own assumptions answer question. how go answering based on title of question, knowing need demonstrate strong math skills? the units red herring: km/hr misleading when we're talking that's more meaningful , intuitive @ cm/year. with said, you've cited maximum rates between 0 , 2 years old , "puberty". have agree on you're looking for: maximum value or overall value? since interview question, have state assumptions , give re

dynamic data - go to link on button click - jquery -

i have script below $('.button1').click(function() { document.location.href=$(this).attr('id'); }); the button1 has variable unique ids. on click, page must redirect url " www.example.com/index.php?id=buttonid " page redirecting " button id ". i want add string " www.example.com/index.php?id= " before current url. how can make possible? $('.button1').click(function() { window.location = "www.example.com/index.php?id=" + this.id; }); first of using window.location better according specification document.location value read-only , might cause headaches in older/different browsers. check notes @ mdc dom document.location page and second - using attr jquery method id bad practice - should use direct native dom accessor this.id value assigned this normal dom element.

php - File & file_get_contents bugging on reading simple file -

file or file_get_contents not read sample file properly <?php ?> this test program $flines=file('../include/test.php'); echo '<pre>'; print_r($flines); echo '</pre>'; for($i=0;$i<count($flines);$i++) { echo("$i:".$flines[$i]."\n<br>"); } echo "file contents"; echo(file_get_contents('../include/test.php')); this output array ( [0] => ?> ) 0:1:?> file contents basically skips php declaration reason... , file empty addition every works fine when removing opening < of course you didn't trick php, php right along; tricked yourself.... $flines=file('./x.php'); echo '<pre>'; print_r(array_map('htmlentities',$flines)); echo '</pre>'; for($i=0;$i<count($flines);$i++) { echo("$i:".htmlentities($flines[$i])."\n<br>"); } echo "file contents"; echo(

balance - How much Silverlight should I use for web development? -

i learned silverlight technology , want use developing quite large web application. question this: should use silverlight base of application , application development in silverlight, or should use silverlight it's necessary? unless absolutely need use silverlight , cannot html, not use silverlight. useful features (video etc) remember many people (such myself) not have silverlight installed , if visit site says "you must install silverlight" our response "you must crazy". every 1 of user or customer lost. i have visited 1 or 2 sites (mostly microsoft) because wanted information, or interested in something. developer decided not allowed have information unless installed silverlight. went elsewhere find information. so of site in html can, , if have use silverlight, offer html alternative.

android - set url image to image view -

possible duplicate: is possible use bitmapfactory.decodefile method decode image http location? i have problem in set url image image view. tried below methods method 1: bitmap bimage= getbitmapfromurl(bannerpath); image.setimagebitmap(bimage); public static bitmap getbitmapfromurl(string src) { try { log.e("src",src); url url = new url(src); httpurlconnection connection = (httpurlconnection) url.openconnection(); connection.setdoinput(true); connection.connect(); inputstream input = connection.getinputstream(); bitmap mybitmap = bitmapfactory.decodestream(input); log.e("bitmap","returned"); return mybitmap; } catch (ioexception e) { e.printstacktrace(); log.e("exception",e.getmessage()); return null; } } method 2: drawable drawable = loadimagefr

How to clone a Python generator object? -

consider scenario: #!/usr/bin/env python # -*- coding: utf-8 -*- import os walk = os.walk('/home') root, dirs, files in walk: pathname in dirs+files: print os.path.join(root, pathname) root, dirs, files in walk: pathname in dirs+files: print os.path.join(root, pathname) i know example kinda redundant, should consider need use same walk data more once. i've benchmark scenario , use of same walk data mandatory helpful results. i've tried walk2 = walk clone , use in second iteration, didn't worked. question is... how can copy it? ever possible? thank in advance. you can use itertools.tee() : walk, walk2 = itertools.tee(walk) note might "need significant storage", documentation points out.

asp.net - hyperlink.NavigateUrl getting changed on master page (possibly by ResolveUrl() ) -

i have hyperlink in cases want change show jquery popup, i'm having strange problem when doing on master page. following works in regular page: hyp1.navigateurl = "#notificationpopup"; which renders as: <a id="ctl00_hyp1" href="#notificationpopup">example</a> this want. problem exact same code on hyperlink on master page renders as: <a id="ctl00_hyp1" href="../masterpages/#notificationpopup">example</a> it looks might running navigateurl through resolveclienturl() or when i'm setting on master page. i've tried swapping <asp:hyperlink <a href runat=server , same thing happens. any ideas? there note on msdn control.resolveclienturl method description. the url returned method relative folder containing source file in control instantiated. controls inherit property, such usercontrol , masterpage, return qualified url relative control. so behavior of m

sql - Change sizing defaults for data types in SSIS -

i have ssis package approximately fifty data flows in interacts oracle database. we changed data types in oracle database 55 tables / 300+ columns float number (30, 15) i working on changing data types in ssis package. every time change column float number in data conversion component, defaults number (10, 0) . is there way me change default comes number (30, 15) ? i don't think possible, can save little bit of pain using text expander / replacer program breevy: http://www.16software.com/breevy/

performance - monitor Java proccess memory in realtime -

i have java application memory starting jump , fall after few days. there tool can show me variables/members sizes during run/debug in real time? debugging eclipce impossible. thanks install this: http://visualvm.java.net/eclipse-launcher.html , launch using eclipse. not use debugger, launches visualvm application lets monitor app. you'll need go run configurations.. settings set up, , select visualvm launcher @ bottom (select other... -> visualvm launcher). you'll need go preferences set location of visualvm too. (on later eclipse versions, drop drops folder, unpacked).

c# - Why am I getting a Specified Cast is not valid error? -

i've developed application asp.net mvc 2, , after deploying it, invalidcastexception : error/exception: "specified cast not valid." stacktrace: [invalidcastexception: specified cast not valid.] system.data.sqlclient.sqlbuffer.get_time() +77 system.data.sqlclient.sqldatareader.gettimespan(int32 i) +56 read_question(objectmaterializer`1 ) +1740 system.data.linq.sqlclient.objectreader`2.movenext() +29 system.collections.generic.list`1..ctor(ienumerable`1 collection) +7667556 system.linq.enumerable.tolist(ienumerable`1 source) +61 testenvironment.managements.questionmanager.getquestionsbytestid(int32 testid) in d:\parallelminds\projects\testapplication\testenvironment\testenvironment\managements\questionmanager.cs:131 testenvironment.controllers.loadtestcontroller.index(nullable`1 testid) in d:\parallelminds\projects\testapplication\testenvironment\testenvironment\controllers\loadtestcontroller.cs:31 lambda_method(executionscope , controll

Login control's login button enabled/disabled property in asp.net -

just wondered how enable/disable "log in" button on login control based on if user name , password textboxes null or not ? thanks.. hi jack first convert login control template , add following jquery code in header section of page $(document).ready(function () { $('input[type="submit"]').attr('disabled', 'disabled'); $('input[type="text"]').keypress(function () { if ($(this).val != '') { $('input[type="submit"]').removeattr('disabled'); } }); });

c# - class properties -

i've began using classes , make functions of class visible outside class. problem haven't got (and unable have) variable of type abc. let me explain snippet of code: class abc { private float foo; public float foo { { return foo; } set { foo = value; } } public static void hello() { foo = 5.0f; console.writeline("hello everyone!"); } } .... somewhere else .... abc bar; bar.foo = 5.0f; // ok, know bar.hello(); // fine, know abc.hello(); // i'm trying this! edit: ok, suppose assign foo in hello (as in code). know might sound nonsense, i'm not sure it's possible. you need static member function. static member functions not associated particular instance of class, need if want access them via class itself . specifics vary depending on whether you're interested in c++ or c#.

java - How to use enums? -

i'm not sure how use enum in java. using right in following example? enum sex {m, f}; public class person{ private person mom; private sex sex; public person(sex sex){ this.sex = sex; //is how i'd set sex? } public void setmom(person mom){ if(mom.sex == 'm'){} //is how check see if sex of passed person argument male? } } this want use: if(mom.sex == sex.m) however, spell out enum constants male , female.

validation - Validating properties in c# -

let's suggest got interface , inherit class it, internal interface ipersoninfo { string firstname { get; set; } string lastname { get; set; } } internal interface irecruitmentinfo { datetime recruitmentdate { get; set; } } public abstract class collaborator : ipersoninfo, irecruitmentinfo { public datetime recruitmentdate { get; set; } public string firstname { get; set; } public string lastname { get; set; } public abstract decimal salary { get; } } then how validate strings in collaborator class? possible implement inside properties? or use dataannotations http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute.aspx

javascript - Replace two double quotes with single one using jquery -

how replace 2 double quotes single 1 using jquery? for example: need replace sam @ ""home"" to sam @ "home" looking similar regex (which replaces double quotes single quotes): mystring.replace(/"/g, "'") try this: mystring = mystring.replace(/""/g, '"'); the regex captures 2 double quotes , replaces them one. we're using regex replace more single match (javascript's replace replace first one). note second argument replace string. represent " in string need escape it: "\"" , or use single quote string: '"' . javascript supports both.

c# - .Net Regex for mm-dd-yy and others + yyymmdd -

i feel chasing tail. i trying arrive @ .net regex match on following: mm-dd-yy m-dd-yy mm-d-yy m-d-yy and (no dashes) yyyymmdd one or 2 digits followed dash, followed 1 or 2 digits, followed dash, follows digits or 8 digits: (\d{1,2}-\d{1,2}-\d{2})|(\d{8})

Does merge direction matter in Mercurial? -

take simple example: i'm working on default branch, have changesets committed locally, , pulled few more master repository. i've been working few days in isolated local repository, there's quite few changes merge before can push results master. default ---o-o-o-o-o-o-o-o-o-o-o (pulled stuff) \ o----o------------o (my stuff) i can 2 things now. option #1: hg pull hg merge result #1: default ---o-o-o-o-o-o-o-o-o-o-o \ \ o----o------------o-o option #2: hg pull hg update hg merge result #2: default ---o-o-o-o-o-o-o-o-o-o-o-o \ / o----o------------o these 2 results isomorphic me, in practice seems option #2 results in way smaller changesets (because applies few changes mainline instead of applying mainline changes few). my question is: matter? should care direction of merges? saving space if this? (doing hg log --patch --rev tip after mer

c - With the Apache API, why feeding strings is done line by line ? Any reason? -

i've starting playing apache, , wanted know. if base myself on tutorial/examples i've found, e.g. mod_example.c or mod_hello.c http seems sent line line: ap_rputs("<html><head><title>greetings</title></head></body>\n",r); ap_rputs("<h1>greetings, earthling</h1>\n",r); is readability issue, or there real reasons ? it's readability in many cases. you send entire response (html, etc.) ap_rputs() if wanted to.

In what instance would git cherry-pick be needed instead of git merge? -

for moving individual 1 branch realize there few options in git. have experimented git merge , git cherry-pick failing see when git cherry-pick preferable. my understanding following: git merge <hash> moves specified commit 1 branch other preserving 1 commit. git cherry-pick <hash> creates copy of commit in second branch separate own commit hash. the first option seems preferable me instances when cherry-pick preferred? say have branch master has bunch of commits. maybe made change appropriate on master , don't want bring in all of changes (a small bug fix, example, or addition of small feature). git cherry-pick , can grab only commit other branch , bring master .

mysql db table query -

i have 2 tables: users{user_id, username, picture} likes{id, user_id, image_id} the query im trying is: select username, picture user , likes user_id=user_id , image_id=4 but dnt know how connect them, thanks the key use inner join between 2 tables. select u.username, u.picture user u inner join likes l on u.user_id = l.user_id l.image_id = 4

c# - generic field getter for a DataRow -

i try extend datarow object generic method : public static t? get<t>(this datarow row, string field) t : struct { if (row.isnull(field)) return default(t); else return (t)row[field]; } it's work fine when t int , decimal , double , etc. but when try use string, have error : "the type 'string' must non-nullable value type in order use parameter 't' in generic type or method 'system.nullable'" how can correct ? i know string not struct wan't return null if string field dbnull. i think want: public static t? getvalue<t>(this datarow row, string field) t : struct { if (row.isnull(field)) return new t?(); else return (t?)row[field]; } public static t getreference<t>(this datarow row, string field) t : class { if (row.isnull(field)) return default(t); else return (t)row[field]; }

javascript - How to use iphone websocket to send data to server -

hello please tell me how use iphone websocket send data server in webapp. i have completed webapp. when compile using phone gap cross domain ajax not working good. want use iphone websocket send data server please tell me iphone websocket how can use these send data server i've used socket-io before, pretty simple , should job.

ios - Is it possible to inherit from MKPolyline -

i'm building mapkit based app iphone. i have number of mkpolylines added map. however, instead of having mkpolyline, have own model class conforming mkoverlay protocol added map can access model properties when creating corresponding view in mapview:viewforoverlay. the problem can't find way inherit mkpolyline because doesn't have init methods can call subclass' init. can create them using convenience methods. how can bring model properties , mkpolyline behaviour? you can set associated object attribute of class. allows bind instance variable existing class. make sure clean after yourself.

Max limit of bytes in method update of Hashlib Python module -

i trying compute md5 hash of file function hashlib.md5() hashlib module. so writed piece of code: buffer = 128 f = open("c:\\file.tct", "rb") m = hashlib.md5() while true: p = f.read(buffer) if len(p) != 0: m.update(p) else: break print m.hexdigest() f.close() i noted function update faster if increase buffer variable value 64, 128, 256 , on. there upper limit cannot exceed? suppose might ram memory problem don't know. big (≈ 2**40 ) chunk sizes lead memoryerror i.e., there no limit other available ram. on other hand bufsize limited 2**31-1 on machine: import hashlib functools import partial def md5(filename, chunksize=2**15, bufsize=-1): m = hashlib.md5() open(filename, 'rb', bufsize) f: chunk in iter(partial(f.read, chunksize), b''): m.update(chunk) return m big chunksize can slow small one. measure it. i find ≈ 10 mb files 2**15 chunksize fastest files i&#

java - is it worth to learn google data store -

i want use google app hosting , have read don't give option of mysql or sql. now building java website using mysql. is data store same sql. , work hibernate should learn or not the datastore not "drop in" replacement sql. have worked python version of gae bit, java version might different... you want limit number of queries run in page , number of objects query. doing otherwise lead looooong load times. inserting lots of data (200+ objects) wont work. you can't range scans on more 1 column in table (for instance 1 < x < 2 , 3 < y < 4). lot of query types not supported compared full fledged database engine. you should edit , insert data via program. datastore admin allows insert data after initial object created types (text,blob) not editable. any changes models require loop through instances , make changes (especially if delete attribute on model). can ignore chances want reclaim space used. backing data , uploading data app

php - Remove non-numeric characters (except periods and commas) from a string -

if have following values: $var1 = ar3,373.31 $var2 = 12.322,11t how can create new variable , set copy of data has non-numeric characters removed, exception of commas , periods? values above return following results: $var1_copy = 3,373.31 $var2_copy = 12.322,11 you use preg_replace swap out non numeric characters , comma , period/full stop follows: <?php $teststring = "12.322,11t"; echo preg_replace("/[^0-9,.]/", "", $teststring); ?>

bash - Creating a directory inside a virtualenv via virtualenvwrapper's postmkvirtualenv -

inside every virtualenv of mine, add directory named run , put running pid files , logs, etc. noticed postmkvirtualenv can me make sure happens when create new virtualenv im not sure how implement. mkdir $virtual_home/$virtualenv/run $virtualenv not available... know it's possible, not sure how. you want use $virtual_env variable instead. example postmkvirtalenv : #!/bin/bash mkdir "${virtual_env}"/run the variable quoted protect against spaces in path.

sql - Tagging database objects (string tags) and tag lookup -

multiple objects in our database need tagged string tags (completely arbitrary). 1 solution classic many-to-many relationship representation: table customer customerid, customername table product productid, productname table tags tagid, tagname table customertags customerid, tagid table producttags productid, tagid another solution have xml column represents tags path secondary xml index improve sequential lookup: table customer customerid, customername, tags table product productid, productname, tags where tags xml column have tags <tags><tag name="tag1" /></tags> , path index /tags/tag the first solution gives faster lookup, adds more tables. second solution slower cleaner. i'm new sql , might have overlooked something, input highly appreciated. my vote on first solution. first of all, xml slower process on sql server 2008 equivalent straight tbl-bridge-tag setup. if wanted find products tagge

java - What is the best way to convert relational to object oriented? -

since learned rdbms, started thinking in relational model , less in object oriented. i'm having trouble trying store , query data in java data structures. i want write application has entity sets relate each other made each entity own class. attributes each entity instance variables. okay think we're far. title , game entities. game isa title title should parent class , game should inherit title (think of game physical copy , title name of game). i have set of games in main class , can iterate through if want find specific game. how find specific title? don't have set of titles because title inherited assume should iterate through games , when find name of title, add set unique titles back. game mutable (isbought can change) using set bad idea? best way create entity sets in java? using map instead of set map id object? fixing object-relational gap not easy task. there orm (object-relational mapping) frameworks that. have learning curve. hibernate

What is the Ivy equivalent of Maven's versions:display-dependency-updates? -

i have ivy.xml file specify dependencies explicitly. there functionality built ivy let me discover or automatically update dependencies out of date? i don't want use latest.release because want stable , reproducible build. every once in while i'll want update dependencies , @ same time answer question, other dependencies out of date? like you, use dynamic versions in-house dependencies. when upgrading, @ start of new development phase, use 1 of repository search tools discover new versions of 3rd party libraries: http://mvnrepository.com/ http://mavencentral.sonatype.com/ as i'm sure you're aware, problem upgrading dependencies can lead involuntary upgrade of transitive dependencies.... what i'd suggest generate ivy dependency report , use review code's module usage. find useful considering 3rd party maven modules not behaved , import many unnecessary libraries onto classpath. the following example of standard dependencies target:

ruby - Replacing unicode linebreaks with BR -

in xml files, there unicode line breaks shown in screenshot. use link see screenshot bigger screenshot the 2 dots after "minds." line break. i've googled , tried know replace them ruby (1.8) without luck. here's code (with different tries of unicodes), maybe me. def formatedbody t = self.body.gsub("\u000a","<br/>") t = t.gsub("\u000d","<br/>") t = t.gsub("\u0009","<br/>") t = t.gsub("\u000c","<br/>") t = t.gsub("\u0085","<br/>") t = t.gsub("\u2028","<br/>") t = t.gsub("\u2029","<br/>") t = t.gsub(/0a\0a/u,"<br/>") return t end the 2 0x0a values hex representation of line-feeds. regular ol' ascii line feeds, aka "\n\n" in string. so, t = t.gsub(/\n/, "<br/>") should work. t = "foo\u000d\u0009\u0

Avoid CakePHP's Auth component to display authentication error messages -

i rid of auth component error messages, specially autherror message comes whenever try access non-allowed action. just sure, double check there no $this->session->flash() call anywhere in layout. besides, setting empty value not work, component has default message value. i using auth component following configuration in appcontroller class: class appcontroller extends controller { var $components = array( 'auth' => array( 'usermodel' => 'webuser', 'loginaction' => '/login', 'loginredirect' => '/', 'logoutredirect' => '/login', 'autoredirect' => false, ), 'session', ... ... } for login , logout redirections have setup 2 routes: router::connect('/', array('controller' => 'posts', 'action' => 'index')); router::conne

html - How can I write the contents of a variable into the text area of a <td>here</td> with javascript? -

how can write contents of variable text area of <td>here</td> javascript? prompt user using called function onclick , store type variable , write string saved variable same <td> form/input/prompt function call in. i'm thinking can done accessing column via class attribute. ideally, i'd function(s) independent , robust such can use them several different columns based on class attributes. <html> <head> <link href="style.css" rel="stylesheet" type="text/css"> <title>asdfsadf</title> </head> <body bgcolor="#000088"> <script type="text/javascript"> function editdates() { var dates = prompt("fill in date(s) of absence", "example: travel 1/7 - 2/10"); document.write. } </script> <table class="maintable" cellspacing="0" border="1" cellpadd

Where to place a recurring task in a Grails app? -

i'm learning grails, , include recurring task fires every 5 seconds while app running, , should have access domain objects , such. proper way accomplish in grails? i considered starting timer in bootstrap.groovy , disposed , kill timer. i've never used grails quartz plugin should let want.

jquery - page method not working -

i'm calling page method using jquery function that's this: function getnewdate(thedateitem) { thismonth = 3; theday = 1; theyear = 2011; datestring = themonth + '/' + theday + '/' + theyear; $.ajax({ type: "post", url: "/pages/callhistory.aspx/resetdate", contenttype: "application/json; charset=utf-8", data: datestring, datatype: "json", success: successfn, error: errorfn }) }; and then, in code behind file, have: [webmethod] public static void resetdate(datetime thenewdate) { var test = 4; } however, when put breakpoint on var test = 4, never stops there. what missing? thanks. you need check happening jquery call - suggest using firebug (or equivalent in browser of choice) trace javascript , see response/request. this allow see errors being returned web page/method. update: you should sendin

PHP + PDF Line Break -

i have below code in magento store adds customers address invoice pdf's. lines of address long address labels added $value = wordwrap($text, 10, " \n"); line thinking create new line. however, doesn't seem work in pdf docs , end funny symbol i'd line be. know how can new line? p.s - php knowledge basic. if (!$order->getisvirtual()) { if ($this->y < 250) { $page = $this->newpage(); } $this->_setfontregular($page, 6); $page->drawtext('ship to:', 75, 222 , 'utf-8'); $shippingaddress = $this->_formataddress($order->getshippingaddress()->format('pdf')); $line = 185; $this->_setfontregular($page, 12); $num_lines = count($shippingaddress); $curr_line = 0; foreach ($shippingaddress $value) { $curr_line += 1; if ($curr_line < $num_lines) { if ($value!=='') { $value = wordwrap($value, 20, "\n"); $page->drawtext(strip_tags(ltrim($value)), 75, $line, 'utf-8'); $line -=14; } } }

python - How do Google App Engine Task Queues work? -

i'm confused task execution using queues. i've read documentation , thought understood bucket_size , rate, when send 20 tasks queue set 5/h, size 5, 20 tasks execute 1 after other possible, finishing in less 1 minute. deferred.defer(spam.cookeggs, egg_keys, _queue="tortoise") - name: tortoise rate: 5/h bucket_size: 5 what want whether create 10 or 100 tasks, want 5 of them run per hour. take 20 tasks approximately 4 hours complete. want execution spread out. update the problem assumed when running locally, task execution rate rules followed, not case. cannot test execution rates locally. when deployed production, rate , bucket size had set executed expected. execution rates not honored app_devserver. issue should not occur in production. [answer discovered nick johnson and/or question author; posting here community wiki have can marked accepted]

wpf - How to access command from MainWindow level in another Window? -

i trying access commands defined in mainwindow.xaml in window. able grayed out titles of these commands. wondering should should done in order full access. sample of command: public partial class mainwindow : window { public static routeduicommand addcommand1 = new routeduicommand("command ", "command1", typeof(mainwindow)); public mainwindow() { initializecomponent(); this.commandbindings.add(new commandbinding(addcommand1, addcommand1executed)); } private void addcommand1executed(object sender, executedroutedeventargs e) { addnewitem picker = new addnewitem(); picker.showdialog(); } i access these command in style through databinding: <menu x:name="taskmenucontainer"><menuitem x:name="menuitem" header="tasks" itemssource="{binding}" template="{dynamicresource taskmenutoplevelheadertemplatekey}"> <menuitem.itemcontainerstyle>

2 way UDP proxy in python -

i trying create proxy udp in python. here's scenario: client connects server on port 6000 high random port (say 53273) server reply port 53273 port 55385 then communication continue on these 2 ports. these 2 port number known when communication initiated. the proxy should log messages in both direction text file. thank you i start this: http://docs.python.org/library/socketserver.html#asynchronous-mixins this threaded socket server built python. can use serve main port , call handler whenever client connects. you'll need threaded since sounds running type of chatroom logging.

namespaces - Ruby Constants in Nested classes. Metaprogramming -

q: how share information in nested classes parent class class post model = self extend postmod has_many :comments, :class_name => 'post::comment' class comment include commentmod belongs_to :model, :class_name => "post" def method_in_comment puts model end end class end end module commentmod def method_in_mod1 puts self.class::model end def method_in_mod2 puts model end end module postmod def method_in_mod1 puts self::comment end end b = post::comment.new b.method_in_comment # post b.method_in_mod1 # uninitialized constant post::comment::model (nameerror) b.method_in_mod2 # uninitialized constant commentmod::model (nameerror) reason of such design, in example (real system more complex), add comments model "include module". thats add controllers, views , model methods comments behavior similar models. model may override method in class comment if needs tunned. tricky part of is,

gwt - How to have change debugger setting in Eclipse for a launch file -

his, i have been trying find out why starting devmode debugger eclipse slow , noticed in list of processes on machine following line: /usr/lib/jvm/jdk1.6.0_14/bin/java -agentlib:jdwp=transport=dt_socket,suspend=y,address=localhost:47248 ... apparently application suspended wait until debugger connected takes 2 minutes. set "suspend=n". know set directive. vm section in eclipse launch configuration empty , if paste updated debugger config there error telling values entered twice. as understand it, eclipse takes config somewhere , inserts automatically when run launch configurations in debugger mode. thanks you can't remove parameter and, if could, wouldn't make difference. when connect new browser gwt oophm instance has compile entire project use in development mode. takes time, not waiting debugger attach.

sqlite - Service account throwing SQLiteException on NServiceBus startup -

i'm getting following exception when try start nservicebus.host.exe service account credentials: database not configured through database method. system.data.sqlite.sqliteexception: unable open database file @ system.data.sqlite.sqlite3.open(string strfilename, sqliteopenflagsenum flags, int32 maxpoolsize, boolean usepool) @ system.data.sqlite.sqliteconnection.open() @ nhibernate.connection.driverconnectionprovider.getconnection() in :line 0 @ nhibernate.tool.hbm2ddl.suppliedconnectionproviderconnectionhelper.prepare() in :line 0 @ nhibernate.tool.hbm2ddl.schemametadataupdater.getreservedwords(dialect dialect, iconnectionhelper connectionhelper) in :line 0 @ nhibernate.tool.hbm2ddl.schemametadataupdater.update(isessionfactory sessionfactory) in :line 0 @ nhibernate.impl.sessionfactoryimpl..ctor(configuration cfg, imapping mapping, settings settings, eventlisteners listeners) in :line 0 @ fluentnhibernate.cfg.fluentconfiguration.buildsessionfactory() in d:\dev\fluent

jquery - Add a confirmation dialog to ASP MVC view -

i want have dialog box popup letting user know of consequences when hitting continue button, preferably styled better standard browser popup. i got jqdialog, jquery plugin, , solution: i have view following html: <form id="formsubmit" action="<%= resolveurl("~/summary/summary") %>" method="post"> <input type="button" name="summarybutton" id="bt-confirm" value="continue »" /> </form> and i've bound click event button jquery: $('#bt-confirm').click(function () { $.jqdialog.confirm("are sure want continue?", function () { callsubmit(); }, // callback function 'yes' button function () { alert("this intrusive alert says clicked no"); } // callback function 'no' button ); }); my callsubmit() gets called, form not submitted: function callsubmit() { var s

javascript - Cannot override the CSS at this site -

this site overriding css own , cannot around it! has style.css "text-align: center" in body. i have <div id="mydiv"> appended body , it's got "text-align: left". there <ul> s , <li> s underneath #mydiv , inheriting body's 'center' reason. tried , it's still not working. $('#mydiv').children().css('text-align', 'auto'); how heck reclaim css!? @grillz, html looks this: <div id="mydiv"> <ul class="container"> <li rel="folder" class="category"><a href="#">category1</a> <ul><li rel="file" class="subcategory"><a href="#">subcategory1</a></li></ul> <ul><li rel="file" class="subcategory"><a href="#">subcategory2</a></li></ul> </li> <li rel=&qu

java - image in a brand new jframe? -

i looking class create new jframe displaying image "rules.jpg" found in src folder of project. edit : worked out how there, image still wont display when export jar, have tips? to load image jar, need access differently. there nice swing tutorial doing that: http://download.oracle.com/javase/tutorial/uiswing/components/icon.html#getresource here relevant code form tutorial: java.net.url imageurl = mydemo.class.getresource("images/myimage.gif"); ... if (imageurl != null) { imageicon icon = new imageicon(imageurl); }

ios4 - how to get another plist? -

i accidentally deleted original plist file comes template app. how back? app isn't 'building , going'. please if didn't perform customization plist, simplest way create new application same name , type application (in different folder on machine). generate default plist file application before. can either copy plist file original project or create new plist called -info.plist in original project , duplicate entries created in dummy application created.

java - Thread exiting due uncaught exception -

hy! my code: thread thread = new thread (){ @override public void run() { while (true) { handler handler = new handler(){ @override public void handlemessage(message msg) { if (msg.obj.tostring()!= null) { jsonparse json = null; try { log.e("channel_state",msg.obj.tostring()); json = new jsonparse(msg.obj.tostring()); string state = json.getchannelstate(); id = state; textview tv2 = (textview)findviewbyid(r.id.mainscreen_state); tv2.settext("channel state: "+ state); log.e("state",stat

test if an MSBuild property is defined? -

in msbuild, possible create msbuild condition (or situation) evaluate whether property 'defined' (presuming previous assigning property value somewhere)? the following seems little clumsy reliable: <propertygroup label="undefined state"> <defined></defined> </propertygroup> <choose> <when condition="('$(defined)' == '' or '$(defined)' != '')"> <message text="defined probably/likely/assuredly defined"/> </when> <otherwise> <message text="defined reportedly/maybe/possibly not defined"/> </otherwise> <choose> there exists common method overriding properties. sample c:\windows\microsoft.net\framework\v4.0.30319\microsoft.common.targets <propertygroup> <targetframeworkidentifier condition="'$(targetframeworkidentifier)' == ''">.netframewo

Splitting a large txt file into 200 smaller txt files on a regex using shell script in BASH -

hi guys hope subject clear enough, haven't found in asked bin. i've tried implementing in perl or python, think may trying hard. is there simple shell command / pipeline split 4mb .txt file seperate .txt files, based on beginning , ending regex? i provide short sample of file below.. can see every "story" starts phrase "x of xxx documents", used split file. i think should easy , i'd surprised if bash can't - faster perl/py. here is: 1 of 999 documents copyright 2011 virginian-pilot companies llc rights reserved virginian-pilot(norfolk, va.) ... 3 of 999 documents copyright 2011 canwest news service rights reserved canwest news service ... thanks in advance help. ross awk '/[0-9]+ of [0-9]+ documents/{g++} { print $0 > g".tx