Posts

Showing posts from May, 2013

asp.net - a potentially dangerous request.form with Freetextbox -

i using control called freetextbox , when click on update button getting error "a potentially dangerous request.form value detected client (ftxtcontent="tyretyeryteyterty...").". , don't want disable page level property i.e validaterequest false. there idea deal error. please me asap. if still needs this, setting validaterequest false work before .net framework 4.0. in 4.0, requests validated default. disable functionality, add following element of web.config: <httpruntime requestvalidationmode="2.0" /> that should fix it. robrisner

java - Object pooling with .wait and .notify -

i'm trying create class in java pool objects. class starts creating minimum amount of objects required, when requests start kick in, every thread checks if there object available, if can create because maximum has not been reached yet, or if otherwise has wait one. the idea threads needs synchronize get/create engine, can process in parallel ( processwithengine method). processing take couple of minutes, , apparently it's working want. the problem is, sometimes when .notify() has been called , thread released .wait() , queue has 0 items, , should impossible because before .notify() , item added. what problem? the code this: queue _queue = new queue(); int _poolmax = 4; int _poolmin = 1; int _poolcurrent =0; public void process(object[] parameters) throws exception { engine engine = null; synchronized(_queue) { if(_queue.isempty() && _poolcurrent >= _poolmax) { _queue.wait(); // here : _queue....

iphone - How to give UIPopOver kind of functionality with simple UIVIew -

i want make uiview should displayed above slider thumb , should show value of slider. don't want use popover it's not looking artwork have. please share views on this. don't have care apple policies application not go through apple's code review. internal survey purpose. thanks. find demo here, using uilabel , animation(though class name popover..but not using popover--), can go through source code, it's simple, hope can help. original link here: uilabel on slider - (bool)application:(uiapplication *)application didfinishlaunchingwithoptions:(nsdictionary *)launchoptions { mslider = [[uislider alloc]initwithframe:cgrectmake(10, 100, 300, 50)]; mslider.minimumvalue = 0; mslider.maximumvalue = 1000; mslider.value = 0; [mslider addtarget:self action:@selector(updatevalue:) forcontrolevents:uicontroleventvaluechanged]; popview = [[uilabel alloc]initwithframe:cgrectmake(mslider.frame.origin.x, mslider.frame.origin.y-20, 70, 20)]; [popv...

iphone - MKOverlay order problems -

i have mkmapview 2 overlays: mkpolyline , subclass of mkoverlay defined overlay cllocationcoordinate2d of 0,0 , bounding rect of mkmaprectworld. i'm trying add mkpolyline overlay , custom overlay afterwards, in response user action. custom overlay needs go under mkpolyline overlay. i add custom overlay with: [map insertoverlay:customoverlay atindex:0]; however doesn't work. cusomoverlay added on top of existing one. overlay array mkmapview claims ordered correctly though. the way i've been able enforce correct order remove mkpolyline, add custom overlay , put mkpolyline in. am missing obvious? edit code snippets: the custom overlay class: @interface transparencyoverlay : nsobject <mkoverlay> {} @end @implementation transparencyoverlay - (cllocationcoordinate2d)coordinate { return cllocationcoordinate2dmake(0, 0); } - (mkmaprect)boundingmaprect { return mkmaprectworld; } @end the adding of custom overlay: - (void)onuseraction { ...

c# - Creating Scrolling Items in Silverlight -

i have silverlight application needs scroll data (like stock information) across footer of application. in effort this, created following: <usercontrol.resources> <storyboard x:name="myliststoryboard" begintime="0:0:0" completed="myliststoryboard_completed"> <doubleanimation x:name="mylistanimation" duration="0:0:30" storyboard.targetproperty="(uielement.rendertransform).(compositetransform.translatex)" storyboard.targetname="myitemscontrol" /> </storyboard> </usercontrol.resources> <border x:name="infolistborder" grid.row="1" height="40" horizontalalignment="stretch" borderthickness="1,1,0,0" background="silver"> <grid> <itemscontrol x:name="myitemscontrol" horizontalalignment="right" scrollviewer.horizontalscrollbarvisibility="disabled" scrollviewer.ve...

python - Time-varying data: list of tuples vs 2D array? -

my example code in python i'm asking general principle. if have set of data in time-value pairs, should store these 2d array or list of tuples? instance, if have data: v=[1,4,4,4,23,4] t=[1,2,3,4,5,6] is better store this: data=[v,t] or list of tuples: data=[(1,1),(4,2)(4,3)...] is there "standard" way of doing this? the aggregate array container best choice. assuming time points not regularly spaced (and therefore need keep track of rather use indexing), allows take slices of entire data set like: import numpy np v=[1,4,4,4,23,4] t=[1,2,3,4,5,6] data = np.array([v,t]) then slice subset of data easily: data[:,2:4] #array([[4, 4],[3, 4]]) ii = [1,2,5] # fancy indexing data[:,ii] # array([[4, 4, 4], # [2, 3, 6]])

javascript - RGB to Hex and Hex to RGB -

how convert colors in rgb format hex format , vice versa? for example, convert '#0080c0' (0, 128, 192) . the following rgb hex conversion , add required 0 padding: function componenttohex(c) { var hex = c.tostring(16); return hex.length == 1 ? "0" + hex : hex; } function rgbtohex(r, g, b) { return "#" + componenttohex(r) + componenttohex(g) + componenttohex(b); } alert( rgbtohex(0, 51, 255) ); // #0033ff converting other way: function hextorgb(hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseint(result[1], 16), g: parseint(result[2], 16), b: parseint(result[3], 16) } : null; } alert( hextorgb("#0033ff").g ); // "51"; finally, alternative version of rgbtohex() , discussed in @casablanca's answer , suggested in comments @cwolves: function rgbtohex(r, g, b) { return "#" + ((1 << 24) + (r ...

asp.net - Is it possible to pass my model which I used in a view back to my controller in MVC3? -

in questionmodel have: private list<questionmodel> _questionlist = new list<questionmodel>(); which use in view: //getquestionlist returns _questionlist foreach (var item in model.getquestionlist()){...} i want acces model in controller when submit form in view. have tried add model parameter in de controller function like: public actionresult savedata(questionmodel model){} but nothing in question is, possible , how it? you need bind type of model , use for loop not for each loop in view.

ios4 - MonoTouch: NSData memory conservation -

does know if it's more memory-efficient use nsdata.fromfile or fromstream vs filling nsdata.fromarray? specific case i'm sending large file via email (mfmailcomposeviewcontroller.addattachmentdata). right i'm filling nsdata bytes want send, hoping if use nsdata.fromfile or fromstream, wouldn't ever keep file data in memory @ once. i think out of luck here. if pass data on addattachmentdata() , mail composer copy bytes , hold them in memory (you should see instruments). best can dispose() nsdata passed on release memory fast possible.

activerecord - Use a find hash in Rails 3.x? -

is there non-deprectated option in rails 3 can pass data structure in execute query, rather use method chaining approach ? consider hash representing set of critieria limiting set of records (say, documents).. { :conditions => { :account_id => 2 }, :limit => 5, # page size :offset => 5, # (page-1) * page_size :sort => 'id desc' } this may come url such as: /documents.js?page_size=5&page=2&sidx=id&sord=desc&filter[account_id]=2 and want avoid issues of order-importance in translation of hash sequential series of calls of methods: # 'right', or better ? document.offset(5).where(:account_id => 2).limit(5) document.where(:account_id => 2).limit(5).offset(5) i'm concerned programmatic transformation of set of query criteria inferred http parameters or json objects may more complicated if have walk hash , created chained method calls. you can use classic find method: document.a...

Shorthand for just $(document) in jQuery -

i noticed in jquery docs of 1.4, calling $() no args returns empty set rather $(document). http://api.jquery.com/jquery/#returning-empty-set so, there no other shorthand $(document)? i ask because can't decide uglier if i'm trying select element id have in variable: $("#" + myid) or $(document).find(myid). thanks. you can make own alias: $d = $(document);

database - Printing the names of all the people greater than age 18? -

this pretty question posed me recently. suppose have hypothetical (insert favorite data storage tool here) database consists of names, ages , address of people residing on planet. task print out names of people age greater 18 within html table. how go doing that? lets hypothetically population growing @ rate of 1200/per second , database updated accordingly(don't ask how). strategy print names of these people , addresses on html table? storing ages in db tables sounds recipe trouble me - impossible maintain. better off storing birth dates , building index on column/attribute. you have initial dump of table display. calculate date 18 years ago (let's d0 ) , use query person born earlier that. use db triggers receive notifications deaths, can remove them table immediately. since people older (unfortunately?), can use ranged queries new additions (i.e. people become 18 years old since yo last queried table). e.g. if want update display next day, issue query peopl...

python - Determining if an input is a number -

how find out if user's input number? input = raw_input() if input = "number": else: what "number" in case? depends on mean "number". if floating point number fine, can use s = raw_input() try: x = float(s) except valueerror: # no number else: # number

XSLT grouping every 4 adjacent elements -

i have xml below. source xml: <?xml version="1.0" encoding="windows-1252"?> <xml> <attributes> <attribute> <name>collection</name> <value /> </attribute> <attribute> <name>a</name> <value>testing</value> </attribute> <attribute> <name>b</name> <value>blank</value> </attribute> <attribute> <name>c</name> <value>11</value> </attribute> <attribute> <name>d</name> <value>na</value> </attribute> <attribute> <name>a</name> <value>testing1</value> </attribute> <attribute> <name>b</name> <value>red</value> </attribute> <attribute> <name>c</nam...

Detecting JavaScript errors -

i trying figure out why page not working correctly in internet explorer 7. i javascript error says error on line 1958 char 7 my html code 534 lines of javascript code externally linked. how go finding error? does error put of external files in file makes number of lines more html code? would need figure out error in javascript code? you should use internet explorer developer toolbar . extremely useful debugging js in ie. i've heard things web development helper. (it supports ie6!) if have visual studio, enabling script debugging in advanced options. may yield better debugging.

wolfram mathematica - Solving system of quadratic equations -

can see way solve system below? tried reduce evaluation takes while i'm not sure work terms = {{g^2, g h, h^2, -o^2, -o p, -p^2}, {g^2, g k, k^2, -o^2, -o q, -q^2}, {g^2, g m, m^2, -o^2, -o r, -r^2}, {g^2, g n, n^2, -o^2, -o s, -s^2}, {h^2, h k, k^2, -p^2, -p q, -q^2}, {h^2, h m, m^2, -p^2, -p r, -r^2}, {h^2, h n, n^2, -p^2, -p s, -s^2}, {k^2, k m, m^2, -q^2, -q r, -r^2}, {k^2, k n, n^2, -q^2, -q s, -s^2}, {m^2, m n, n^2, -r^2, -r s, -s^2}}; vars = variables@flatten@terms; coefs = array[c, dimensions[terms]]; eqs = mapthread[#1.#2 == 0 &, {terms, coefs}]; reduce[eqs, vars, reals] you can approach problem optimization perspective, building sum of squares of r.h.s. of equations. define matrix: mat[{g_, h_, k_, m_, n_, o_, p_, q_, r_, s_}] := {{g^2, g h, h^2, -o^2, -o p, -p^2}, {g^2, g k, k^2, -o^2, -o q, -q^2}, {g^2, g m, m^2, -o^2, -o r, -r^2}, {g^2, g n, n^2, -o^2, -o s, -s^2}, {h^2, h k, k^2, -p^2, -p q, -q^2}, {...

iphone - EasyAPNS: Has anybody tried it with large amounts of notifications? -

i implemented easyapns in app , server , have database 2000+ registered devices. today tried send notifications of these devices , script timed out. checked code (should've done earlier, know) , discovered opens connection for each message . basically thing never work , ip banned, right? how's possible problem not mentioned anywhere in google group ? apparently nobody tried library lot of notifications -- can real? or missing something? i ended rewriting lot of code sends messages apns. instead of looping through each message opening , closing connection every time, fetch n messages (probably limit 100) database every minute , send them in 1 shot. until messages table empty (i used cron job this). had more work because needed multiple application support. i'm not sure easyapns guys thinking when wrote library. honestly, didn't @ -- have been better if had written apns code scratch on own. should need in modifying library, comment post.

c# - What is difference between Task and Thread? -

today digging tpl , found new class task.now wanted know diffrence between task , thread,and 1 better? what diffrence between task , thread? suppose running book delivery company. have 4 cars , 4 drivers. car thread, driver processor, , book delivery task. problem face how efficiently schedule drivers , cars tasks done possible. where things weird when there more cars (threads) drivers (processors). happens halfway through trip driver parks 1 car (suspends thread) , gets different car (switches context), drives 1 around while performing tasks, , comes first car. not efficient 1 driver staying in 1 car. the idea of task-based parallism break work small tasks can produce results in future , , efficiently allocate many threads there processors don't waste time context switching. in practice, not work out nicely, that's idea. which 1 better, task or thread? the question cannot answered because doesn't make sense. better, book deliver customer,...

ruby on rails - Using IP restricting API's on Heroku -

a third party api using restricts access based on ip address. since there no dedicated ip heroku app, optimal solution? get server can control ip on (like ec2 instance) , route requests through that. or, talk api provider modifying access controls.

console - How can I detect elapsed time in Pascal? -

i'm trying create simple game in pascal. uses console. goal in game collect many 'apples' can in 60 seconds. game structure simple infinite loop. each iteration, can make 1 move. , here's problem — before make move ( readkey ), time can pass as wants. example, user can press key after 10 seconds! there way count time? need program know when user plays (before , after key pressed), don't know how prevent user "cheating". here's simple structure of game: begin repeat {* ... *} case readkey of {* ... *} end; {* ... *} until false; end. full code: http://non.dagrevis.lv/junk/pascal/parad0x/parad0x.pas . as far know there 2 possible solutions: gettime (from dos), delay (from crt). ...but don't know how use them loop. check this link . there might useful information you. , here is same you're asking for. , here's you're looking (same code below). var hours: w...

java - Ant Javac and Commandline Javac give different results -

i have class imports servlet libraries. when compile command-line fine. when use ant compile task compile it, gives errors can't find servlet libraries in path. is known/common occurrence? here ant target: <target name="compile" depends="prepare" description="compile source" > <echo>=== compile === srcdir: ${src}/com/udfr/src/java </echo> <!-- compile java code ${src} ${build} --> <javac srcdir="${src}/com/udfr/src/java" destdir="${dist}/web-inf/classes"/> </target> it's common occurrence if don't specify servlet libraries in classpath javac task... suspect that's problem. if post task fails , command line works, we'll able more.

sql - Optimize complex MySQL selects for reporting -

i'm building application in which, a) each librarian can create campaign b) actions carried out part of campaign tracked in campaign_actions , actions being page loads in order report on number of actions made in each campaign, i wrote sql query (for mysql) following database structure, intention of tracking number of actions undertaken librarian each campaign: librarians id | status campaigns id | librarian_id campaign_actions id | campaign_id | name the problems having are: a) have specify fields want count in correlated subselects b) query quite expensive result my question is, since there multiple actions campaign, how can count number of actions per campaign in more efficient manner? less complex queries amount returning result set so: librarians.id | librarians.status | campaign_actions.name 1 3 pagex 1 3 pagey 1 3 ...

email - PHP Mail Headers -

essentially i'm trying attach file email i'm sending out. simple enough, right? reason or not following code (presumably because of headers). can help? thanks in advance!! $subject = "file ".date("ymd"); $message = "none"; $filename = "test.csv"; $content = chunk_split(base64_encode(file_get_contents($filename))); $uid = md5(uniqid(time())); $name = basename($file); $header .= "mime-version: 1.0\r\n"; $header .= "from: noreply@x.com\r\n"; $header .= "reply-to: noreply@x.com\r\n"; $header .= "content-type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n"; $header .= "this multi-part message in mime format.\r\n"; $header .= "--".$uid."\r\n"; $header .= "content-type:text/plain; charset=iso-8859-1\r\n"; $header .= "content-transfer-encoding: 7bit\r\n\r\n"; $header .= $message."\r\n"; $header .= "--".$ui...

asp.net MVC3 auto generate meta keywords and description based on page content -

i'm working on mvc3 web application using razor view engine. i'm looking solution generate meta keywords , description automatically on pages. i've found this solution here on stackoverflow, idea looking good. since i'm planning post blogs etc... on website want meta keywords , description auto generated based on content of page. soo far i've got following things in mind. let's current html looks below; <html> <head> </head> <body> <header></header> <div id="container"> <div id="sidebar"></div> <div id="pageheader"></div> <div id="content"> <!--this part contains dynamic content--> </div> <div class="clear"></div> </div> <footer>...

How can a server communiate with two clients at once (JavaScript, HTML, PHP)? -

i got assignment , use www technology html, javascript, php etc. i'm sorry haven't studied of these technologies. therefore took few tutorials , skimmed through them searching answers. i found solutions many problems 1 problem yet unsolved. this: i want 2 clients communicate through server assignment. 1 send message, server processes , forwards next. none of php tutorials showed me anyway of doing this. of them talked of communication between 1 client server. please help. show me way this. thanks. currently, without reverting cutting-edge (and possibly hacky/unreliable) techniques, php server cannot initiate communications page you've loaded web browser. result of way http protocol works. one way solve polling on "receiving" end data. publish-subscribe pattern. one way be: one client sends data server using http request (xhr aka ajax) specifying target data (the other client). the server stores data in persistent storage (local file, d...

c# - How to run Selenium tests with CI (Continuous Integration)? -

i'm using selenium automated testing websites. have around 100 test cases , want run them every day making test suite automatically. had written test cases in selenium 1 (selenium rc) , not easy migrate selenium 2 (webdriver). there way or application out there can load , execute selenium 1 scripts automatically? thanks help. you don't need convert tests selenium 2 able run them. selenium 2 contains code selenium 1 , selenium merged webdriver. existing scripts should run fine latest version of selenium. from questions above assuming have recorded scripts in selenium ide , want run them using selenium server, if have @ following: run selenese directly within server using -htmlsuite can run selenese html files directly within selenium server passing html file server’s command line. instance: java -jar selenium-server.jar -htmlsuite "*firefox" "http://www.google.com" "c:\absolute\path\to\my\htmlsuite.html" "c:\absolute\path...

sql server - UPDATE Using Self Join and Aggregates -

i'm trying update table using self join , aggregates. for example, table has following columns: store, item, price, lowprice, lowprice store i need populate lowprice , lowprice store . the lowprice be: select item,min(price) group item the lowprice store store min(price) each item. i'd love able take step further well. 2 stores offer item @ same lowprice . value lowprice store 'store a/store b' part less important. i'm using sql server. i agree @jnk comment better off using view . sql server 2005+ can try: create view lowprices select a.store, a.item, a.price, a.low_price, min(b.store) low_price_store ( select *, min(price) over(partition item) low_price yourtable) join yourtable b on a.low_price = b.price group a.store, a.item, a.price, a.low_price if still want update , try: with cte ( select a.store, a.item, a.price, a.low_price, min(b.store) low_price_store ( select *, min(price) over(partition item) ...

What to learn to do Java web services? -

the last time did java web development in 2004 java servlets , jsp. never got anywhere ejbs. recall experience in developing web services\dynamic web sites these slow (in terms of development time) , painful (in terms of easy deployment). what businesses use develop java based websites these days? use axis or other framework web services? use jsp or other technology front end? the current standards use jax-ws (for soap web services) , jax-rs (for restful web services). these standards have multiple implementations. jax-ws has metro, cxf, etc. jax-rs has jersey, resteasy, etc.

iphone - 2-dimensional glRotatef() -

(iphone) i'm trying make user can rotate object dragging finger on screen. dragging left or right should rotate around y-axis, , dragging or down should rotate around x-axis. here's original code: glrotatef( yamt, 0, 1, 0 ); glrotatef( xamt, 1, 0, 0 ); the rotation crazy , seems go in random directions. i'm pretty sure has second statement being dependent on first statement, i've tried negate fancy math , still couldn't right. well partially figured out, have new problem (how sum 2 rotations?). my solution: let's wanted rotate cube left 90 down 90. try this: glrotatef( 90, 0, 1, 0 ); glrotatef( 90, 1, 0, 0 ); it doesn't work. second function behaves strangely because first function has swapped x , z axes. try this: glrotatef( 90, 0, 1, 0 ); glrotatef( 90, 0, 0, 1 ); now have desired result, if change amount of y rotation in first function 180 or 45 or whatever, fails again. desired rotation vector dependent of amount of y rotation first...

c# - I need OCR for WPF -

i need ocr component inkcanvas control in wpf can recognize characters , replaced hand writing 1 1 ocr ? microsoft has 2 dll analyzing hand writing in inkcanvas "iawinfx.dll" , "microsoft.ink.analysis" , there open source example http://khason.net/blog/ink-recognition-in-wpf/

asp.net mvc 3 - Server-side Validation using MVC 3 -

i'm building asp.net mvc3 app. have 2 views; list item contains grid details view consists of drop down list (combobox) i have requirement alert user @ details view when try select item selected in list view. in other words, grid should contain unique items what best way implement server-side business logic validation? model: public class allocatedresource { public virtual project project { get; set; } public virtual datetime startdate { get; set; } public virtual datetime enddate { get; set; } } list view: @(html.telerik().grid(model.allocatedresources) .name("gridallocatedproject") .datakeys(keys =>{keys.add(p => p.id);}) .columns(columns => { columns.bound(p => p.id).visible(false); columns.bound(p => p.project.name); columns.bound(p => p.project.projectmanager).title("project manager"); columns.bound(p => p.startdate).width(80).format("{0:d}...

c++ - getline with delimiter storing an empty character -

i trying input delimited text file getline when debug it shows me there empty character @ beginning of variable. this happening tid variable happens first on each line. when debug shows character array: [0] = '' [1] = '2' [2] = '3' [3] = '4' here relevant code: ifstream infile("books.txt"); if (!infile){ cout << "file couldn't opened." << endl; return; } while(!infile.eof()){ string tid, ttitle, tauthor, tpublisher, tyear, tischecked; getline(infile,tid, ';'); getline(infile,ttitle, ';'); getline(infile,tauthor, ';'); getline(infile,tpublisher, ';'); getline(infile,tyear, ';'); getline(infile,tischecked, ';'); library.addbook(tid, ttitle, tauthor, tpublisher, tyear, (tischecked == "0") ? false : true); } here few lines of book.txt: 123;c++ primer plus; steven prata; sams; 1998;0; 234;data structures , algor...

c# - Regexp not working due to newlines? -

this have far, trying convert: [quote="tom":1m8ud0zc]blah blah[/quote:1m8ud0zc] into <table width="99%"><tr><td class="bbquote"><strong><em>originally posted tom</strong></em><br /><br />blah blah</td></tr></table> but text between quote tags can have newlines, seems make not work, can tell me how make (.*?) include matching every special char well? message = regex.replace(message, @"\[quote=""(.*?)"":.*?](.*?)\[/quote:.*?]", "<table width=\"99%\"><tr><td class=\"bbquote\"><strong><em>originally posted $1</strong></em><br /><br />$2</td></tr></table>" ); use regexoptions.singleline . changes meaning of dot (.) matches every character instead of every character except \n. m...

mysql - updating results -

table1 create table master (id int primarykey, start_point int, data blob ) 'changes' table: sample data 1, 0, data1 2, 1, data2 3, 2, data3 4, 4, data4 5, 6, data5 6, 8, data6 table2 create table changes (id int, start_point int, user varchar(10), data blob ) user table: sample data 5, 6, user1, data5(with changed data) 3, 2, user2, data3( changes) 4, 6, user2, data4(with changes) 5, 8, user2, data5 (with changes) table3 create table users (id int, user varchar(10) ) sample data 1, user1 2, user1 3, user1 4, user1 5, user1 1, user2 2, user2 3, user2 4, user2 5, user2 final result user1 should (information of id's user1 provided table3) 0, data1----from master 1, data2----from master 2, data3----from master 4, data4-----from master 6, data5...this changes final result user2 should be 0, data1 1, data2 2, data3 6, data4 8, data5 so trying get.....my problem here getting changed re...

iphone - Tableview within Split View Controller -

Image
i trying put tableview controller split view controller... kind of settings app , mail app combined (the tiny section , large section have functioning tableviews link other pages). can please provide working source code of this? thanks! um, that's built-in sample:

linux - How to compare spoken audio against reference recording - language learning -

i looking way compare user submitted audio recording against reference recording comparison in order give grade or percentage language learning. i realize un-scientific way of doing things , more gimmick anything. my first thoughts sort of audio fingerprinting, or waveform comparison. any ideas should looking? this no means trivial problem solve, though there abundance of research on topic. presently successful forms of machine learning in speech recognition domain apply hidden markov model techniques. you may want take @ existing implementations of hmm algorithms. 1 such library in stages ghmm . perhaps better , more readily applicable problem htk .

Ruby: Method Help -

i computer science major, , learning ruby. lost on problem supposed solve, syntax issues. here do: write method takes array of strings , block , calls block on each string. recall keyword call block yield. syntax call following: method(["blah", "blah"]) {...} test method passing block prints result of applying reverse each string. print out original array after call. test again passing block calls reverse!. print out original array. observe differences, explain them in comments. i'm not sure how problem @ all. i'm new block , yield. def my_method(array, &block) array.each{|a| yield a} end array = ["one", "two", "three"] my_method(array) |a| puts a.reverse end #=> eno #=> owt #=> eerht array #=> ["one", "two", "three"] my_method(array) |a| puts a.reverse! end #=> eno #=> owt #=> eerht array #=> ["eno", "owt", ...

javascript - Upgrading to jQuery 1.5 has broken my code -

i have following code make parallax niceness mapped scroll bar. moves both background position of section , elements in section classed "mover" it works fine jquery 1.4.x when upgraded 1.5.2 elements don't quite original positions does know changes in 1.5 cause this? var lastscrolltop = 0 var scrolltop = 0 $(window).scroll(function() { scrolltop = $(window).scrolltop(); var move = lastscrolltop - scrolltop; lastscrolltop = scrolltop; $('.mover').each(function(i, element){ element = $(element); if(!belowthefold(element)){ var currentpos = parseint(element.css("top")); var speed = $(this).attr('data-scroll-speed'); var pos = currentpos + (move*speed); element.css('top', pos); } }); $('.background-mover').each(function(i,element){ element = $(element); if(!belowthefold(element)){ var currentpos = p...

Switch image by variable with Javascript -

i'm writing image gallery script in thumbnail currently-viewed image indicated smaller image below thumbnail. placeholder follows: <img name="indicator0" alt="indicator> with indicator1 , indicator2 , etc. following. in script, placeholder has indicator called variable thumbindicator . i'd able this: document.(thumbindicator).src = "indicator_image.jpg"; but has not worked. i've changed image placeholder this: <img id="indicator0" alt="indicator"> and script this: document.getelementbyid(thumbindicator).src = "indicator_image.jpg"; but hasn't worked either. i have been designing websites while now, have fair amount of experience php/mysql, new javascript. appreciated. you need set id of placeholder image, (which might doing, not in code above). <img id="thumbindicator" alt="alternate text" /> then it: document.getelementbyid("thumbindica...

php - Kohana 3: has_many and order_by -

how can order query uses has_many association in kohana 3? have tried $model->items->order_by('fieldname')->find_all() ? __get() method returns query_builder object, not database_result, can add qbuilder's conditions (where/order_by/etc) needs.

SQL Select Count in Where Clause Performance issue -

i have following sql query performs horribly due select count(1) statement in clause. can suggest way speed up? idea want rows returned there 1 invoice found. select people.name, people.address people ((select count(1) invoices invoices.pid = people.id)=1) count(1) superstition what have count per row of people = cursor/loop action so, try join this select people.name, people.address people join invoices on invoices.pid = people.id group people.name, people.address having count(*) = 1 i'd hope have indexes, @ least on invoices.pid , people.pid, name, address

Issues with inheritance (java) -

i reading how java avoids deadly diamond of death, still have questions. if class inherits class , implements interface , each have method same prototype? or method same name, same arguments, different return types? thank you! what if class inherits class , implements interface , each have method same prototype? if don't override inherited method, compiler assume it's class' implementation of interface method. may not correct. depends on superclass' implementation. or method same name, same arguments, different return types? you won't able implement interface method because compiler think trying overload superclass method different return type.

qt4 - How to call one mainwindow to another mainwindow in Qt (or PyQt) -

in project have created 2 mainwindow want call mainwindow2 mainwindow1 (which in running). in mainwindow1 used app.exec_() (pyqt) , show maindow2 using maindow2.show() in click event of button not show anything calling mainwindow2.show() should work you. give more complete example of code? there may wrong somewhere else. edit: code updated show example of how hide , show windows when opening , closing other windows. from pyqt4.qtgui import qapplication, qmainwindow, qpushbutton, \ qlabel, qvboxlayout, qwidget pyqt4.qtcore import pyqtsignal class mainwindow1(qmainwindow): def __init__(self, parent=none): qmainwindow.__init__(self, parent) button = qpushbutton('test') button.clicked.connect(self.newwindow) label = qlabel('mainwindow1') centralwidget = qwidget() vbox = qvboxlayout(centralwidget) vbox.addwidget(label) vbox.addwidget(button) self.setcentralwidget(cent...

c# - What is the equivalent of DataSource for a WPF ListBox? -

i'm trying set listbox txt file. read file , populate list, want display in listbox, have no datasource option available (only datacontext , datacontextchanged). my listbox declared in xaml : <listbox name="scriptlist" grid.row="0" grid.column="1" textblock.fontsize="12" margin="2" /> any idea why ? also, right way proceed (read file -> i've used itemssource , works.

wpf - Binding with UpdateSourceTrigger==LostFocus do not fire for Menu or Toolbar interaction -

i noticed bindings updatesourcetrigger==lostfocus not updated when user activates menu or toolbar. this leads unfortunate situation last change user made gets lost when user selects "save file" menu or toolbar. is there easy way around or have change bindings updatesourcetrigger=propertychanged . the problem textbox does, in fact, not lose focus when menu item activated. thus, updatesourcetrigger lostfocus not fire. depending on (view)model, updatesourcetrigger propertychanged might or might not feasible workaround. for me, propertychanged not option (i need validate data after user finished entering it, not in between), used workaround calling method before "save file" (or other menu/toolbar entry requires up-to-date model): public shared sub savefocusedtextbox() dim focusedtextbox = trycast(keyboard.focusedelement, textbox) if focusedtextbox isnot nothing dim = focusedtextbox.getbindingexpression(textbox.textproperty) ...

Python JSON Google Translator parsing with Simplejson problem -

i trying parse google translation result using simplejson in python. getting following exception. traceback (most recent call last): file "translator.py", line 45, in <module> main() file "translator.py", line 41, in main parse_json(trans_text) file "translator.py", line 29, in parse_json json = simplejson.loads(str(trans_text)) file "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/__init__.py", line 385, in loads return _default_decoder.decode(s) file "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/decoder.py", line 402, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) file "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/decoder.py", line 418, in raw_decode obj, end = self.scan_once(s, idx) simplejson.decoder.jsondecodeerror: expecting property nam...

c# - Accessing xaml elements in viewmodel and applying dynamic styles at runtime using wpf mvvm -

i need apply dynamic style button in viewmodel on basis of if else condition. have created 2 styles button in separata user controls using resourcedictionary same key. button in 1 usercontrol i.e. xaml. how dynamically apply styles using style tag , dynamicresource. how properties? kindly suggest? thanks by sounds of things need use either multitriggers or multidatatriggers. can find out more multitriggers here , multidatatriggers here . triggers allow take different actions based on single or multiple condition(s). hope helps.

java - HttpSession, session.getAttribute(), problem -

i have problem related java servlet sessions. don't understand why getattribute() function of session object used before setattribute(); here code: vector buylist=(vector)session.getattribute("register"); if (action.equals("del")) { string del = request.getparameter("deli"); int d = (new integer(del)).intvalue(); buylist.removeelementat(d); } session.setattribute("register", buylist); thanks. because register attribute may set other place (like. jsp(in bad case),servlet or filter . . )

url - problem in using camera in android -

following code capturing images in app. after capturing image saves in sdcard , shows done , retake when click done button want captured image uploaded url. i not able know done , retake button gets appeared pls me... protected static final int take_receipt = 0; button b1; intent myintent; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); b1 = (button)findviewbyid(r.id.widget98); b1.setonclicklistener(new onclicklistener() { @override public void onclick(view view) { takepicturefromcamera(); } private void takepicturefromcamera() { intent intent = new intent(mediastore.action_image_capture); startactivityforresult(intent, take_receipt); } to save image somewhere specific, need provide uri using mediastore.extra_outp...

java - How to execute Google Codepro analytix from command line? -

is possible run google codepro analytix command line. what looking run shell script passing file name parameter , metrics generated on file level filename passed in parameter. is possible so? , how? are there other tools can give same metrics java file , executed shell script? there set of codepro ant tasks can used auditing report generation. as other tools, there set of ant tasks pmd pmd plugin maven . both can run command line. similar findbugs : instructions ant task can found here , , maven plugin here edit: seems me google purchased beatiful tool let die of obscurity. there seems no ongoig development , no release open source. ant tasks not released (and have found no usable examples). there no maven plugin. unable integrate in our build , using pmd, findbugs , sonar. it's shame.

multithreading - glGenTextures not returning a texture name -

i creating opengl game on windows 7 machine using vs2010. in addition, sdl, qtcore, qtxml , fbxsdk used assist in development. experiencing peculiar problem glgentextures when running outside debug mode. let me explain. when compile , run application in debug mode, models textured , displayed properly. debug application or compile , run application using release mode textures no longer being applied models. i have tracked down problem glgentextures not giving me valid name. not give me errors either. way loading follows: models loaded fbx through fbxsdk, required textures loaded model loaded. models loaded in thread, made sure no opengl functions called anywhere while thread loading models. if don't load models in thread works. tried can think of including halting main thread while models loaded guarantee nothing else if happening while models loaded. none of works. again wouldn't weird except compiling debug works. release , debugging application doesn't work. ...

layout - Android animation starts only after scrolling it's parent view -

i'm trying create expandable menu item in android, button , on button click, button expand down animation. set expand animation layout want expand when clicked view , have problem animation. doesn't start when clicked view, , starts when scroll-down or scroll-up container of view. , if container not scrollable, animation never starts. doing wrong? here expand method, onclick method , layout xml file custom view things: expand: public void expand(final view v) { try { method m = v.getclass().getdeclaredmethod("onmeasure", int.class, int.class); m.setaccessible(true); m.invoke(v, measurespec.makemeasurespec(0, measurespec.unspecified), measurespec.makemeasurespec(((view)v.getparent()).getmeasuredwidth(), measurespec.at_most) ); } catch (exception e) { log.e(tag , "caught exception!", e); } final int initialheight = v.ge...

Android: UnitTest -

need advice. have app. , need write unittest. don't know test. test settings , preferences, that's easy. else people test ? lets have 3 activities. main 1 list activity, when click on list item forward on second list activity...and on list item click forward on third activity. think maybe should test switching between activities ? how simulate click on list item in unittest , how check activity open or not ? ! android provides test classes able exhaustive in unit testing want be. can unit test java components, android-architecture dependant components, , workflow whole. in case, test sequences between activities, can use instrumentationtestcase class , extend it, , in tests, should use following methods: // prepare monitor activity instrumentation instrumentation = getinstrumentation() instrumentation.activitymonitor monitor = instrumentation.addmonitor(yourclass.class.getname(), null, false); // start activity manually intent intent = new intent(intent.action...

grammar - stack translator in formal languages -

can explain how stack translator works ? think used lexical analysis (i wrong) . additional material or links welcome ! ! the correct term searching "pushdown transducer" see here, example: http://www.cse.ohio-state.edu/~gurari/theory-bk/theory-bk-threese2.html

Using pure TNSNAMES rather than host-based database connections in Oracle JDeveloper -

i'm using oracle jdeveloper 11.1.1.4.0, , can create database connections (with type of oracle (jdbc) ) using thin driver without problems long i'm specifying host. for instance, can connect locally-running oracle xe database specifying: driver: thin host name: localhost jdbc port: 1521 service name: xe for connecting remote databases, use tns, , tnsnames.ora file set below, mydatabase.example.com oracle service identifier want use. mydatabase.example.com= (description= (address= (protocol=tcp) (host=testdb.example.com) (port=1234) ) (connect_data= (service_name=mydatabase.example.com) ) ) connections mydatabase.example.com service work sql developer, sql plus, tnsping etc. machine can't find way of specifying in jdeveloper database connection without being forced specify host. the reason don't want specify host same reason we're using tns in first place - testdb.example.com host change on time, mydata...

php - Asterisk full log parser -

i want make log parser for asterisk pbx, don't know start. figured out need log. lines need this: [apr 12 11:11:56] verbose[3359] logger.c: -- called 111 number in verbose[....] same 1 call. the first thing have lines contain verbose number can identify call. second thing read text, there standard texts won't hard recognize. the thing read real time (the file written real time), , display in webpage. php or ajax. the thing want is, show rows in webpage users call. , new call added under current/answered call. any tips, examples great. thanks, sebastian i in 2 programs can work simple cgi programs. first program parses log , show date , call identifier. such identifier link 2nd program. in python can use regexp: # 1st group - date, 2nd - callid rx_verbose = re.compile(r'(.*) verbose\[(\d+)\] ') def make_link(call_id): return(' <a href="show_call.cgi?call_id=%d>%d</a>' % (call_id, call_id)) def show_calls(lo...

ios - EXC_BAD_ACCESS issue on iphone and simulator -

i getting exc_bad_access out side of own code. code gets url through shareurlcache object , starts url connection. once leave method starts url connection hit exc_bad_access. have tried using instruments find zombies , have analysed memory leaks , not turned either. @ point stuck. here code loads url , starts url connection - (void)locationmanager:(cllocationmanager *)manager didupdatetolocation:(cllocation *)newlocation fromlocation:(cllocation *)oldlocation { nslog(@"at new location: %@",newlocation); mkcoordinateregion region = mkcoordinateregionmakewithdistance([newlocation coordinate], 750, 750); [mapview setregion:region animated:yes]; [location stopupdatinglocation]; cllocationcoordinate2d coord = [newlocation coordinate]; nsurl *url = [urlcache getreccomendationforuid:@"12345" atlat:coord.latitude atlon:coord.longitude forcategories:nil]; // create reques...

How can I set session timeout for 2-3 days in PHP? -

i set sessions last 2-3 days users not have login data after days of being idle. please me code achieve this. you try: ini_set('session.gc_maxlifetime', 2*60*60*24); // 2*60*60*24 = 2 days

iphone - why can't Xcode find this header file? -

hi i'm getting xcode "no such file or directory" for: #import "three20core.h" i note when i'm typing in #import statement recognises, , helps autocomplete, "three20core.h" file, when compile error? this main library file header three20 library (from facebook). i've got three20 directory @ same level app directory. in xcode application target build settings: header search paths - "$(built_products_dir)/../../../three20" , recursive, and user header search paths - same above. any fault finding advice? see expanded version of answer here: xcode 4 archive version unspecified i've found many issues xcode 4 when comes complex project structures. create group in project called "indexing" drag header files group when asked select target uncheck all targets this has solved of xcode 4 issues. related questions: xcode 4 can't locate public header files static library de...

types - What is the size of column of int(11) in mysql in bytes? -

what size of column of int(11) in mysql in bytes? and maximum value can stored in columns? an int 4 bytes no matter length specified. tinyint = 1 byte (8 bit) smallint = 2 bytes (16 bit) mediumint = 3 bytes (24 bit) int = 4 bytes (32 bit) bigint = 8 bytes (64 bit). the length specifies how many characters display when selecting data mysql command line client. ... , maximum value 2147483647 (signed) or 4294967295 (unsigned)

cant tab what ever i want in emacs indentation mode -

in javascript , html mode emacs cant make indentation , want make better hand when use tab use self indentation , not listen :d what can do? now <html> <body> http 404 error !! </body> </html> what want <html> <body> http 404 error !! </body> </html> only example some modes offer "bouncing" indentation, tab toggle indentation level between few alternatives. example javascript js2-mode . i'm not aware of more general solution. however, note if tab getting intercepted major mode's keymap, can still insert literal tab character using c-q tab . need.

how to set width of spinner in android? -

how set width of spinner programatically ? in layout file <spinner android:id="@+id/spinner" android:layout_width="200dip" android:layout_height="fill_parent" android:prompt="@string/my_spinner" /> would give spinner width of 200dip .