Posts

Showing posts from May, 2012

Javascript function with vars on PHP print: quotes -

i wondering if there better way write down php vars passed javascript function called inside php print.: while($nav = mysqli_fetch_array($nav_db)){ print '<li> <a href="#" onclick="getproductpage('.$nav['id'].', \''.$name.'\')"> '.$nav['data'].' </a> </li>'; } where $nav['id'] is integer don't need '' js, and $name is not integer need \' \' js. especially step: getproductpage('.$nav['id'].', \''.$name.'\') thank you <?php while($nav = mysqli_fetch_array($nav_db)): ?> <li> <a onclick="getproductpage(<?php echo $nav['id']; ?>, '<?php echo $name; ?>')"> <?php echo $nav['data']; ?> </a> </li> <?php endwhile; ?> you should break ou...

angularjs - $http.get is not allowed by Access-Control-Allow-Origin but $.ajax is -

i have problem fetching json remote server control. have 2 web applications, 1 serving data , running on port 3311, other, requesting data, running on port 5000. using jquery following works: $.ajax({ url: "http://localhost:3311/get-data", type: 'get', datatype: 'json', beforesend: function(xhr) { xhr.setrequestheader("x-some-header", "some-value"); } }) .done(function(data) { $rootscope.$apply(function() {d.resolve(data); }); }) .fail(function(data) { $rootscope.$apply(function() {d.reject(data); }); }); when attempting same request angular $http .get("http://localhost:3311/get-data", { headers: {"x-some-header": "some-value"} }) .success(function(data) { d.resolve(data);}) .error(function(data) { d.reject(data); }); i receive error origin http://localhost:5000 not allowed access-control-allow-origin. the console log shows error occurring after options requ...

class - How to understand python classes? -

hello i'm learning python, first language. i'm trying figure out how classes work. have small code , can't work after week of searching. thank helping me. also i'm trying figure out getattr , super do. read on documentation not easy me understand. english not native language , little difficult understand sometimes.if can explain 2 things or if know website explains in simple way thank it. here code: import sys class map(object): dicti = {'stuff': stuff(), 'more_stuff': more_stuff() } class stuff: def stuff(self): print "did work?" next = raw_input("type next: ") if next == "next": return 'more_stuff' else: print "what? lets try again." return 'stuff' class morestuff: def more_stuff(self): print "ok" next...

android - Button Contacts : couldn't save which view has focus because the focused view.com has no id -

error: couldn't save view has focus because focused view com.android.internal.policy.impl.phonewindow$decorview@40556f58 has no id here code: intent intent = new intent(intent.action_pick, contactscontract.contacts.content_uri); startactivityforresult(intent,pick_contact ); and result: public void onactivityresult(int reqcode, int resultcode, intent data) { super.onactivityresult(reqcode, resultcode, data); switch(reqcode) { case (pick_contact): if (resultcode == activity.result_ok) { uri contactdata = data.getdata(); cursor c = managedquery(contactdata, null, null, null, null); if (c.movetofirst()) { string id = c.getstring(c.getcolumnindexorthrow(contactscontract.contacts._id)); string has...

In Linux Driver, how to disable a specific USB Device -

assume usb devices powered usb bus. firmware in usb device encounter problem , can't recovery itself. have unplug , plug usb device host. is there way can dis-power usb device, , later re-enable usb device in linux driver or in shell command? by way, need standard method. in specific platforms, can disable usb ehci/ohci's power in driver.

function - C++ Infinite Loop causing a stack overflow error? -

okay, i've been working on calculator. trying tell difference between valid integer , character. easy workaround did: int calc() { cout << "number 1:"; cin >> fnum; cout << "number 2:"; cin >> snum; if (snum <= -1000 || fnum <= -1000) { cout << ("error: invalid number!") << endl; calc(); } else { ff(); } return 0; } and whenever enter in character goes infinite loop saying: symbolhere:number 1:number 2: ff(); calling in calculation function. i wondering how fix , prevent stack overflow/ infinite loop? pastebin link: http://pastebin.com/gxn2ujaq edit: ok, there number of things code. wait = 0; while (wait <= 5) { wait++; } will absolutely nothing, program increment fast undetectable human mind. recommend removing entirely. if (snum >= 0 || fnum >= 0) { cout << ("error: invalid number!") <...

