Posts

Showing posts from January, 2010

Ruby composition/design quandary -

Image
i trying create convinience method called: def signin_screen end which should have 2 components. all common methods devicescreen's signin_screen specific methods either android/ios (which determined @ runtime based in env variable) signinscreen have methods def emailfield end def passwordfield end but may have common methods , specific methods. now androidscreen , iosscreen subclasses of devicescreen. design signinscreen, should class under each of these or module? please don't add emphasis android/ios/screens etc. person student faculty/staff, need have common authentication class i don't have experience in specific topic answer based on general ideas. in opinion, signinscreen serves controller prepare content show, while both androidscreen , iosscreen should nothing more templates. content controller , show on specific device. by design, signinscreen(or better name without screen since controller or controller actio...

Php redirect with variable -

i trying use header("location: http://www.mysite.com/gamecode.php?gameid=$pw"); below code. <?php header("location: http://www.mysite.com/gamecode.php?gameid=$pw"); $con = mysqli_connect("localhost","placeholder","placeholder","placeholder"); //or die ('unable connect'); // check connection if (mysqli_connect_errno()) { echo "failed connect mysql: " . mysqli_connect_error(); } //create random table name $alpha = "abcdefghijklmnopqrstuvwxyz"; $numeric = "0123456789"; $special = ".-+=_,!@$#*%<>[]{}"; $chars = ""; if (isset($_post['length'])){ // if want form above if (isset($_post['alpha']) && $_post['alpha'] == 'on') $chars .= $alpha; if (isset($_post['alpha_upper']) && $_post['alpha_upper'] == 'on') $chars .= $alpha_upper; if (isset($_po...

javascript - Create an image puzzle game using jQuery -

i'm trying create image puzzle game using jquery. using code var img_one=$("img[src$='one.jpg'][name='a']"); var atrval_one=img_one.attr("src"); var img_two=$("img[src$='blank.jpg'][name='b']"); var atrval_two=img_two.attr("src"); $('#one').click(function() { if(atrval_two == "images/img/blank.jpg"){ $("img", '#one').attr("src", atrval_nine); $("img", '#two').attr("src", "images/img/one.jpg"); } }); and html <div id="one" class="1" style="background-repeat:no-repeat;position:absolute;"><img id="1" name="a" src="images/img/one.jpg" /></div> <div id="two" class="2" style="background-repeat:no-repeat; position:absolute;"><img id="2" name="b" src="imag...

php - Yii - no values are being retrieved from the MYSQL database -

i new yii framwork in php. had created mysql database using python , populated using python code. have used same database yii , created models , controllers table using gii. have opened crud interface listing values -> http://localhost/vawhack/index.php?r=appname/admin i getting message "no results found." , no values saved in database shown. missing in between?

muxing overhead error when converting a video via ffmpeg -

i'm using ffmpeg converting videos on site. i'm converting videos flv . if upload flv , has not problem if upload other file type except flv , shows me error : ffmpeg version 0.7.11, copyright (c) 2000-2011 ffmpeg developers built on jul 26 2013 01:58:02 gcc 4.4.7 20120313 (red hat 4.4.7-3) configuration: --enable-gpl --enable-version3 --enable-nonfree --enable-shared --enable-libmp3lame --enable-libx264 --enable-libfaac --enable-libvorbis --enable-libopencore-amrnb --enable-libopencore-amrwb libavutil 50. 43. 0 / 50. 43. 0 libavcodec 52.123. 0 / 52.123. 0 libavformat 52.111. 0 / 52.111. 0 libavdevice 52. 5. 0 / 52. 5. 0 libavfilter 1. 80. 0 / 1. 80. 0 libswscale 0. 14. 1 / 0. 14. 1 libpostproc 51. 2. 0 / 51. 2. 0 seems stream 0 codec frame rate differs container frame rate: 2997.00 (2997/1) -> 14.99 (15000/1001) input #0, avi, 'uploads/v_37.avi': metadata: title : aj mclean - teenage wildlife encoder : lavf52.16.0 duration: 00:04:17.19, start: 0.000000, ...

image processing - feature detectors and descriptors comparison -

there several kinds of detectors , descriptors, sift, surf, fast. wonder eligible real-time applications? best or better? and furthermore, harris-laplacian dectector still useful when have above three? better them? i can advise use hessian-affine , mser detection, if need invariance different factors (e.g., viewpoint change) or fast, if need real time. fast doing similar job harris, faster. you can " local invariant feature detectors: survey ", , " a comparison of affine region detectors " many detectors tested , described well. update: " wxbs: wide baseline stereo generalizations " extended benchmark of novel , classical detectors , descriptors. second, description part slower detection, real-time have use gpu or binary descriptor brief or freak . update2: " hpatches (homography patches) dataset , benchmark " , corresponding workshop @ eccv 2016. http://www.iis.ee.ic.ac.uk/computervision/descrworkshop/index.html . ...

