Posts

Showing posts from March, 2014

uitableview - Change UITableViewCell Height on Orientation Change -

i have uitableview cells containing variable-height uilabels. able calculate minimum height label needs using sizewithfont:constrainedtosize:linebreakmode: , works fine when table view first loaded. when rotate table view cells become wider (meaning there fewer lines required display content). there way can have height of cells redetermined uitableview during orientation change animation or before or after? thank you. your uitableviewcontroller can implement tableview:heightforrowatindexpath: method specify row height particular row, , can @ current orientation ( [[uidevice currentdevice] orientation] ) decide height return. to make sure tableview:heightforrowatindexpath: gets called again when orientation changes, you'll need detect orientation change described in this question , , call [tableview reloaddata] .

javascript - Altering firebugx.js to Accommodate IE Developer Tools -

the firebugx.js file (shown below) checks both !window.console , !console.firebug, correctly detects if firebug installed. however, check not accommodate native console object in ie developer tools -- overwrites ie console object. for example, if include firebugx.js code, following exception not appear in ie console (it swallowed): function foo() { try { throw "exception!!!"; } catch (e) { console.error(e); } } question: best approach accommodating ie developer debugger? maybe obvious answer comment out firebugx.js check when debugging in ie. there other approaches? reference: firebugx.js if (!window.console || !console.firebug) { var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupend", "time", "timeend", "count", "trace", "profi...

XNA SpriteBatch causing problems with BasicEffect -

i'm using xna visualize data, , i'm trying use billboards data, , spritebatch hud text drawing. for billboards, i'm using following example, works great: http://create.msdn.com/en-us/education/catalog/sample/3d_audio in example, there cat , dog sprite, cat passes in front of or behind dog, depending on positions , camera position you'd expect. doesn't matter order cat.draw , dog.draw called in. these guys drawn basiceffect. however if add class inherits drawablegamecomponent , uses spritebatch, basiceffect in other components loses it's depth sorting , quads drawn in order called. note component added game class via this.components.add(...). is there incompatibility between basiceffect , spritebatch? problem occurs whenever spritebatch.begin()/end() called. if don't call cat/dog render fine. any ideas? you need reset renderstates spritebatch changes. try setting these before basiceffect calls: graphicsdevice.blendstate = blendstate...

actionscript 3 - Adobe AIR and different OS filesystems -

another adobe air question first here background project have been tasked with. air app read assets usb key , must work on both win , macos. problem is, how load assets app on macos! sounds simple enough , works seamlessly on windows. here code snippet of trying do: var loader:loader = new loader(); loader.contentloaderinfo.addeventlistener(event.complete, ok); loader.contentloaderinfo.addeventlistener(ioerrorevent.io_error, ioerror); var p:string; if (os == "mac") { p = "/volumes/" + keyvolume.rootdirectory.name + file.separator + "0a0ff0ff-f7ae-4b9c-9637-843b1d6c80e8.jpg"; } else { p = keyvolume.rootdirectory.name + file.separator + "0a0ff0ff-f7ae-4b9c-9637-843b1d6c80e8.jpg"; } var temp:file = new file(p); debugger.display.text += "\nattempting load: ...

quote - What's the difference between ' and #' in Lisp? -

it seems both (mapcar 'car '((foo bar) (foo1 bar1))) and (mapcar #'car '((foo bar) (foo1 bar1))) work same. and know ' means (quote symbol) , #' means (function function-name). but what's underlying difference? why these 2 both work in previous mapcar ? 'foo evaluates symbol foo. #'foo evaluates function bound name foo. in lisp symbol can called function when symbol foo has function binding. here car symbol has function binding. but not work: (flet ((foo (a) (+ 42))) (mapcar 'foo '(1 2 3 4 5))) that's because foo symbol not access local lexical function , lisp system complain when foo not function defined elsewhere. we need write: (flet ((foo (a) (+ 42))) (mapcar #'foo '(1 2 3 4 5))) here (function foo) or shorthand notation #'foo refers lexical local function foo. note in (funcall #'foo ...) vs. (funcall 'foo ...) the later might 1 more indirection, since ...

is linfu 2.3 released anywhere? -

i see projects , articles reference linfu.core version 2.3 when go to linfu website here , see version 2.2. does know download linfu.core version 2.3 ?? try: http://github.com/philiplaureano/linfu/archives/master the googlecode site linfu deprecated , linfu hosted on github.

php - Datetime and date-range comparsion -

i have datetime-row in mysql database. have check time between , date using php. if range bigger 1 month - somtething. i tried this: $datefrommysql = strtotime($rowdata); $currentdate = date("m/d/y g:i a"); and comparsion hands. it's ugly. select * mytable mydatetime <= now() - interval 1 month or mydatetime >= now() + interval 1 month this query returns dates @ least 1 month apart now() (either in past or in future).

python - Problem with number/type of arguments passed to an overloaded c++ constructor wrapped with swig -

i trying wrap c++ class (let's call "spam") written else swig expose python. after solving several problems, able import module in python, when try create object of such class obtain following error: foo = spam.spam('abc',3) traceback (most recent call last): file "<stdin>", line 1, in <module> file "spam.py", line 96, in __init__ = _spam.new_spam(*args) notimplementederror: wrong number of arguments overloaded function 'new_spam'. possible c/c++ prototypes are: spam(unsigned char *,unsigned long,bool,unsigned int,sstree::io_action,char const *) spam(unsigned char *,unsigned long,bool,unsigned int,sstree::io_action) spam(unsigned char *,unsigned long,bool,unsigned int) spam(unsigned char *,unsigned long,bool) spam(unsigned char *,unsigned long) googling around, realized error caused type of arguments , not number (which quite confusing), still cannot identify. suspect problem lies in pa...

Using HTML5/Canvas/JavaScript to take in-browser screenshots -

Image
google's "report bug" or "feedback tool" lets select area of browser window create screenshot submitted feedback bug. screenshot jason small, posted in duplicate question . how doing this? google's javascript feedback api loaded here , their overview of feedback module demonstrate screenshot capability. javascript can read dom , render accurate representation of using canvas . have been working on script converts html canvas image. decided today make implementation of sending feedbacks described. the script allows create feedback forms include screenshot, created on clients browser, along form. screenshot based on dom , such may not 100% accurate real representation not make actual screenshot, builds screenshot based on information available on page. it does not require rendering server , whole image created on clients browser. html2canvas script still in experimental state, not parse of css3 attributes want to, nor have support loa...

mysql - Help with two SQL Queries -

i’m having difficulties 2 queries. can of information problem lies in special conditions can’t seem right in sql statement. the first query in natural language defined: i’m going find candidates has acquired 2 qualifications during same time period, different institutes my relational schema looks this: bold = primary key italics = foreign key candidate = ( candidateid , name, birth, mail) qualification = ( qualificationid , instituteid , candidateid , datestarted, datefinished, degreename, major) institute = ( instituteid , institutename, city) the sql i’ve tried run not pretty (at point) , not working either is: select (candidate.firstname, candidate.lastname) candidate, qualification, institute (select count(qualification.candidateid) qualification qualification.candidateid = 2) , between qualification.datestarted , qualification.datefinished , qualification.instituteid <> qualification.instituteid i gives me error , i’m pretty, in count c...

html - need to align part of list item to right of li - using CSS3 Jquery column-layout -

using jquery script acheive css3 3-columns, display list of members alphabetically. i need display way, does: a d b e c f here using http://www.csscripting.com/css-multi-column/example6.php ? (using js file http://www.csscripting.com/js/v1.0beta/css3-multi-column.js ) to right of each member, has phone extension, want float right, easy read. i tried putting phone extension within div , span , when that, tends screw @ last item in each column, placing person's name correctly, extension first item in next column. screenshot: http://cl.ly/fq4 of doing html code: <div class="article3col"> <ul> <li>doe, john <div style="float:right;"> 8317 </div> </li> <li>doe, sally <div style="float:right;"> 8729 </div> </li> <li>doe, john <div...

c# - Dynamically showing fields to a Dev Express Grid view on windows form -

in 1 of windows application in c# , using dev express grid view control bind data , display user. have custom business objects properties defined purpose.then simple set datasource of grid list of custom business objects. a while ago , there came requirement means columns displayed on grid dynamic. means cannot know @ design time fields need display. i thinking of abandoning setting datasource , populating grid manually code. think cause many of grid's features not work properly, example , grouping data drag n drop of fields header area etc. there way tell grid @ runtime skip fields list of bo's when databinding grid ? this pretty simple, time. need bind grid datasource , rest you. hiding fields easy also, set visibleindex -1 you this c# grid.focusedview.columns["col1"].visibleindex = -1; vb grid.focusedview.columns("col1").visibleindex = -1;

project management - Keeping track of business rules within IT department? -

i looking best way keep track of business rules both developers , else (support staff / management) in startup enviroment. challenge our business model requires quite lot of different business rules, created pretty on fly , evolving organically after that. after running project 3+ years, have many of such rules way sure application supposed in situation go find module responsible process , analyze code , comments. fine long have 1 single developer created entire application scratch, every new developer needs go on pretty entire codebase in order understand how application works. bigger problem non technical employees don't have option , therefore forced ask me pretty every day how case handled application. quick example - start charging our customer campaigns once have been active @ least 72 hours, @ same time stop creating invoices campaigns belong insolvent accounts , close such accounts within month of first failed charge. not apply accounts set "non-chargeable" ...

winforms - C# Question:Dynamically Disable ToolStripMenuItems/ToolStripButtons in an MDIParent Form: Which Event? -

any guidance on following issue appreciated. in mdiparent event should disable items/buttons? activated? on program launch, want buttons disabled. if there no active mdichildren, want buttons disabled. when launch child form, want test child form data. if blank form, want buttons remain disabled. have code in mdichildactivated event handler. time. i used activate event disable items/buttons. in mdichildactive event test blank form. if not blank, enable items/buttons.

xaml - WPF: How to justify all lines within paragraphs (lines with line breaks too) -

i have paragraphs within flowdocument, , need justify lines (even lines line breaks) here's code sample: <paragraph textalignment="justify"> "one of important operations necessary when text materials prepared printing or display task of dividing long paragraphs individual lines.<linebreak/> when job has been done well, people not aware of fact words reading have been broken apart arbitrarily , placed rigid , unnatural rectangular framework; if job has been done poorly, readers distracted bad breaks interrupt train of thought." </paragraph> the output of above not justify line has line break, line aligned left, need same-width lines lines how achieved? (note desired output same output achievable in ms word if paragraph has line breaks , set justify, example if have 3 words on line we'll have 1 word on left, 1 in center , 1 on right) thanks, sam i don't think can achieve want. if replace <linebreak/> close...

math - Are there any example of Mutual recursion? -

are there example recursive function call other 1 calls first 1 ? example function1() { //do f2(); //do } function2() { //do f1(); //do } mutual recursion common in code parses mathematical expressions (and other grammars). recursive descent parser based on grammar below naturally contain mutual recursion: expression-terms-term-factor-primary-expression . expression + terms - terms terms terms term + terms term - terms term factor factor * term factor / term factor primary primary ^ factor primary ( expression ) number name name ( expression )

Maven and Eclipse code organization -

i'm new maven, , after having read docs on maven site , sonatype's online maven book, i'm still not clear on how best organize things. i have 2 apps, , b share code mylib. different developers work on apps , app b, released independently. before started maven, in eclipse, i'd have workspace apps , b , mylib. classpath app contained mylib. if made change in mylib, pressing run within eclipse, contained latest changes. in maven, can create parent pom.xml, references app , mylib. makes mylib subdirectory of app a. how can keep 1 instance of mylib , not link building of apps , b? we use svn our scm thanks you have multiple options, however, potentially simplest approach separate out mylib own maven project own life-cycle. benefit of approach can support having multiple versions of mylib , apps , b can reference different versions of mylib needed. if mylib , appa open in eclipse (and mylib references version of mylib have open), can build application ...

Solr date range and specific date -

i index data include date in solr when search specific date, record (not record) include record in next day example: http://localhost:8080/solr/select/?q=pubdate:[2010-03-25t00:00:00z 2010-03-25t23:59:59z]&start=0&rows=10&indent=on&sort=pubdate desc i have 625000 record in 2010-03-25 above query result return 325412 include 14 record 2010-03-26. also try below query, not right result http://localhost:8080/solr/select/?q=pubdate:"2010-03-25t00:00:00z"&start=0&rows=10&indent=on&sort=pubdate desc how right result specific date? could please me?

python - Is it possible to turn this code snippet in a list comprehension? How? -

= 0 b = {'a': [(1, 'a'), (2, 'b'), (3, 'c')], 'b': [(4, 'd'), (5, 'e')]} c, d in b.iteritems(): e, f in d: += e // = 15 tried several ways. want know way (if possible) simplify sum list comprehension: a = sum(...) thank in advance, pf.me a = sum(e d in b.itervalues() e, _ in d) works in python 2.7. a = sum([e d in b.itervalues() e, _ in d]) works in python 2.3. i haven't tried it, a = sum(e d in b.values() e, _ in d) should python 3.0 equivalent.

date - Javascript: getFullyear() is not a function -

i getting error: statdate.getfullyear() not function. from javascript code: var start = new date(); start = document.getelementbyid('stardate').value ; var y = start.getfullyear(); any idea why function isn't available? try this... var start = new date(document.getelementbyid('stardate').value); var y = start.getfullyear();

onClick event in android webview too slow -

i've got feeling javascript pretty fast in andorid webview, there long delay between touching element , onclick event beeing fired. i imagine feature if navigate between pages - first see highlight on element, , see effect (navigation). applications, slow. is there way change behavior? or there maybe event should go for, onhover or ontouch? fires way before onclick? this known 'issue' related 300ms due user tapping/zooming @ display: http://updates.html5rocks.com/2013/12/300ms-tap-delay-gone-away in near future, seems solved, in static sized layouts, adding information @ header. actual webkit webview version not have/consider option. in case, solution use tappy lib: https://github.com/filamentgroup/tappy just import it, , bind each element has click event, , see difference. just 1 more point: adjusted timer 100000ms (default:1000ms) avoid event repetition in specific cases.

asp.net mvc 2 - Serving application with wrong mime type -

my mvc 2 application seems serving pages application/vnd.wap.xhtml+xml in firefox beta 10. works fine in other browsers. any ideas? bug ff4 , should ignore it? we having same trouble our asp.net 2.0 webforms using 51degrees.mobi , wurfl. anyway, upgrading latest version of 51degrees solved our problem. made sure firefox 4.0 in our web_browsers_patch.xml file.

visual studio 2010 - Expired Beta Release of Silverlight -

i getting following message when trying create new silverlight application in vs2010rc: this application created expired beta release of silverlight. please contact owner of application , have them upgrade application using official release of silverlight. what need resolve issue? the final releases of both visual studio 2010 , silverlight 4 available, suggest "upgrade".

How can I determine if jquery tab is shown because of user click or from tab rotation -

i've been using jquery ui tabs bit , interesting request has come up. current tab setup using rotation feature. need find way determine if tab shown because of result of rotation itself, or because user physically clicked tab. i've wired of standard events, show , select , fire regardless of source of tab change. does have ideas? i'd additional if user clicked tab, not if tab changes via rotation. if wire click tabs doesn't seem fired @ all, i'm assuming because tabs widget using event itself. edit: here's basic code <script type="text/javascript"> $(document).ready(function(){ $("#featured").tabs( {show: function(e, ui) { console.log(e);} } ).tabs("rotate", 5000, false); }); </script> the console show event (e) whether clicked user or shown part of rotation. also, same if change event show: select: from jqueryui documentation : this event triggered when clicking tab. $( ...

javascript - Functions with appropriate parameters -

hello have more of question. working functions , events have far.. <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>personal information</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <link rel="stylesheet" href="js_styles.css" type="text/css" /> <script type="text/javascript"> //<![cdata[ function printperonalinfo( "name,age,hobbies,favorite movies") { document.write("<p>" + name +"</p>"); document.write("<p>" + age +"</p>"); document.write("<p>" + hobbies + "</p>"); document.write("<p>" + favorite video + "</p>"); ...

cocoa - How to properly save a QTMovie after editing using QTKit? -

i making minor edits qtmovie in application using nsdocument architecture (such adding track, shown below). after edit, want save original file. however, keep getting 'file busy' error. assume due oversight made in handling of files, or failure in how using nsdocument. tips helpful! here (some of) relevant code: // open file has track want add movie qtmovie* tempmovie = [qtmovie moviewithurl:outputfileurl error:nil]; // use old api add track addmovieselection([movie quicktimemovie], [tempmovie quicktimemovie]); // filename nsdocument nsstring *filename = [[self fileurl] path]; nslog(@"writing filename: %@", filename); // flatten movie file don't external references nsmutabledictionary *attributes = [nsmutabledictionary dictionarywithcapacity:1]; [attributes setobject:[nsnumber numberwithbool:yes] forkey:qtmovieflatten]; // attempt write nserror *error; // "file busy" if (![movie writetofile:filename withattributes:attributes error:...

How to keep an ordered list on the App Engine DataStore, in a way each entity knows its position on the list? -

i have ranking of people, based on points earn. need tell each participant position on game example, john (1) - 170 points, mary (2) - 160 points, sarah (3) - 110 points so john's first one, mary's seconds , sarah's third. if mary wins 20 more points, she'll first , john second. i'm trying avoid having run task on cron list , recalculate everybody's position. my first try maintain separate set of entities (personrank) wouldn't run transaction problems, rank have same key name, db.get() key. entity have person's calculated rank, when person receives points, i'd have check if next person on line has fewer points me, , exchange places me that's true. problem sarah, on example, may have won 100 points, , number one. on previous algorithm, i'd have "walk" among lot of entities, means lot of datastore gets , puts (updating each involved entity new position). my next guess maybe kind of linked list referenceproperties, maybe u...

sql server - Detail Dimension for Drillthrough -

i have created number of type 1 dimensions hold customer/subscription level details. these dimensions large compared other dimensions using 1 1 relationship facts. dimensions being used provide drillthrough details. it's working size of these dimensions quite large , i'm running memory issues when processing. i'm wondering if there porperties should setting since these used drillthrough? nonaggregateable? would better include details nonaggregateable measures since there 1 1 relationship? an example subscriptiondetail has values email, useruid, activationcode. if users looking @ subscription fact can drillthrough pull these details. you won't able use strings measures, email out. i have had success using hidden datetime measures drillthrough though, exact datetime when fact table keys off date dimension. if processing issue, , there 1:1 fact, dimension change historically? if not, have tried processadd add new rows? if have enterprise ssis th...

assembly - Anything wrong with the assmbly code to count number of positive element in list -

can please advice wrong below assmbly code using tasm, can not output @ below. from tasm output d:\tasmzip\tasmzip>tasm test1.asm turbo assembler version 1.0 copyright (c) 1988 borland international assembling file: test1.asm error messages: none warning messages: none remaining memory: 453k d:\tasmzip\tasmzip>tlink test1.obj turbo link version 2.0 copyright (c) 1987, 1988 borland international d:\tasmzip\tasmzip>test1 d:\tasmzip\tasmzip> my code: assume cs:code , ds : data org 0000h data segment list db 2,23,11,7,5,25,13,18,0 ; given array last element 0 indicate end of array data ends code segment org 2000h start : lea si , list mov cl,0 mov al,0 again: cmp al,[si] ; end of je on inc si inc cl jmp again on : mov ah,4c int 21h code ends end start you not printing out answer, exiting 0 return value. need add more system calls print out value ...

flex - Callable objects on ActionScript? -

is posible have callable objects on actionscript? example: class foo extends eventdispatcher { foo() { super(); } call(world:string):string { return "hello, " + world; } } and later... var foo:foo = new foo(); trace( foo("world!") ); // not work why need this? (i'm not criticising, interested!) functions in as3 first-class citizens, , can passed around arguments. e.g. public function main(foo:function):void { trace(foo("world!")); // work, assuming foo = function(str:string):string {...} }

Perl not closing TCP sockets if clients are no longer connected? -

the purpose of application listen specific udp multicast , forward data tcp clients connected server. code works fine, have problem sockets not closing after tcp clients disconnects. socketsniffer utility shows the sockets remain open , udp data continues forwarded clients. problem believe "if ($write->connected())" block return true, if tcp client no longer connected. use standard windows telnet connect server , see data. when close telnet, tcp socket suppose close on server. any reason why connected() show connections active if not? also, alternative should use then? code: #!/usr/bin/perl use io::socket::multicast; use io::socket; use io::select; $tcp_port = "4550"; $tcp_socket = io::socket::inet->new( listen => somaxconn, localaddr => '0.0.0.0', localport => $tcp_port, ...

c# - ADO.NET parameters from TextBox -

i'm trying call parameterized stored procedure sql server 2005 in c# winforms app. add parameters textboxeslike (there 88 of them): cmd.parameters.add("@customername", sqldbtype.varchar, 100).value = customername.text; i following exception: "system.invalidcastexception: failed convert parameter value textbox string. ---> system.invalidcastexception: object must implement iconvertible." the line throwing error when call query: cmd.executenonquery(); i tried using .tostring() method on textboxes, seemed pointless anyway, , threw same error. passing parameters incorrectly? it's probable forgot specify text property when assigning 1 of parameter values. for example, instead of: customername.text you may have done just: customername this easy thing miss if there 88 of them.

iphone - Why is uitableview underneath my uinavigationbar -

i have uinavigationcontroller uiviewcontroller (vc1) "root view controller". there 3 views in uiviewcontroller: headerview(uiviewsubclass) uitableview (custom frame) footerview(uiviewsubclass) the reason header/footer view separate uitableview because need stationary , allow uitableview scroll. when vc1 loaded in place , behaves expected. however, when click on of cell rows, navigate vc2 , navigate vc1 tableview "under" uinavigationbar. note: root view controller (vc1) subclass of uiviewcontroller change frame size tableview. frame tableview set in ib (0,0, 320,300). stated before when vc1 loaded tableview aligned under headerview, when navigate vc1 vc2. i have tried setting autoresizingmask uiviewautoresizingflexibletopmargin in viewdidload, noavail. suggestions appreciated i fixed problem. problem related issue three20 thumbnailviewcontroller

inheritance - In Perl/Moose, how can I apply a modifier to a method in all subclasses? -

i have moose class intended subclassed, , every subclass has implement "execute" method. however, put apply method modifier execute method in class, applies execute method in subclasses. method modifiers not preserved when method overriden. there way ensure subclasses of class have method modifier applied execute methods? example: in superclass, have this: before execute => sub { print "before modifier executing.\n" } then, in subclass of that: sub execute { print "execute method running.\n" } when execute method called, doesn't "before" modifier. this augment method modifier made for. can put in superclass: sub execute { print "this runs before subclass code"; inner(); print "this runs after subclass code"; } and instead of allowing subclasses override execute directly, have them augment it: augment 'execute' => sub { print "this subclass method"; }; ...

google app engine - Transaction to find an entity - locks all entities of that type? -

reading docs transactions: http://code.google.com/appengine/docs/java/datastore/transactions.html an example provided shows 1 way make instance of object: try { tx.begin(); key k = keyfactory.createkey("salesaccount", id); try { account = pm.getobjectbyid(employee.class, k); } catch (jdoobjectnotfoundexception e) { account = new salesaccount(); account.setid(id); } ... when above transaction gets executed, block other write attempts on account objects? i'm wondering because i'd have user signup checks username or email in use: tx.begin(); "select user musername == str1 limit 1"; if (count > 0) { throw new exception("username in use!"); } "select user memail == str1 limit 1"; if (count > 0) { throw new exception("email in use!"); } pm.makepersistent(user(username, email)); // ok. tx.commit(); but above more time consuming think, making worse bottl...

javascript - Using drop down selection to populate a text box with a default in KnockoutJS -

i have simple order creation form on office app i'm building. scenario cannot figure out under "order lines" section of form. want click add row row appears contains drop down containing products, 2 text boxes quantity , price. want when product selected, products price set default value in price text box, use able change still. so far have in- can add rows, can select part- piece cannot figure out how correctly populate default price. cut down version of knockout viewmodel looks this; viewmodel = { parts : ko.observablearray(initialdata.parts), sale : ko.observable(initialdata.sale), salelines : ko.observablearray(initialdata.salelines), addrow: function() { this.salelines.push({ id: "00000000-0000-0000-0000-000000000000", saleprice : 0.00, qty : 1, partid: "" }); $("select").combobox({ selected: function (event, ui) { $(ui...

http - How can I encode a filename in PHP according to RFC 2231? -

how can encode value of filename according encoding of mime parameter value , encoded word extensions: character sets, languages, , continuations (rfc 2231) ? i think should it: function rfc2231_encode($name, $value, $charset='', $lang='', $ll=78) { if (strlen($name) === 0 || preg_match('/[\x00-\x20*\'%()<>@,;:\\\\"\/[\]?=\x80-\xff]/', $name)) { // invalid parameter name; return false; } if (strlen($charset) !== 0 && !preg_match('/^[a-za-z]{1,8}(?:-[a-za-z]{1,8})*$/', $charset)) { // invalid charset; return false; } if (strlen($lang) !== 0 && !preg_match('/^[a-za-z]{1,8}(?:-[a-za-z]{1,8})*$/', $lang)) { // invalid language; return false; } $value = "$charset'$lang'".preg_replace_callback('/[\x00-\x20*\'%()<>@,;:\\\\"\/[\]?=\x80-\xff]/', function($match) { return rawurlencode($match[0]);...

drupal - How to validate PAN No and Bank account number using php? -

i need validate pan number , bank account number fields. how can using php? have implement validation in civicrm custom form. civicrm has built in function these 2 validations. pan number validation regular expression if (!preg_match("/^([a-za-z]){5}([0-9]){4}([a-za-z]){1}?$/", $pannumber)) { echo "invalid pan number"; }

asp.net mvc - Create custom Helper in ASP NET MVC 3 and Razor -

i creating helper asp net mvc 3 , razor display grid @helper listapessoa(ienumerable<testehelpersmv3.models.pessoamodel> listapessoa) { <table> <tr> <th></th> <th>nome</th> <th>endereco</th> <th>datanascimento</th> </tr> @foreach (var item in listapessoa) { <tr> <td> @html.actionlink("edit", "edit", new { id = item.nome }) | @html.actionlink("details", "details", new { id = item.nome }) | @html.actionlink("delete", "delete", new { id = item.nome }) </td> <td>@item.nome</td> <td>@item.endereco</td> <td>@item.cidade</td> </tr> } </table> } but razor can not find @html.actionlink , following error o...

XNA Level config file in C# -

i'm working on small game class , wondering easy way handel level configuration files. object placements , names, etc. i'm new c# fluent in java, ruby. so xml? yml? text, serialized objects? first thing came mind: lua; it's pretty generic , there's class available it: http://xnua.com/xna_lua_xnua

indexing - What kind of indexes does Firebird use and why? -

according firebird faq , indexes directional, means don't use classical b-trees implementation. use? what advantages? other databases use too? the link provided not contain enough information make conclusion index structure used firebird. afaik, firebird indexes b-tree variants. not have direct documentation link right support word, can see references: tracker entry reporting wrong index entries order @ non-leaf b-tree pages (firebird tracker) description of b-tree page structure ods version (ibexpert documentation) there many other examples on internet, google it.

c++ - Simple alternative to GNU Readline library not GPL -

i love gnu readline library, since under gpl license, can not use commercial software. know alternatives ? need commandline history , auto completion (of customer keywords , files) features. found link : http://github.com/antirez/linenoise which seem starting point, not have auto completion. any suggestions, surely must common task people building interactive shell commands. update : upps forgot 1 important detail should run on windows.. netbsd has readline replacement library called libedit, see http://www.thrysoee.dk/editline/ .

Java 2D additive colors -

are there way draw additive colors using graphics2d. e. g. if cyan , red lines overlap, intersection of white color? thanks. it sounds want enable xor mode , results not defined , may not want. perhaps using alphacomposite can achieve want? outcome more predictable.

servlets - Form filling validation in Java -

i check in servlet, works. how validation of form filling? example, re-send user .jsp-file, if username registered? sorry bad english. public void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // fetch username sent in request string username = request.getparameter("username"); // todo: verify if username taken in database // based on results set value request.setattribute("isusernametaken", "true"); requestdispatcher dispatcher = getservletcontext().getrequestdispatcher("/register.jsp"); dispatcher.forward(request, response); }

git - Passing a string to a bash script via an argument -

i'm writing bash script that, amongst other things, triggers git commit on codebase specified drupal 6 site. script accepts 2 arguments, second of commit message git commit. #!/bin/sh directoryname=${1} commitmsg=${2} echo $directoryname echo $commitmsg git add . git commit -vam "the commit message" the script called this: sh git-bash-test.sh name_of_directory "custom commit message" how can change out "the commit message" value stored in $commitmsg? simply replace "$commitmsg": git commit -vam "$commitmsg"

java - Swapping names using indexOf and substring and compareTo -

i having trouble understanding how use indexof() , substring() , compareto() methods flip people's first name last name in array. let's have following: string[] names = new string[]{"joe bloggs", "sam sunday"}; you can use following code swap last name , first name: for (int i=0; < names.length; i++) { string somename = names[i]; int spacebetweenfirstandlastname = somename.indexof(" "); //these next 2 lines of code may off character //grab characters starting @ position 0 in string not including // index of space between first , last name string firstname = somename.substring(0, spacebetweenfirstandlastname); //grab characters, start @ character after space , go // until end of string string lastname = somename.substring(spacebetweenfirstandlastname+1); //now, swap first , last name , put array names[i] = lastname + ", " + firstname; } the string compareto method...

c# - Creating and Saving an Excel File -

i have following code creates new excel file in c# code behind. when attempt save file user select location of save. in method #1, can save file using workbook savecopyas without prompting user location. saves 1 file c:\temp directory. method #2 save file in users\documents folder, prompt user select location , save second copy. how can eliminate first copy saving in users\documents folder? excel.application oxl; excel._workbook owb; excel._worksheet osheet; excel.range orng; try { //start excel , application object. oxl = new excel.application(); oxl.visible = false; //get new workbook. owb = (excel._workbook)(oxl.workbooks.add(missing.value)); osheet = (excel._worksheet)owb.activesheet; // ***** osheet.cells[2, 6] = "ship to:"; osheet.get_range("f2", "f2").font.bold = true; osheet.cells[2, 7] = sshiptoname; osheet.cells[3, 7] = saddress; osheet.cells[4, 7] = scitystatezip; osheet.cells[5, ...

How to return a view for HttpNotFound() in ASP.Net MVC 3? -

is there way return same view every time httpnotfoundresult returned controller? how specify view? i'm guessing configuring 404 page in web.config might work, wanted know if there better way handle result. edit / follow up: i ended using solution found in second answer question slight tweaks asp.net mvc 3 handle 404s: how can handle 404s in asp.net mvc? httpnotfoundresult doesn't render view. sets status code 404 , returns empty result useful things ajax if want custom 404 error page throw new httpexception(404, "not found") automatically render configured view in web.config: <customerrors mode="remoteonly" redirectmode="responserewrite"> <error statuscode="404" redirect="/http404.html" /> </customerrors>

OCaml: Matching with any negative -

is there way pattern matching match value negative number? not matter negative number need match negative. i have accomplished want simple code: let y = if(n < 0) 0 else n in match y 0 -> [] | _ -> [x] @ clone x (n - 1) but want eliminate if statement , check case in match statement yes, use guard: match n _ when n < 0 -> [] | _ -> [x] @ clone x (n - 1)

java - Are autoboxing and unboxing operator overloading -

are autoboxing , unboxing fancy terms operator overloading? happens when integer = 10; ? no, it's not operator overloading. java doesn't provide mechanism operator overloading. integer = 10; is saying: integer = integer.valueof(10); which isn't overloading = @ all.

How to extract a part of xml code from an xml file using c# code -

<?xml version="1.0" encoding="utf-8" standalone="yes" ?> <erecon xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:nonamespaceschemalocation="erecon.xsd"> <header> <company code="" /> <commoncarriercode /> <inputfilename inputidpk="">f:\reconnew\tmesysrec20100111.rec</inputfilename> <batchnumber>000152</batchnumber> <inputstartdatetime>2010-02-26 11:47:00</inputstartdatetime> <inputfinishdatetime>2010-02-26 11:47:05</inputfinishdatetime> <recordcount>8</recordcount> </header> <detail> <carrierstatusdate>2010-01-11</carrierstatusdate> <claimnum>ydf02892 c</claimnum> <invoicenum>0108013775</invoicenum> <lineitemnum>001</lineitemnum> <nabp>10600211</nabp> <rxnumber>4695045</rxnumber> <...

java - in a J2EE application when does a listener get called? -

i have j2ee app , has listener in web.xml . listener contains method called contextinitialized i want know when contextinitialized called? from reading understand gets called when deploying application. can there situations/scenario's called after application has been deployed? in clustered glassfish app server environment. called after application has been deployed? it's called once when application first deployed. shouldn't called again if application stays deployed. however, application may go through undeploy/deploy cycle while server running. example, can set application redeployed when file changed in directory.

android - Put circle over google map -

i have map ( geoactivity ) in app. need mark region circle, circle need move finger touch . how achieve ? need similar http://www.apartmentfinder.com/georgia/atlanta-apartments when go on personalize search . any idea, advice ? have looked @ following post creating custom overlay on map

ergonomics - Best keyboards for emacs? -

Image
for emacs users out there, recommended keyboards? bonus points keyboards that: have no capslock key. instead, control key in position. alt keys closer centre, , easier use meta key combos. find alt keys far left bit awkward hit thumb in key combos. help ergonomically emacs in other ways. i'm not huge fan of model m style high , clacky keys. instead prefer laptop style flat keys; however, i'm not disqualifying either category. a couple of interesting keyboards i'm curious if people have tried emacs - kinesis semi-conclusion: ended getting ms natural 4k, lot overall alt keys on both sides easy hit thumbs. useful ergoemacs-mode . however, 1 flaw see keyboard number keys shifted left, 6 on wrong side of keyboard. aside 0 left shifted enough accidentally hit - when meant hit 0 pinky. due flaw, i'm leaving question open in case can come perfect emacs keyboard. richard stallman (which i'm sure know author of emacs, , biggest emacs...

c# - Overloading Methods Or Not? -

what have here 2 methods (killzombie) handle cases have 1 argument (string) or more 1 argument (string[]). because same thing, made method named "killazombie" used other 2 methods. problem i'm having method "killazombie" named... kind of strangely. problem other people encounter too? best way solve , name "killazombie" method else distinguishes more "killzombie" public void killzombie(string zombielocation){ killazombie(zombielocation); } public void killzombie(string[] zombielocations){ foreach(string zombielocation in zombielocations){ killazombie(zombielocation); } } public void killazombie(string zombielocation){ //kills zombie @ specified location } another way can see problem being solved instead of overloading "killzombie" have 2 different methods this: public void killzombie(string zombielocation){ //kills zombie @ specified location } public void killzombies(string[] zombielocatio...

What network port to use for mobile app -

i have mobile app uses socket connection communicate server. however, seems users complaining port blocked isp, or wireless network. is there range of ports are well-known enough not blocked not used mobile devices use? or there better way address issue? asking isp/wireless network admin unblock port not feasible thing me do. edit: i'm looking @ canadian, us, , european mobile operators in particular. the best , port use 80 standard http traffic. you try... 443 ssl http traffic 8080 backup http traffic port used proxy servers or links. but if remotely worried networks blocking traffic standard http , port 80 ways go. networks allow port 80 if allow thing. btw times way ask isps/networks open port server isn't ideal if block port 80 going have ask them.

escaping - PHP: escape filename as linux does -

i'm having troubles filenames upload users have process. when try access them, because of them have special characters, command used says file not found or similar. i've used escapeshellcmd no sucess. when use "tab" key in linux console (when have started type filename , want complete), bash escape filename correctly, , if use "escaped" filename, works. i've tried this: preg_replace("/[^a-za-z0-9\-\.\s]/", "\\\\$0", $filename) to escape except numbers, letters, - , spaces ... found file "test_1.jpg", command converts "test_1.jpg", , not work, since "_" not need converted. i'm afraid there more "allowed" characters, question ... how can "clone" escape function of "tab" key in linux console bash ? thank ! i use both file names , making urls out of blog post titles , like. // lower , no spaces begin or end $path = strtolower(trim($path)); // add...

css - -moz-linear-gradient with PNG background over top -

so firefox supports gradient backgrounds. supports multiple background images.. why not work?? background:-moz-linear-gradient(top, #5989bd,#336296), url(active-arrow.png) right center no-repeat; also tried: background-color:-moz-linear-gradient(top, #5989bd,#336296); background:url(active-arrow.png) right center no-repeat; can done?? you must include background image before linear gradient. e.g: background: url("http://127.0.0.1/css/bg.png") no-repeat, -moz-linear-gradient(top left, rgb(0,255,0), rgb(255,0,0));

c# - Getting File name from the String -

could me finding file name string. have 1 string of content "c:\xxxx\xxxx\xxxx\abc.pdf". want file name ie. abc.pdf. how using string functions? use path.getfilename : string full = @"c:\xxxx\xxxx\xxxx\abc.pdf"; string file = path.getfilename(full); console.writeline(file); // abc.pdf note assumes last part of name file - doesn't check. if gave "c:\windows\system32" claim filename of system32, though that's directory. (passing in "c:\windows\system32\" return empty string, however.) can use file.exists check file exists and file rather directory if help. this method doesn't check other elements in directory hierarchy exist - pass in "c:\foo\bar\baz.txt" , return baz.txt if foo , bar don't exist.

Problem with the Blackberry browser -

i working on application have image onwhich when u click gets navigated browser link dont display web page. need code displaying simple web page in blackberry.. simulator , device working simulator.so kindly me it....i newbie blackberry.. thank in advance help.. the following code open native browser url specify: browser.getdefaultsession().displaypage(url);

objective c - How to access files in interior of an iPhone App? -

i need in iphone app access files app build with(.plist etc). there's hardcoded way this: nsstring *appdir = [[[nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes) objectatindex:0] stringbydeletinglastpathcomponent] stringbyappendingpathcomponent:appfolder]; where appfolder name of folder app, "test.app". after appdir known, access files simple. is there other, not-hardcoded way have access files form app? thanks in advance! nsstring* pathtofile = [[[nsbundle mainbundle] resourcepath] stringbyappendingpathcomponent:@"myfile.plist"]; // or, better (handling localization): nsstring* pathtofile = [[nsbundle mainbundle] pathforresource:@"myfile" oftype:@"plist"];

c# - WCF Best Practice/Cleanest Method implementation in Silverlight -

http://www.dnrtv.com/default.aspx?shownum=122 after watching above video "extreme wcf", clean approach taken towards layout of code. however not directly apply silverlight. i wondering if either knew how tie proxy @ end of video silverlight, or if knew of similar method tidying wcf up. either or discussion on wcf techniques helpful. thanks public class proxy : clientbase<itaskauditservice> , itaskauditservice { #region itaskauditservice members public ienumerable<taskaudittype> getlist( string measure, string username, string taskreason ) { return channel.getlist(measure, username, taskreason); } public ienumerable<string> getusers() { return channel.getusers(); } public ienumerable<string> gettaskreasons() { return channel.gettaskreasons(); } public ienumerable<string> getmeaures() { return channel.getmeaures(); } #endregion } as requ...

css - How to vertically center divs? -

i'm trying make small username , password input box. i ask, how vertically align div? what have is: <div id="login" class="blackstrip floatright"> <div id="username" class="floatleft">username<br>password</div> <div id="form" class="floatleft"> <form action="" method="post"> <input type="text" border="0"><br> <input type="password" border="0"> </form> </div> </div> how can make div id username , form vertically align center? i've tried put: vertical-align: middle; in css div id login, doesn't seem work. appreciated. the best approach in modern browsers use flexbox: #login { display: flex; align-items: center; } some browsers need vendor prefixes. older browsers without flexbox support (e.g. ie 9 , lower), you'll need ...

java - Logarithmic Spiral -

so in programming class learning use draw classes. draw line , stuff , did y=mx+b line in class. i wanted jump ahead , start doing more crazy mathematical ones! i'm having trouble using 1 though, found on u of princeton website. public class spiral { public static void main(string[] args) { int n = integer.parseint(args[0]); // # sides if decay = 1.0 double decay = double.parsedouble(args[1]); // decay factor double angle = 360.0 / n; double step = math.sin(math.toradians(angle/2.0)); turtle turtle = new turtle(0.5, 0.0, angle/2.0); (int = 0; < 10*n; i++) { step /= decay; turtle.goforward(step); turtle.turnleft(angle); } } } import java.awt.color; public class turtle { private double x, y; // turtle @ (x, y) private double angle; // facing many degrees counterclockwise x-axis // start @ (x0, y0), facing a0 degrees counterclo...

c# - Catching a SoapException thrown by a WebService -

i wrote following service : namespace webservice1 { [webservice(namespace = "http://tempuri.org/")] [webservicebinding(conformsto = wsiprofiles.basicprofile1_1)] [system.componentmodel.toolboxitem(false)] public class service1 : system.web.services.webservice { [webmethod] public string test(string str) { if (string.isnullorempty(str)) throw new soapexception("message", soapexception.clientfaultcode); else return str; } } } and basic application test (one button calling test method on click event): private void button1_click(object sender, eventargs e) { servicereference1.service1soapclient ws = new windowsformsapplication1.servicereference1.service1soapclient(); try { ws.test(""); } catch (soapexception ex) { //i never go here } catch (faultexception ex) { //always go there...