c - Is 'vacated' in open address hash table only capable to store one variable? -

i'm studying master algorithms c , in open address hash table program, author defined: void *vacated; point vacated position in hash table. if delete 2 values in hash table consecutively. true not possible vacated point last deleted variable? if delete 2 variables of same hash value consecutively. think different deleting 2 variables of different hash value. in function ohtbl_remove , not find statement null variable deleted. how manages delete variable if delete variables consecutively? thanks. int ohtbl_remove(ohtbl *htbl, void **data) { int position, i; /***************************************************************************** * * * use double hashing hash key. * * * *****************************************************************************/ ...

c# - Is it possible to limit extension methods in a class to be of specific type? -

this requirement driven grief peer developers mix extension method on different types 1 xxxext class. still works because compiler takes care of resolution looking @ imported namespaces. annoying , not easy maintain when comes overlapping types. is @ possible constraint type extensions written in specific xxext class? circulating manual rules not work well... possibly static code analysis if not compiler level restriction? code (which want restrict in class isactiverisk method). public static class tradedataext{ public static bool isactivetrade(this tradedata tradedata){...} public static bool isactiverisk(this riskdata riskdata) {...} } this more of "desired" feature, not sure if @ possible. comments/suggestions helpful. first of all, seems me wrote example , forgot more important keyword of extension methods, missed keyword "this" right before parameter! :) i'm guessing meant: public static class tradedataext { public...

javascript - location.replace to remove history of current page without redirecting? -

i had posted question regarding problem here . when click on submit button or link, not want history of page user clicked button or link recorded in browser. i received suggestion use history.pushstate() . not familiar function , urgently need solution work. i still not sure do. can suggest me whether can use solve problem. <input type="submit" onclick="location.replace(this.href); return false;"/> <a href="foo.jsp" onclick="location.replace(this.href); return false;">continue</a> example : have page bar.html has link <a href="foo.html">foo</a> . when user clicks on link, should redirected foo.html , browser history of bar.html should not recorded user cannot use button on page. edit: how can force browser not store page in cache, next time user visits, browser requests server page. here working example: file: a.html <!doctype html> <html lang="en"> ...

c# - How to Restrict canvas size in wpf when Zoomed -