javascript - Page.handleJavaScriptDialog does not work in Chrome 29 -

i using page.handlejavascriptdialog in chrome.debugger handle js dialog in chrome extension. fails in latest chrome 29. chrome.debugger.sendcommand({"tabid": 2}, "page.handlejavascriptdialog", {accept:true}, function(msg){}); is there replace or api changed?

java - Get a file from a given classpath -

public string getquery(string namefile, package pathfile) { // how on inputstrem namefile , pathfile } i not able make through classloader string path = getclass().getpackage().getname().replace('.', file.pathseparatorchar); string file = path + "file.txt"; inputstream in = this.getclass().getclassloader().getresourceasstream(file); return in = null the pathseparatorchar : on unix , ; on windows. has nothing char used load resources classloader, / , on platforms. moreover, forgot separator between path , file name. should be string path = getclass().getpackage().getname().replace('.', '/'); string file = path + "/file.txt"; inputstream in = this.getclass().getclassloader().getresourceasstream(file); or, simpler, since class has method can load resources same package class directly: inputstream in = this.getclass().getresourceasstream("file.txt");

excel vba - How to get the Date from Time Stamp -

am having 1 excel file contains data multiple sheets. in 1 column having time stamp 21/6/12 10:33:07:am. system date format "m/d/yyyy" while converting date 21/06/2012. able date showing in wrong. 06-12-2021 should 21-06-2012. using below code. ex : 26/6/12 11:15:07:am should 26/06/2012 21/6/12 10:33:07:am should 21/06/2012 public sub convtdate() dim parsedatetime date application.screenupdating = false each datcol in ws_raw2.range("i2:i65536") x = instr(1, datcol, " ", vbtextcompare) - 1 if x > 0 parsedatetime = datevalue(left(datcol, x)) datcol.value = parsedatetime end if next application.screenupdating = true end sub please how date. in advance. datevalue expects date string in format set system. excel help: if date string includes numbers separated valid date separators, datevalue recognizes order month, day, , year according short date format specified system. since data in day month...

android - Detect new data when call is given to webservice -

i have app, in refreshing app in particular amount of time. each time call given webservice , messages in database loaded listview. its done follows: public class messages extends activity { protected handler handler = new handler(); @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_messages); intent intent = getintent(); string message = intent.getstringextra(mainactivity.extra_message); string id = intent.getstringextra(mainactivity.extra_id); string[] lst = null; listview lm=(listview)findviewbyid(r.id.listview1); textview tv = (textview)findviewbyid(r.id.textview1); tv.settext("welcome " + message); handler.postdelayed(new updatetask(),750); } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getme...

html - css background-height makes element overflow -

i have webpage in want set height of head 60px, somehow inner elements overflow , doesn't show right. i'm suspecting logo's background somehow setting height bigger should be. i'm setting background-size: 202px 56px; , height:56px; . original height of background image 250x69px , should resized (auto calculated)x56px (or fixed 202x56px ok too). if displaying right, there should small 'border' on bottom turns blue when corresponding top element hovered. the styles written in scss of compass , compiled css . i've used compass generate sprites. i've provided css files on webpage. i'm not putting code here because it's large (200+ lines in each file). if have show scss files, please let me know. the webpage i'm editing can found on address: http://stogrebro.com/page-test/ i'm creating webpage on localhost there might broken links. if there important missing, please let me know. i made tries page , found out "o...

Java creating a custom Map -

i have 2 questions regarding following code: 1) there way can implement map in case, rather extend 1 direct implementation of interface? not wish write whole map implementation though. nice seeing implementation not care underlying map implementation being used. 2) there bad practices? extremesmap.java package ocr.util; import java.util.arrays; import java.util.hashmap; import java.util.hashset; import java.util.list; import java.util.set; /** * * @author student */ public class extremesmap extends hashmap<string, integer> { private set<string> smallest; private int smallestvalue; private set<string> biggest; private int biggestvalue; public extremesmap() { super(); smallest = new hashset<>(); smallestvalue = integer.max_value; biggest = new hashset<>(); biggestvalue = integer.min_value; } @override public void put(string key, integer value) { if (value == nu...

Android MediaPlayer freezes after seeking a new video position -

i load .mp4 on videoview, things go fine until drag seekbar point new position, mediaplayer starts buffering , app freezes (not crash, freeze) error message: "can't play video" this code: try { // start mediacontroller controller.setanchorview(videoview); // url string videourl uri video = uri.parse(getintent().getextras().getstring("video")); videoview.setmediacontroller(controller); videoview.setvideouri(video); } catch (exception e) { log.e("error", e.getmessage()); e.printstacktrace(); } videoview.requestfocus(); videoview.setonpreparedlistener(new onpreparedlistener() { // close progress bar , play video public void onprepared(mediaplayer mp) { pdialog.dismiss(); videoview.start(); } }); no errors if seek already-buffered position. only no-buffered positions. error log: attempt perform seekto in wron...

c++ - Using different fonts/attributes in QTextEdit -

i have problem displaying text area different attributes. my project has multi-threading build. reach gui text area using signal-slot mechanism. put texts text area this; addrmw->ui->printerarea->appendplaintext(command.data); i want append text area different font, size, etc.. i'm using qt creator 2.7.2 / qt 5.1. explain me example? what want rich text edit. luckily qtextedit able handle that. check acceptrichtext property (which should true default). then methods you're looking are: setcurrentcharformat setcurrentfont setfontfamily setfontpointsize etc... then, instead of appendplaintext() should use append() add text qtextedit . see q/a . proposed in accepted answer, can use html formatted text instead.

calculate months between two dates in java -

this question has answer here: java date month difference 16 answers i need calculate months between 2 dates, if startdate=2013.01.01, enddate=2013.01.31 answer should 1, startdate=2013.01.01, enddate=2013.02.01 answer should 2. please help use joda months : datetime start = new datetime(startdate.gettime()); datetime end= new datetime(enddate.gettime()); int months = months.monthbetween(start, end).getmonths();

php - Strange behaviour in hierarchical menu? -

the function simple: function showmenu( $level = 0 ) { $sql = "select * `menus` `submenu`=".$level; $result = mysql_query( $sql ); echo "<ul>"; while ( $node = mysql_fetch_array( $result ) ) { echo "<li>". $node['name']; $sql_ = "select * `menus` `submenu`=".$node['id']; $haschild = mysql_fetch_array( mysql_query( $sql_ ) ) != null; if ( $haschild ) { showmenu( $node['id'] ); } echo "</li>"; } echo "</ul>"; } but results when i'm using level 1 or on strange. example: showmenu( 1 ); will return me items, except first items. function showmenu( $level = 0 ) { $sql = "select * `menus` `submenu`=".$level; $result = mysql_query( $sql ); echo "<ul>"; $rows = ""; wh...

android - TextView Marquee and Digital Clock -

when use digital clock , textview marquee , textview marquee not work- , if remove digital clock works perfectly. textview tv = new textview(this); tv.setlayoutparams(paramssong); tv.setellipsize(truncateat.marquee); tv.setfocusableintouchmode(true); tv.setfreezestext(true); tv.setsingleline(true); tv.setmarqueerepeatlimit(-1); tv.settext("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); tv.setselected(true); rl.addview(tv); digitalclock dg = new digitalclock(this); rl.addview(dg); /*if remove digital clock works*/ can not use both @ same time or there solution? yes can use these first correct mistakes 1. adding view rl.addview(tv); 2 times 2. set height , width of digitalclock try following code working fine me textview tv = new textview(this); rl.addview(tv);// here mistake ! remove tv.setlayoutparams(paramssong); tv.setellipsize(truncateat.marquee); ...

php - Unable to pass form values using POST method -

i'm trying pass multiple values input form (checkboxes) post method, 1 of values dumping, no matter how many checkboxes checked.. doing wrong? var_dump($_post); result : array(2) { ["pal_num"]=> string(1) "2" ["post"]=> string(3) "go!" } code: <?php $l = $_post['lt']; $pals = ''; $r = mysql_query("select distinct pal_num pl_tab lt_num='$l'"); while($row = mysql_fetch_assoc($r)) { $pals .= '<input type="checkbox" name="pal_num" value="'.$row['pal_num'].'">'.$row['pal_num'].'<br>'; } if($pal == '') echo ''; else echo '<form name="get_pal" action="post.php" method="post">'; echo $pals; echo '<input type="submit" name="post" value="go!">'; echo '</form>'; ?> you should post...

Capistrano custom strategy without making a gem -

is there way of making custom deploy strategy capistrano, without having bundle gem? i've searched , searched everyone's examples packaged gems. i want stick in include path , require in capfile. something should work: require 'capistrano/recipes/deploy/strategy/remote_cache' class insanestrategy < capistrano::deploy::strategy::remotecache def copy_repository_cache do_something() end end set :strategy, insanestrategy.new(self)

php - Laravel 4 htaccess redirect loop -

i have laravel 4 application , have subfolder applications. laravel 4 app in root folder , there .htaccess file there following content: options -multiviews rewriteengine on rewritecond %{http_host} !^www\. rewriterule ^(.*)$ http://www.%{http_host}/$1 [r=301,l] rewritecond %{request_filename} !-f rewriterule ^ index.php [l] now, if go www.mysite.com/subfolder-app redirect loop error. error subfolder on server you should able change rewriterule include sub-folder: options -multiviews rewriteengine on rewritecond %{http_host} !^www\. rewriterule ^(.*)$ http://www.%{http_host}/$1 [r=301,l] rewritecond %{request_filename} !-f rewriterule ^ /subfolder-app/index.php [l] note, however, won't "dyamically" change environment. if localhost running laravel in webroot instead of sub-folder, making change htaccess file make no longer work in localhost dev environment. one solution not use .htaccess file, rather include rewrite rule in virtual host configur...

php 5.3 - Imagick setSamplingFactors in php -

i using imagick in php create image property "chroma subsampling" 4:2:2 (2x1,1x1,1x1) i use code: $image = new imagick('test.jpg'); $factors = array("2,1,1"); $image->setsamplingfactors($factors); $image->writeimage('test2.jpg'); $image->destroy(); but result is: jpeg:sampling-factor: 2x2,1x1,1x1 to see image's properties; use: $image = new imagick(test2.jpg'); $identify = $image->identifyimage(true); $data = $identify['rawoutput']; i want set: jpeg:sampling-factor: 2x1,1x1,1x1 thanks in advance , time i found 1 solution using shell_exec, <?php $path = "e3.jpg"; $path2 = "e3.jpg"; $arr = array("-sampling-factor 4:2:2"); $properties = ""; foreach ($arr $property) { $properties .= $property." "; } $cmd = "convert ".$path." ".$properties." ".$path2; shell_exec($cmd); ?> i hope find right soluti...

python - A scalable solution for sharing objects between threads in web.py (+ flup/fcgi) -

i need share object between threads in web.py . i'm running web service performs calculation & returns value. calculation done using object takes quite lot of memory, don't want created each request. i have solution works fine, doesn't seem scale: import web urls = ('/', 'index') class index: def get(self): ... result = web.myobject.docalculation() return result if __name__ == "__main__": app = web.application(urls, globals()) web.myobject = loadobjectfromfile app.run() web.py automatically opens 10 threads, number fixed, , it's limiting. can change that? the web.py install guide recommends using flup + server lighttpd , or apache . can done while retaining shared object feature need? can tell me how? i installed flup , added " fcgi " command line parameter when starting server. gave me desired behaviour in terms of threads (unlimited number), of course didn't perform task. fcgi seve...

java - How to create a Jahia Ajax Call (JSP,JQuery) -

when build module/component need pass actionresult in order recieve proper httpservletrequest in ajax call? for instance (in jsp): var location = '${currentnode.path}.sqlpaging.do'; $.post(location, function(data) { temp=data; alert(data.info); $('#result').html(data); }); further information (here class): @override public actionresult doexecute(httpservletrequest req, rendercontext rendercontext, resource resource, jcrsessionwrapper session, map<string, list<string>> parameters, urlresolver urlresolver) throws exception { jsonobject json = new jsonobject(); json.put("info",3.14); actionresult result = new actionresult(httpservletresponse.sc_ok, null, json); result.setjson(json); return result; } packages used: javax.servlet.http org.jahia.bin.actionresult org.json.jsonobject that problem. needed have json...

php - MySQL multiple selects in one query -

for example have few tables: products: | product_id | name | price | | 1 | apple | 20.32 | | 2 | pear | 9.99 | | 3 | banana | 1.5 | product attribute: | attr_id | name | value | | 1 | weight | 10 kg | | 2 | date | 2013 | | 3 | color | red | ...and on. product-attribute relations table: | product_id | attr_id | | 1 | 3 | | 2 | 1 | | 1 | 2 | | 3 | 2 | my question : there available construct 1 select request query returns product 1 , 2 in following data structure(or similar)? should run deveral select requests first "where product_id in (1, 2)" , throught loop select them attributes. sorry bad english :] array( [0] = array( product_id = 1, name = apple, attributes= array( [0] => array( attr_id = 3, name = color, ...

ios - Assigning a dictionary to a variable -

when check self.weatherdata, nothing though there data in "data". here function: - (void)handlenetworkresponse:(nsdata *)mydata { //nsmutabledictionary *data = [nsmutabledictionary dictionary]; nsmutabledictionary *data = [[nsmutabledictionary alloc] init]; // we'll parse our data using nsjsonserialization id myjson = [nsjsonserialization jsonobjectwithdata:mydata options:nsjsonreadingmutablecontainers error:nil]; // typecast array , list contents nsdictionary *jsonarray = (nsdictionary *)myjson; // take @ elements in array (id element in jsonarray) { id key = [element description]; id innerarr = [jsonarray objectforkey:key]; nsdictionary *inner = (nsdictionary *)innerarr; if ([inner conformstoprotocol:@protocol(nsfastenumeration)]) { for(id ele in inner) { id innerkey = [ele description]; [data setobject:[[inner valueforkey:innerkey] description] for...

objective c - @autorelease Pool and Loops (for, while, do) Syntax -

clang allows following loop syntax: for (...) @autorelease { ... } while (...) @autorelease { ... } @autorelease { ... } while (...); i haven't found documentation on syntax far (apple doesn't use syntax in guides, @ least no in guides introducing @autorelease construct), reasonable assume 3 statement above equivalent 3 statements below: for (...) { @autorelease { ... } } while (...) { @autorelease { ... } } { @autorelease { ... } } while (...); since expect them (going standard c syntax rules), yet i'm not entirely sure if that's case. "special syntax", autorelease pool not renewed every loop iteration. both syntax same -(void)afunc { int i=0; for(;i<5;) @autoreleasepool { ++i; } } -(void)bfunc { int i=0; for(;i<5;) { @autoreleasepool { ++i; } } } assembly code "-[appdelegate afunc]": ## @"\01-[appdelegate afu...

azure - Programmatically spawn new instances of a worker role -

is possible programmatically spawn new instances of worker role? have worker role that's dependent on service bus queue(s) grabs messages , puts data table storage, sql database , sends out notifications. need able add more instances depending on sb queue sizes can gradually receive larger amounts of messages in future. possible me control code? , in case how? there multiple ways achieve functionality: 1) windows azure supports auto-scaling based on amount of messages in service bus queues. can configure scaling work inside azure management portal. free while in beta, , price has not yet been announced when live. 2) there open-source api called wasabi microsoft's patterns , practices group. you'll need place host it, it'll communicate azure service management api on behalf , provide framework implementing own auto-scaling based on service bus queues. using it, instrumenting configuration xml files 3) if don't mind using 3rd party products ...

ios - UICollectionView steals focus -

i have uicollectionview header, cells , footer supplementary views. header contains uisearchbar . if type search field, keyboard automatically dismisses after first letter. think caused -searchbar:textdidchange: , contains code refreshing collection view (via -reloaddata , because method know works). my theory is, reloading uicollectionview causes become first responder , somehow not work. i have line in output every time keyboard dismisses: setting first responder view of collection view don't know type (cell/header/footer) i attempted overwrite uicollectionview 's -canbecomefirstresponder , unfortunately didn't work. any ideas how can prevent uicollectionview become first responder after reload? i've had luck restoring search bar first responder after updating table view: collectionview.reloaddata() searchbar.becomefirstresponder()

php - Log4php wrong time -

i'm new user of log4php , have problem time. time logged in log file late of 2 hours compared real time. configuration file contains: < layout class="loggerlayoutpattern"> < param name="conversionpattern" value="%-5level %date{y-m-d h:i:s,u} %logger %msg%n" /> < /layout> my configuration: apache-log4php-2.3.0 wampserver 2.4 -x64 windows 7 64 bits how can correct time ? advice :) have set timezone in php script? you can set like: date_default_timezone_set('europe/amsterdam'); or can set on server in php.ini or .htaccess files shown in following article. how set timezone on php server.

recaptcha - Customize Google Re Captcha in Perl -

i want customize google re captcha have digits option verification code. is possible . if yes how ? no, not possible. the recaptcha system meant easy way plug in captcha site. side effect, helps digitizing books using image snippets scans visual challenge. if numbers should displayed, such “words” books used known numbers. void secondary objective of recaptcha (helping transcription of scans). using numbers makes system less secure (in theory). whereas attacking ocr software might have difficulty telling apart g , 9 , becomes unambiguous.

java - Run jbehave stories from a user defined location -

i new jbehave i trying execute jbehave through junit. seems jbehave loads story files classpath. possible configure fetch story files user defined path. public class algebrastory extends junitstories { @override public configuration configuration() { return super.configuration() .usestoryreporterbuilder( new storyreporterbuilder() .withdefaultformats() .withformats(console, txt)); } @override public injectablestepsfactory stepsfactory() { return new instancestepsfactory(configuration(), new calculator()); } @override protected list<string> storypaths() { return new storyfinder().findpaths((<user defined path>, "**/algebra_story.story", ""); } } in same way possible save jbehave reports in user defined path. yes, can locate stories anywhere want in network. them in class path, or externally, locatable via urls. see locating stories . and recommend l...

sql - MySQL query that gets all rows UNTIL the SUM(column) is bigger than X -

i have following data user_id days date 88 2 2013-08-25 88 4 2013-08-23 88 18 2013-08-5 88 1 2013-08-4 88 2 2013-08-2 73 11 2013-08-2 299 4 2013-08-2 12 983 2013-08-2 i'm trying recent rows ( order date desc ) specific user_id , until sum of days column bigger x . example in case if x=7 3 first rows sum(days)=24. try this. here use local variable count sums in subquery. select user_id, days, date ( select user_id, days, date, @sum_days := @sum_days + days sum_days mytable order date desc ) t cross join (select @sum_days := 0) const -- resetting @sum_days var. sum_days < x -- fill number in x here.

provisioning - Device’s Activation Code best practice -

quoting documentation: once pre-registered, device can activate sending activation code xively api. signals xively device has woken first time, , requesting provisioned feed id , api key can use. device’s activation code generated using hmac-sha1 hash combines device’s serial number parent product’s product secret makes impossible extract product secret activation code, or fraudulently impersonate device in provisioning process. what best practice: keeping activation code on each device memory: time consuming program @ factory time computing activation code on device wakeup via hmac-sha1(serialnumber, productid) . in case second make more sense, cannot find how hmac calculated api docs. string concatenation? padding? everything errordeveloper said absolutely correct. one additional thing keep in mind product secret listed on product (or device) page in hex pair format. not need convert string hex, rather use current string hex string. can see how done in a...

Define a custom CakePHP pagination url -

is possible define custom url cakephp pagination url? i need /:slug/:slug2/:slug3/ . how should provide url pagination? thanks!! p.s. if i'm using this, cakephp defines controller , view automatically in url , result /controller/action/something/ - need disable controller , action in url. $this->paginator->options(array( 'url' => '/something/' )); use routing. http://book.cakephp.org/2.0/en/development/routing.html you should not use string type urls "internal" links because won't work routing , links wont work more in case app in subdirectory of webroot.

php - Magento - Get custom form field value from product page -

i have magento shop in client wants sell personalized gift items. example pencil customer's girlfriend name. in product page managed show in form product_addtocart_form fields one: <input type="text" value="" id="gift_name" name="gift_name"> now have observer when user checkout ( checkout_type_onepage_save_order_after ) should custom field value can't figure out how. i tried mage::app()->getfrontcontroller()->getrequest()->getparam('gift_name'); didn't work out. i think parameter being passed form quantity, how can retrieve it? you can use below code parameter url in observer function $request = $observer->getevent()->getdata('front')->getrequest(); $parameter = $request->yourparametername;

objective c - In Java is there a name for the object the method is called on? -

when explain code, have write "the object method called on". e.g. the contains() method checks if input substring present in the string call contains() on . in objective-c i'd write the contains() method checks if input substring present in receiver (string). which makes sense objective-c uses message passing , message has sender , receiver. the lack of expression java terminology makes descriptions complicated when object in question cannot named explicitly. there exist standard name the object method called on ? verdict : receiver seems express relationship best. that's called "receiver". see terminology .

AJAX or more specific MooTools Request.JSON error types? -

i'm trying myself overview errors can occur on request.json(). i've googled while there seems not overview them all. i've figured out 404 error occures if no such file available request on. does have idea find them? think has not specific mootools errors, i'm looking ajax errors itself. kind regards well, ajax has no 'error codes'. ajax asynchronous request making server without refreshing page. things can go wrong same things can go wrong on normal request. these instance http status codes: http://www.w3.org/protocols/rfc2616/rfc2616-sec10.html some frameworks implement error codes or change of them. frameworks/libs (like mootools) have usefull onfailure() function passes in xhr object used dor request. the 'error' code noet 'ajax' code http code.

css3 - Style table to highligh every other 2 rows -

i've been reading css3's nth-child, can't figure out how can style table rows 3,4 | 7,8 | 11,12 | 15,16 etc. yellow. every other 2 rows styled. thanks combine following: every 4th row starting 3rd one , nth-child(4n+3) every 4th row starting 4th one ( nth-child(4n+4) ) - can nth-child(4n) : table tr:nth-child(4n+3) td, table tr:nth-child(4n+4) td { background: red; } demo

php - Is there a way to count integers in an array less than a given point without a foreach loop? -

is possible count integers in array match criteria (e.g. less n ) without foreach loop? $arr = range(0,100); // not consistent 0,1,2,3...100. 1,1,3,5,25,6,10,100. $n = 20; echo countlessthan($n,$arr); // can work without loop? echo countlessloop($n,$arr); // works, of loop // can make work without loop? function countlessthan($n,$arr) { $count = ?; // number of items in $arr below $n return $count; } // works, loop function countlessloop($n,$arr) { $count = 0; foreach($arr $v) { if ($v < $n) $count++; } return $count; } one generic method can use of array_filter function creates array of elements meeting criterion (given function name) for example count number of elements in array bigger 3 1 can run function test($x){ return $x>3; } $data = array( 1,2,3,4,5 ); echo count( array_filter( $data, 'test' ) ); which prints 2 but - without restrictions on criterion and/or array - solution use loop "under hood...

Red Hat Linux + Rails + RVM: Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension -

so i'm trying deploy rails 3 app red hat linux server uses rvm, keeps failing: ** [out :: myserver.server.com] gem::installer::extensionbuilderror: error: failed build gem native extension. ** [out :: myserver.server.com] ** [out :: myserver.server.com] /usr/local/rvm/rubies/ruby-1.9.3-p448/bin/ruby extconf.rb ** [out :: myserver.server.com] checking vm_core.h... no ** [out :: myserver.server.com] checking vm_core.h... no ** [out :: myserver.server.com] makefile creation failed ** [out :: myserver.server.com] ************************************************************************** ** [out :: myserver.server.com] no source ruby-1.9.3-p448 provided debugger-ruby_core_source gem. ** [out :: myserver.server.com] ************************************************************************** ** [out :: myserver.server.com] *** extconf.rb failed *** ** [out :: myserver.server.com] not create makefile due reason, lack of ** [out :: myser...

main() function in C -

i've been learning c programming in self-taught fashion weeks, , there questions have concerning main() function. all functions must declared in function prototype, , later on, in defintion. why don't have declare main() function in prototype first? why have use int main() instead of void main() ? what return 0 in main() function? happen if wrote program ending main() function return 1; , example? you need either definition or prototype in order call function, main must never called other function, must not declared. because c standard says so. operating systems pass return value calling program (usually shell). compilers accept void main , non-standard extension (it means "always return 0 os"). by convention, non-zero return value signals error occurred. shell scripts , other programs can use find out if program terminated successfully.

javascript - Force encoding used in XHR request -

in browser extension i'm developing, i'm doing xhr request load data, using jquery: $.get(url).done(function(data, textstatus) { console.log(data); }) the remotely-loaded data windows-1252 encoded csv file served content-disposition:attachment , without mime-type/charset header (i don't have control on backend, can't fix that). how can force browser decode response windows-1252 instead of utf-8 apparently does? as hinted previous research , first answers, couldn't find way wanted using jquery. worked around issue using vanilla xmlhttprequest responsetype=blob, explained in https://developer.mozilla.org/en-us/docs/web/api/xmlhttprequest/sending_and_receiving_binary_data var oreq = new xmlhttprequest(); oreq.open("get", url, true); oreq.responsetype = "blob"; oreq.onload = function(e) { var blob = new blob([oreq.response], { type : 'text\/csv' }); account.data = blob; } oreq.onerror = function(e){ ... } ...

c# - Sharing authentication between 3 websites -

i have main website, 2 sub-sites. want create simple way authenticate on website such can view other 2 sub-sites. the websites setupa follows: www.example.com/ www.example.com/subsite1 www.example.com/subsite2 as further requirement, subsite1 , subsite2 may re-used on different website. could use built in authentication module in asp.net this? or have create own custom cookie? yes, since 3 sites on same domain, share forms authentication cookie between 3 applications. achieved setting domain property on 3 applications: <forms domain="www.example.com" ...> also work should share same machine keys between 3 applications. please take @ following article on msdn goes further details.

perl - RDF::Redland::Model how to add tag <foaf::nick> -

i have loaded rdf::redland::model parsed rdf/xml document , want add tag <foaf::nick> in it. how can it? update: this code far: my $st = rdf::redland::node->new_xml_literal("<foaf:nick>content</foaf:content>"); $self->{model}->add_typed_literal_statement($st); print $self->{model}->to_string; and doesn't work. doing wrong? rdf models don't contain tags (or xml elements); rdf model set of triples of form subject predicate object . foaf:nick property relates foaf:person nickname. based on title of question, sounds want add triple something foaf:nick somenick model. in case, documentation rdf::redland::model indicates you'll want either add or add_typed_literal_statement : add subject predicate object add new statement model subject, predicate , object. these can rdf::redland::node, rdf::redland::uri or perl uri objects. add_typed_literal_statement subject predicate string [xml_la...

Save a http link in word document with java BufferedWriter -

Image
i want save http link in word document using java application (file.doc) .i succesfully write link word document using bufferedwriter class link in word document simple line of text . if press enter button on document word turns http link , that's want java application , save http format here code : import java.awt.borderlayout; import java.awt.dimension; import java.awt.eventqueue; import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.border.emptyborder; import javax.swing.jfilechooser; import javax.swing.jlabel; import javax.swing.jbutton; import javax.swing.joptionpane; import javax.swing.jtextpane; import java.awt.font; import java.awt.event.actionlistener; import java.awt.event.actionevent; import java.io.bufferedwriter; import java.io.file; import java.io.filewriter; import javax.swing.jtextfield; import java.awt.toolkit; import javax.swing.imageicon; import java.awt.event.mouseadapter; import java.awt.event.mouseevent; public class save_file ex...

c# - Grouping algorithm for combinations -

let's have list of items, each item defined simple structure struct simpleitem { string category1; string category2; ... string categoryn; } each item have series of values belonging categories. number of categories n known @ time of processing list , each items have same amount of categories , 1 value per category, there no duplicate items. however, each list can have different category set. i'm looking way group these items categories in way if groups deconstructed single items combining each permutations of categories, i'll end original combinaisons, no duplicates. a group result be: struct grouped { string[] category1; string[] category2; ... string[] categoryn; } example for sake of example, we'll limit 3 categories, there can n. categories animal, eye color, fur choices "animal" category : cat, dog, rat, horse choices "eye color" category : blue, yellow, green, red, orange choices ...

c# - returning an assignment expression -

while working on of older code in c#, encountered code irked me. without ado, goes this: private string foo(string _text) { /* manipulation on _text */ return _text = server.htmldecode(_text); } it's last line irks me; i'm c background, , can understand code in effect trying return decoded _text variable. value of assignment operator left operand, can see it. yet still find irksome. is ordinate practice in c# need accustomed to? to me last line should be return server.htmldecode(_text); and not assignment expression. there deeper c# feature i'm not aware of? while working on of older code in c#, encountered code irked me. there numerous irksome problems here. let's list them all. private string foo(string _text) { /* manipulation on _text */ return _text = server.htmldecode(_text); } it's last line irks me the comment irksome. local variables cheap . there no need erase original value of _text . instead, make ...

android - SrollView in content of DrawerLayout prevents the drawer to be opened by swiping -

when put scrollview content of drawerlayout , nolonger able open drawer swiping side. activity layout: <android.support.v4.widget.drawerlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- menu_main content view --> <framelayout android:id="@android:id/content" android:layout_width="match_parent" android:layout_height="match_parent"/> <!-- navigation drawer --> <listview android:name="com.gumtree.androidapp.drawerfragment" android:id="@+id/drawer" android:layout_width="240dp" android:layout_height="match_parent" android:layout_gravity="start" /> </android.support.v4....

How to load DLL using C#? -

i have small dll has 3 functions : init, load , run. i'm new c# read questions here, i've opened console project , wanted load dll , use it's functions. unfortunately - didn't work. can advise went wrong? this error get: unable find entry point named 'init' in dll '....path dll....'. this code: using system; using system.collections.generic; using system.linq; using system.text; using system.runtime.interopservices; namespace consoleapplication1 { class program { [dllimport("c:\\desktop\\dlltest.dll", charset = charset.unicode)] public static extern bool init(); [dllimport("c:\\desktop\\dlltest.dll", charset = charset.unicode)] public static extern bool load(string file); [dllimport("c:\\desktop\\dlltest.dll", charset = charset.unicode)] public static extern bool play(); static void main() { console.writeline("got ti...

html - How do I dynamically create events and event handlers in javascript -

i'm trying create buttons dynamically unique listeners , handlers using loop, unfortunately must doing wrong because last button works. more surprising fact when clicking last button instead of "button no.3" returns "button no.4" bellow code , here jsfiddle http://jsfiddle.net/y69jc/4/ html: <body> <div id="ui"> text ... </div> </body> javascript: var uidiv = document.getelementbyid('ui'); uidiv.innerhtml = uidiv.innerhtml + '<br>'; var results = ["button one","button two","button three","button four"]; for(var n=0;n<results.length;n++) { uidiv.innerhtml = uidiv.innerhtml + '<button id="connect'+n+'">option'+n+':'+results[n]+'</button><br>'; var tempid = document.getelementbyid('connect'+n); tempid.addeventlistener('click', function(){console.log("button ...