i designing wpf in visual studio 2010 application implementing zoom feature in canvas. event is: < canvas mousewheel="canvas_mousewheel" /> and backend in xaml.cs is: const double scalerate = 1.1; private void canvas_mousewheel(object sender, mousewheeleventargs e) { if (e.delta > 0) { st.scalex *= scalerate; st.scaley *= scalerate; } else { st.scalex /= scalerate; st.scaley /= scalerate; } } the problem when zooming figure in canvas ,the whole canvas expanding , taking whole space undesired.because want zoom in canvas not expand , have defined max height , max width well. kindly me this. perhaps: private void canvas_mousewheel(object sender, mousewheeleventargs e) { double maxscale = 2.0; if (e.delta > 0) { st.scalex *= scalerate; ...

javascript - JSON stringify conversion of float to int -

i using node.js , built-in json object stringify json object. in object is { weight : 1.0 } however when stringify , write file output weight : 1. actually yours not issue , 1 == 1.0 == 1.00 in javascript , if have float value 1.55 stringify gives same 1.55 not 1 .. if want 1.0 written , change value string i mean enclose value in double quotes { weight : "1.0" }

android pay - What is the difference between Google Checkout & Wallet? -

i got email google informing me shuttering google checkout , should switch google wallet. confuses me because started google digital goods shopping cart 6 months ago under impression checkout dead. numerous news articles , wikipedia state checkout merged wallet in 2011. many google support pages use terms google checkout , google wallet interchangeably, , have google wallet logo @ top. my question simple, api using 1 of ones being discontinued. if so, there wallet (or other) alternative , way transition? when went this page , clicked "sign up", first step asked me go merchant center , enter credentials. of course have entered credentials there when signed google wallet checkout 6 months ago, furthermore page has giant red notice telling me service being discontinued. going insane or outrageously confusing? yes, api you linked retired. google not providing replacement product. transition consist of either swapping checkout non-google provider or integrat...

javascript - Counting a hrefs then subtracting -

$(function() { var getname = $('#fa_welcome').text(); var myname = getname.replace('welcome ',""); var = $('#recent_topics').find('a[href*="/u"]').filter(':contains("'+myname+'")').length; var b = $('#recent_topics').find('a[href*="/u"]').length; var c = a-b; if(c <= 1) { $('.topics_name').append('<div title="'+c+' new post" id="newtops">'+c+'</div>'); } }); just randomness give lengths of var , b a= 15 b= 25 i want subtract these 2 in var c 15-25 though -25 parsed? any suggestions try parseint like var = parseint($('#recent_topics').find('a[href*="/u"]').filter(':contains("'+myname+'")').length); var b = parseint($('#recent_topics').find('a[href*="/u"]').length);

unix - Java key release event from STDIN in terminal raw mode -

i'm trying write console game using java, , when hold down key, want move character constantly. this means need key press , key release events, because there delay when hold down key before starts typing same letter on , over. i've put terminal raw mode using stty, don't seem getting key release events. this answer seems indicate can indeed events stdin: https://stackoverflow.com/a/1598436/2404047 what receive when in raw mode single byte keys, in cases, arrow keys, multiple bytes. is there way can key press , release events through stdin, or console game not doable? this missunderstanding. cannot events console using pure java. possible solutions are: get events using native utility, redirect them file/pipe , read them java code file use jni/jna directly use library wraps jni , expose java api purpose. take on charva provides api need , more.

java - Writing data to file is erasing everything before it(Placing 00's) and changing the file size -

i have program writes out data- using logic fileoutputstream outpre = new fileoutputstream(getfile()); filechannel ch = outpre.getchannel(); ch.position(startwr); ch.write(bytebuffer.wrap(dsave)); outpre.close(); it writes out correct data correct location, problem before starting location write (startwr) gets replaced 00's, , file changed making point @ writing done, end of file. how can write data file without corrupting previous data , changing file size? you need instruct stream either append or overwrite contents of file... take @ fileoutpustream(file, boolean) more details updated after mucking around, found solution close working was... randomaccessfile raf = null; try { raf = new randomaccessfile(new file("c:/test.txt"), "rw"); raf.seek(3); raf.writebytes("bb"); } catch (ioexception exp) { exp.printstacktrace(); } { try { raf.close(); } catch (exception e) { } }

java - hadoop textinputformat read only one line per file -

i wrote simple map task hadoop 0.20.2, input dataset consists of 44 files, each 3-5mb. each line of file has format int,int . input format default textinputformat , mapper's work parse input text integers. after task run, statistics of hadoop framework shew number of input records map task 44. tried debug , found input records method map first line of each file. does know problem , can find solution? thank in advanced. edit 1 the input data generated different map-reduce task output format textoutputformat<nullwritable, intxint> . tostring() method of intxint should give string of int,int . edit 2 my mapper looks following static class mymapper extends mapreducebas implements mapper<longwritable, text, intwritable, intwritable> { public void map(longwritable key, text value, outputcollector<intwritable, intwritable> output, reporter reporter) { string[] s = value.tostring().sp...

android - Updating ListView to strikethough item on click -

i using cursoradapter listview , cursor getting data sqlite database. have function called renderlist() call every time update database new item list or if set checked value of row 1 (this add new item or strikethough item name). private void renderlist(){ string showwhere = show_checked ? null : dbhelper.c_checked + "= '0' "; try { db = dbhelper.getreadabledatabase(); cursor = db.query(dbhelper.table, null, showwhere, null, null, null, dbhelper.c_id + " desc"); grocerieslist = (listview)findviewbyid(r.id.listview1); adapter = new groceryadapter(this, cursor); adapter.newview(getapplicationcontext(), cursor, grocerieslist); grocerieslist.setadapter(adapter); grocerieslist.setonitemclicklistener(itemlistener); } catch (exception e) { log.d(tag, "renderlist error: ",e); } } this reset list, if click item way down listview reset listview t...

Python 030 == 24 is True, How is that correct? -

this question has answer here: not getting exact result in python values leading zero. please tell me going on there 6 answers i came across following problem: as expect: >>> [01,02,03] [1, 2, 3] adding superflous 0 's front of integer n results in mathematical equivalent of integer 0n , i.e n . however when do: >>> [030, 031, 031, 031, 030, 031, 031, 032, 031, 032] [24, 25, 25, 25, 24, 25, 25, 26, 25, 26] this notion proved completly incorrect. tried figure out why case trying check if 030 int: >>> type(030) <type 'int'> then thought perhaps, 030 being evaluted 24 , it's instead getting type(24) . thought looking see what's happening dis might help: >>> dis.dis('n=030') 0 jump_forward 12349 (to 12352) 3 delete_slice+1 4 <48> ...

how to implement concatenate mysql queries in zend framework Model -

hi new in zend framework. i want know possible use concatinate queries in zend model. example in core php $abc ="select * emp" if ($_post ['a'] != '') { $abc =$abc ." code=$_post ['a']"; } if ($_post ['b'] != '') { $abc =$abc ." name=$_post ['b']"; } $abc.=" order datetime;"; if possible want implement above code in zend model. yes can such in zend. here dummy idea you. first create object of model of emp table. $emp = new application_model_emp(); $select = $emp->select(); in model $_post not working need pass arguments controller. here using variable. if($a != '') { $select->where("code = ?", $a); } if($b != '') { $select->where("name = ?", $b); } $select->order("datetime"); $rows = $emp->fetchall($select);

android - Frame Animation doesnt run on second click -

it work on first tap, on second tap doesn't respond. waited 1 second execute 'generaterandom()' method can please? my code: paper.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { player.setimageresource(r.drawable.papel1); settimerimage4bot(); } }); public void settimerimage4bot() { try { handler = new handler(); frameanimation = (animationdrawable)bot.getdrawable(); frameanimation.setcallback(bot); frameanimation.setvisible(true, true); frameanimation.start(); log.i("baoanh", "start"); handler.postdelayed(new runnable(){ public void run(){ frameanimation.stop(); log.i("baoanh","stop"); generaterandom(); } },1000); }catch (exception e) { } }...

web parts - SharePoint-specific WebPart-class (instead of System.Web.UI) -

i started using sharepoint 2013. created project using built-in tools (office developer add-ons) sharepoint project. i porting sharepoint 2010 project few webpart more or less file-by-file. old webparts made use of webpart class found in microsoft.sharepoint.webpartpages.webpart . according msdn, should exist in sharepoint 2013. however, not present (i compiler errors). my question is: dll / using directive missing? i tried using using microsoft.sharepoint.webpartpages (and inheriting webpart ), still comes error ( using works fine though). i figured out. had set project sandboxed, disables features including specific webpart-type. re-creating project non-sandboxed project made work.

php - Get the text of multipart Gmail messages -

i trying fetch emails gmail php using imap. i'm getting emails problem of messages in multipart format, , remove multipart format. for example, 1 gmail message "hi, how you? fine", message has text this: "hi, how you? fine ------=_nextpart_000_000b_01ce5613.4a5d9f20 // multipart format content-type: text/html; // multipart format charset="us-ascii" // multipart format content-transfer-encoding: quoted-printable". // multipart format hi try this, $mailnumber = '11796'; $result = $mailbox->getmessagecontent($mailnumber); if ($result->texthtml) echo '<br>'.$result->texthtml; else echo '<br>'.$result->textplain;

javascript - TypeError on static method of mongoose model -

i'm using node.js along mongodb driver mongoose 3.6.1 . schema definition: models/user.js var mongoose = require('mongoose'), schema = mongoose.schema; var userschema = new schema({ ... }); module.exports = { model : mongoose.model('user', userschema) }; userschema.statics.dosomething = function () { console.log("i'm doing something"); } then in separate controller, do controllers/another.js var user = require("../models/user").model; function foo() { user.dosomething(); } and following error [typeerror: object function model(doc, fields, skipid) { if (!(this instanceof model)) return new model(doc, fields, skipid); model.call(this, doc, fields, skipid); } has no method 'dosomething'] however, if dump user object can see method there, expected. relevant part of dump confirming that ... schema: { statics: { dosomething: [function] } ... any idea o...

c++ - Person counting for a store using image processing techniques in OpenCV -

i new image processing , writing small application in need count number of people entering store. entry point fixed , there 4 camera feeds in same video same counting. can possibly use this? i have used running average , background subtraction till , has given me parts of image involve person. how use counting? using opencv c++. thanks! if have @ disposal multiple video stream can calibrate system create passive stereo framework. i've seen many work on topic one: http://www.dis.uniroma1.it/~iocchi/publications/iocchi-ie05.pdf you can take @ question: people counting using opencv

google app engine - How to use cursors for search in gae? -

when rtfm, can't understand how specify paginated searches using technique described in manual . here's code: def find_documents(query_string, limit, cursor): try: subject_desc = search.sortexpression( expression='date', direction=search.sortexpression.descending, default_value=datetime.now().date()) # sort 1000 matching results subject in descending order sort = search.sortoptions(expressions=[subject_desc], limit=1000) # set query options options = search.queryoptions( limit=limit, # number of results return cursor=cursor, sort_options=sort, #returned_fields=['author', 'subject', 'summary'], #snippeted_fields=['content'] ) query = search.query(query_string=query_string, options=options) index = search.index(name=_index_name) # execute query return in...

Adwords - KEYWORD_PERFORMANCE_REPORT Data with test key -

i have got test key using adwords api's , ran through "getreportfields" returned empty data averagecpc(money) := [] averagecpm(money) := [] averageposition(double) := [] bottomposition(int) := [] campaignid(long) := [] campaignname(string) := [] i have campaigns in project , hoping meaningful results (atleast campaignid , campaignname) ; test account limited jst showing fields? additionally; copy these results local object; entities "significancedata" defined , type they? thanks, -dev it's called impressionsignificance which the significancedata

mysql - select the 2nd blog from each category -

how can 2nd post each category in php mysql? if have table following: post_id | cate_id -------------------- 1 | 2 2 | 4 3 | 2 4 | 1 5 | 1 6 | 3 7 | 4 8 | 3 9 | 5 10 | 5 expecting result following: post_id | cate_id -------------------- 5 | 1 3 | 2 8 | 3 7 | 4 10 | 5 thanks. select t.cate_id,min(t.post_id) (select cate_id, min(post_id) post_id foo group 1) firsts inner join foo t on t.cate_id=firsts.cate_id , t.post_id > firsts.post_id group 1; given: mysql> select cate_id, group_concat(post_id order post_id) foo group 1; +---------+----------------------------------------+ | cate_id | group_concat(post_id order post_id) | +---------+----------------------------------------+ | 0 | 0,1,3,4,7 | | 1 | 0,1,2,4,6,8,9 ...

mongodb - MongoTemplate instance is not created inside spring -

i want try spring integration mongodb, purpose did following things. not working how mongotemplate instance not created , throws java.lang.nullpointerexception. here application-context.xml <?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- activate annotation configured components --> <context:annotation-config/> <!-- scan components annotations within configured package --> <context:component-scan base-package="com.jeroen...

c# - WebMethod with optional parameter doesn't work in client side -

this question has answer here: can have optional parameter asp.net soap web service 5 answers how pass optional parameters web method? 2 answers i write webmethod optional parameter. [webmethod] public void emailsend(string from, string to, string cc = null, string bcc = null, string replytolist = null, string subject = null, string body = null, bool isbodyhtml = false , string[] attachmentnames = null, byte[][] attachmentcontents = null) { ..... } i call method in client side application emailservicemanagement.emailservice es = new emailservicemanagement.emailservice(); es.emailsend(from, to,null,null,null,subject,body,true,attname,att); //this works but es.emailsend(from,to); // isn't working. according c# optional parameter syntax must work. ...

Horizontal Scrolling in HTML CSS -

Image
i have list of content want display in bootstrap grid of span9 , has scroll across in x axis. below can find snap shot of design. but not able work with overflow-x: scroll; overflow-y: hidden; link: http://play.mink7.com/mybooks/template.html the content not overflowing on x axis because goes new line. you'd need force content stay on 1 line with: .featured-category ul { white-space: nowrap; // add } .featured-category ul li { display: inline-block; // add /*float: left;*/ // remove }

javascript - AngularJS: How to set a variable inside of a template? -

how can avoid having {{f = ...}} statement in third line print out content of forecast[day.iso] ? i want avoid using forecast[day.iso].temperature , on every iteration. <div ng-repeat="day in forecast_days"> {{$index}} - {{day.iso}} - {{day.name}} {{f = forecast[day.iso]}} temperature: {{f.temperature}}<br> humidity: {{f.humidity}}<br> ... </div> use nginit : http://docs.angularjs.org/api/ng.directive:nginit <div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]"> {{$index}} - {{day.iso}} - {{day.name}} temperature: {{f.temperature}}<br> humidity: {{f.humidity}}<br> ... </div> example: http://jsfiddle.net/coma/uv4qf/

pdf - How do I make text field to be hidden? -

i'd create text field itextsharp not visible. here's code i'm using create textfield: textfield field = new itextsharp.text.pdf.textfield(writer, new itextsharp.text.rectangle(x, y - h, x + w, y), name); field.backgroundcolor = new basecolor(bgcolor[0], bgcolor[1], bgcolor[2]); field.bordercolor = new basecolor(bordercolor[0], bordercolor[1], bordercolor[2]); field.borderwidth = border; field.borderstyle = pdfborderdictionary.style_solid; field.text = text; writer.addannotation(field.gettextfield()); in java, textfield class has method named setvisibility() inherited parent, basefield class. possible values are: basefield.visible , basefield.hidden , basefield.visible_but_does_not_print , and basefield.hidden_but_printable . as you're using itextsharp, should setvisibility() method or visibility property. using render mode suggested person in answer question applies content written content stream, xobject or appearance. asking hide field, ...

Extend java.util.calendar class -

i want extend java.util.calendar class in order add functionality: import java.util.calendar; abstract class extendedcalendar extends calendar { public static extendedcalendar getinstance() { calendar c = calendar.getinstance(); return (extendedcalendar)c; } } i exception, because calendar.getinstance returns gregoriancalendar: java.lang.classcastexception: java.util.gregoriancalendar cannot cast extendedcalendar but how possible cast of gregoriancalendar calendar working? calendar calendar = (calendar)c; how can solve problem? calendar.getinstance() static factory method event not allow customizations or injections. returns instance of concrete calendar. in cases gregoriancalendar . can buddhistcalendar or japaneseimperialcalendar depending on locale. if want create instance of calendar direct call of constructor: new extendedcalendar() . btw imho not have extend gregoriancalendar . extending functionality not limited extendi...

sql server 2008 - T-SQL - Best way to select rows that corresponds to a category and default category if the category is not configured -

i have table of configuration data can associated recipe (category more generic). like this: recipes: id name 1 default 2 3 b configuration data id equipment parentid recipeid 1 3420 1 1 2 3420 1 2 3 3421 1 1 4 3421 1 2 5 3422 1 1 i want know how select configuration data recipe "a", , fall on "default" values if recipe not configured configuration data row. this: id equipment parentid recipeid 2 3420 1 2 4 3421 1 2 5 3422 1 1 i found unsure approach: select * configurationdata recipeid=2 , parentid=1 union select * configurationdata recipeid=1 , parentid=1 , equipment not in (select equipment configurationdata recipeid=2 , parentid=1) something using cte? /** * first declare id search */ declare @recipeid int set @recipeid = 2 -- change recipe want select /** * actual query */ cte ( select r.id recipe, c.id, ...

java - Spring Validator does not support command class -

i think issue pretty common, reason cannot manage fix this. this error getting: org.springframework.beans.factory.beancreationexception: error creating bean name 'reversecontroller' defined in servletcontext resource [/web-inf/app-servlet.xml]: initialization of bean failed; nested exception java.lang.illegalargumentexception: validator [formvalidator@6b3ded0d] not support command class [reversestring] this supports method in formvalidator class: public boolean supports(class clazz) { return reversecontroller.class.isassignablefrom(clazz); } this bean definition on app-servlet.xml: <bean id="reversecontroller" class="reversecontroller"> <property name="commandname"><value>reversestring</value></property> <property name="commandclass"><value>reversestring</value></property> <property name="formview"><value>reverse</value...

Allow only 2 decimal points entry to a textbox using javascript or jquery? -

i called class called test textbox. when entered first value e.g. first value 4. , output coming 4.00 . want restrict entry 2 decimal places. $(".test").keyup(function (event) { debugger; this.value = parsefloat(this.value).tofixed(2); }); this small change code may suffice: this.value = this.value.replace (/(\.\d\d)\d+|([\d.]*)[^\d.]/, '$1$2'); essentially replace decimal point followed number of digits decimal point , first 2 digits only. or if non digit entered removes it.

iphone - Adding NSArray items to UITableViewCell content view -

in app adding 3 uilabel each table view cell in following way. - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { static nsstring *cellidentifier = @"showmorecell"; uitableviewcell *cell = [tableview dequeuereusablecellwithidentifier:cellidentifier]; cell = [self getcellcontentview:cellidentifier]; return cell; } - (uitableviewcell *)getcellcontentview:(nsstring *)cellidentifier { uitableviewcell *cell = [[[uitableviewcell alloc] initwithstyle:uitableviewcellstylevalue1 reuseidentifier:cellidentifier] autorelease]; cell.backgroundcolor=[uicolor clearcolor]; for(int j = 0; j < 3; j++) [cell insertsubview:[items objectatindex:j] atindex:j]; cell.selectionstyle = uitableviewcellselectionstylenone; return cell; } here items nsmutablearray , has got elements of uilabel. trying add 3 labels in each cell . displaying 3 labels in last row. am doing wrong here ? thanks...

web scraping - Scrape website with Ruby based on embedded CSS styles -

in past, have used nokogiri scrape websites using simple ruby script. current project, need scrape website uses inline css. can imagine, old website. what possibilities have target specific elements on page based on inline css of elements? seems not possible nokogiri or have overlooked something? update: example can found here . need main content without footnotes. latter have smaller font size , grouped below each section. i'm going teach how fish. instead of trying find want, it's lot easier find don't want , remove it. start code: require 'nokogiri' require 'open-uri' url = 'http://www.eximsystems.com/laverdad/antiguo/gn/genesis.htm' footnote_accessors = [ 'span[style*="font-size: 8.0pt"]', 'span[style*="font-size:8.0pt"]', 'span[style*="font-size: 7.5pt"]', 'span[style*="font-size:7.5pt"]', 'font[size="1"]' ].join(','...

linq - to count the number of occurrence of an element with specific attribute and specific value in xml -

i using linq xml along xpath number of occurrence of element specific attribute , specific value....here xml file... in have extract number of occurrence of element p attribute "hsdpacodecapacity" , value 5....this long file dint post completely......help pls ......i want use linq xml program " <managedobject class="wbts" version="rn6.0_2.0" distname="plmn-plmn/rnc-3003/wbts-2743" id="214999014"> <defaults name="system"/> <p name="dlcecapacity">0</p> <p name="hsdpacodecapacity">5</p> <p name="ulcecapacity">0</p> <p name="bburruflag">0</p> <p name="name">whalanoo</p> <p name="nbrrepeater">0</p> <p name="numfa">1</p> <p name="type">3</p> <p name="btsadditionalinfo">150.78892:-33.76300</p...

email - Postfix Perl mailing via PostDrop -

i'm trying inject email directly postfix queue using perl module mail::postfix::postdrop ultilises postfix method of allowing messages written directly postdrop directory. there small amount of documentation has enabled me send message successfully, however, confused how able set subject , message body. attempt set variable $message little nothing. i must admit, i'm apprentice perl @ best, appreciate help. #code sends email: use mail::postfix::postdrop 'inject'; $message = 'test message'; inject $message, sender => 'postmaster@mydomain.com', recipients => [ qw(email@someotherdomain.com) ]; some relavant documentation: http://annocpan.org/~pmakholm/mail-postfix-postdrop-0.3/lib/mail/postfix/postdrop.pm in email messages "headers" section separated "body" section empty line. change $message to: $message = "subject: subject!\n\nand message"; and should...

php - Find the nearest postcodes to given postcode using ordance survey easting and northing system -

i have database table of uk postcodes has 4 fields: postcode, east, north, pqi example values: st1 6bq, 388605, 349057,10 the primary key postcodes , east , north both int(11)` fields. does have efficient mysql query return nearest 5 postcodes given post? i have seen many examples using long , lat , not northing , easting . convert northings/eastings lat/long, remembering os grid based on osgb36 rather wgs84. i use following class: <?php namespace osgb36; use \geodetic\datum; class converter { private $_osref; private $_fromdatum; private $_todatum; public function __construct() { $this->_osref = new osref(); $this->_fromdatum = new datum(datum::osgb36); $this->_todatum = new datum(datum::wgs84); } /** * converts easting/northing lat/long * * @param integer $eastings * @param integer $northings * @return \geodetic\latlong */ public function calculatelat...

php - Joining 2 Tables and show the same column repeatedly based on its associative ID -

hi not sure how put in brief sentences, have db table following user table user_id username and on... item item_id item_name item_equipped equipped_id head (fk item_id) hand (fk item_id) user_id (fk user_id in user table) i generate query display following format user_id | head | head_item_name | hand | hand_item_name | ... so far able this: select user.user_id, user.username, equipments.head, equipments.head_acc, equipments.hand, equipments.acc, equipments.body gw_member_equipped equipments left join gw_member user on user.memberid = equipments.member_id which (i have brutally honest) doesn't much. i tried perform inner join between item , item_equipped unable individual name each item (based on item id) you need join item table 2 times item_equipped table. you can use below query desired output column shown in question.. select user.user_id, item_equipped.head, item_heads.item_id head_item_i...

php - How to get stock for configured item in cart? -

with simple product can this: $quote = mage::getsingleton('checkout/session')->getquote(); $item = $quote->getitembyid($params['item']); // $params['item'] contains item id $product = $item->getproduct(); $stockqty = (int)mage::getmodel('cataloginventory/stock_item')->loadbyproduct($product)->getqty(); however, if item configured product, tries stock of parent configurable product, in cases has inventory of zero. how can stock quantity of configured product, preferably without looping through configurable parent's child products? you can set variable determines stock status depending on stock status of children of configurable product: $instock = true; $quote = mage::getsingleton('checkout/session')->getquote(); $cart = mage::getmodel('checkout/cart')->getquote(); $item = $quote->getitembyid($params['item']); // $params['item'] contains item id $_product = $item->getprod...

c# - Save user's login method in cookie? -

i have .net mvc3 website multiple authentication options: facebook google websites own when user browses site asked his/her choice of authentication , once have either registered or logged in through third party authenticated on site. my questions are: is possible save user's authentication choice in cookie, when revisit site logged in using previous authentication choice (google , facebook automatically if logged in)? if possible whats best practice creating secure cookie in mvc3? cheers i think help this or this it can implemented in server side too.

xaml - why this style is not working in wpf -

i have style button follow: <style targettype="button" x:key="blackbutton"> <setter property="background" value="black"/> <setter property="template"> <setter.value> <controltemplate targettype="button"> <controltemplate.triggers> <trigger property="ismouseover" value="true"> <setter property="background" value="red" /> </trigger> </controltemplate.triggers> <contentpresenter /> </controltemplate> </setter.value> </setter> </style> and button on defined follow: <button canvas.left="19" canvas.top="520" height="34" width="107" style="{staticresource blackbutton}" />...

apache - how to create session in php with mongodb -

in node.js create mongodb session this. app.configure(function() { app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.bodyparser()); app.use(express.cookieparser()); app.use(express.session({ secret: 'my secret', store: new mongostore({ db: 'my session db', host: 'localhost', port:88888 }) })); app.use(everyauth.middleware()); app.use(express.methodoverride()); app.use(app.router); }); how create session mongodb in php.i new 1 php..i want create session mongodb in php(webserver: apache),so let me know how create you must use session handler accomplish this. don't answer these sort of questions lack research of kind but, 1 time, here small, extremely simple, self contained edition have: class session{ public $db; /** * decides lifetime (in seconds) of session * * @access private * @var int */ ...