Posts

Showing posts from May, 2014

android - java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2 -

scenario:- i have 2 arraylist list contains images postlist contains position of selected images now when ever selecting images , press delete menu ,it should delete selected images . when running code in debug ,its working fine , give desire output. but when running normal mode ,its crashing , giving above exception . if (poslist.size() > 0) { toast.maketext(getbasecontext(), "i value" +poslist.size(), toast.length_short).show(); (int = 0; < poslist.size(); i++) appadp.list.remove(appadp.list.get(poslist.get(i))); appadp.notifydatasetchanged(); poslist.clear(); toast.maketext(getbasecontext(), "you deleted selected items", toast.length_short).show(); } return true; postlist values here @override public void onitemcheckedstatechanged(actionmode mode, int position, long id, boolean checked) { poslist.add(position); erro...

phpmyadmin - Codeigniter get sum of goals a player has made -

i got database. mysql script of it. player can appear more in table want sum of goals player has made. script: create table if not exists `spelerswedstrijden` ( `id` int(5) not null auto_increment, `spelerid` int(2) not null, `wedstrijdid` int(5) not null, `goals` int(5) default null, `assisten` int(5) default null, `gelekaarten` int(5) default null, `rodekaarten` int(5) default null, primary key (`id`) ) my model code: function getgoals($id) { $this->db->where('spelerid', $id); $this->db->from('spelerswedstrijden'); $goals = $this->db->select_sum('goals');; return $goals; } using code gives me following error: object of class ci_db_mysql_driver not converted string ideas how can fix this? in advance function getgoals($id) { $this->db->select('count(id) totalgoals'); $this->db->where('spelerid', $id); $this->db->group_by('spelerid'); $goals = $...

mongodb - Slow range query on a multikey index -

i have mongodb collection named post 35 million objects. collection has 2 secondary indexes defined follows. > db.post.getindexkeys() [ { "_id" : 1 }, { "namespace" : 1, "domain" : 1, "post_id" : 1 }, { "namespace" : 1, "post_time" : 1, "tags" : 1 // array field } ] i expect following query, filters namespace , post_time , run in reasonable time without scanning objects. >db.post.find({post_time: {"$gte" : isodate("2013-04-09t00:00:00z"), "$lt" : isodate("2013-04-09t01:00:00z")}, namespace: "my_namespace"}).count() 7408 however, takes mongodb @ least ten minutes retrieve result and, curiously, manages scan 70 million objects job according explain function. > db.post.find({post_time: {"$gte" : isodate("2013-04-09t00:00:00z"), "$lt" ...

sum - java "=+" compiles but it does not affect any variable -

i wanted increment integer adding 1 , wrote "=+" instead of "+=" . , saw compiles not . or ? a=3 b=5 a=+b print >>> 5 what reason ? since =+ not operator (but += is). so a=+b equals "a = +b" , b = +b a = b in end. may looking a += b equals a = + b

javascript - How to specifically set the caret position in a contenteditable div -

i need set caret position in contenteditable div in chrome not focused know caret position i.e. character index in html of div. div may have other elements inside of it. the best got far setting caret position either @ end or start of div domnode.focus(); if (window.getselection) { var sel = window.getselection(); //sel.collapsetostart(); //sel.collapsetoend(); sel.collapse(domnode, caretpos); } i tried calling 'modify' on selection manually move cursor word word , counting length of selected text text stops if there's element in way e.g. if div content " hello <span>world</span> " selected node's text hello .

jquery - Change the onclick attribute -

<div class="hp_imp" onclick="location.href='https://www.abc.com/xyz';"> </div> <div class="hp_imp" onclick="location.href='https://www.abc.com/xyz/';"> </div> the first div div https://www.abc.com/xyz , need make url https://www.abc.com/xyz/ in div dynamically. $('.hp_imp').attr('onclick', function(i, val) { return val + '/'; }); don't care inline event handlers, , should consider removing it, change it, should work.

ruby on rails - error when i try to go to calendars_path ( nil can't be coerced into Fixnum) -

i have succeeded resolve problem nil can't coerced fixnum 1 :( no block given (yield) i know problem on index.html line 8 dont know resolve module calendarhelper def calendar(date = date.today, &block) calendar.new(self, date, block).table end class calendar < struct.new(:view, :date, :callback) header = %w[monday mardi mercredi jeudi vendredi samedi dimanche] start_day = :monday delegate :content_tag, to: :view def table content_tag :table, class: "calendar" header + week_rows end end def header content_tag :tr header.map { |day| content_tag :th, day }.join.html_safe end end def week_rows weeks.map |week| content_tag :tr week.map { |day| day_cell(day) }.join.html_safe end end.join.html_safe end def day_cell(day) content_tag :td, view.capture(day, &callback), class:...

css - Wrap two adjacent td's -

i have table 2 columns, both 300px wide, taking 600px in width on regular computer screen. i want modify display of table small screen mobile devices. is there css way make cell of right column wrap , go below cell of left column, followed next left cell, followed next right cell, , on? here proof-of-concept demonstration. consider following table: <table> <tr> <td>first row - cell 1</td> <td>first row - cell 2</td> </tr> <tr> <td>second row - cell 1</td> <td>second row - cell 2</td> </tr> </table> if float table cells, can them stack vertically, example: table { width: auto; } table td { background-color: lightgray; float: left; width: 150px; margin: 10px 0; } you need adjust table width , cell width in media query. the 1 advantage of using floats table responsive without using media queries, may useful in ...

php - Passing Arg in Ant -

i working on ant script following code block: <target name="phplint"> <apply dir="${dir.publish.php}" executable="${tool.php.lint}" parallel="true" failonerror="false"> <fileset dir="${dir.publish.php}"> <include name="**/*.php"/> </fileset> <arg value="-l" /> <srcfile/> <mapper type="glob" from="*.php" to="*.html"/> </apply> </target> the command want run below: php -l index-1.php > index-1.html how can it...! because above code working. don't want <arg value="-l"/> i want pass <arg value="-l"/> <arg value="> *.html"/> set output attribute specify file output of command should redirec...

android - Custom Actionbar Sherlock PreferenceActivity ListView -

Image
i use sherlockpreferenceactivity preference activity xml file. code below: public class setting extends sherlockpreferenceactivity { protected void oncreate(bundle parambundle) { super.oncreate(parambundle); addpreferencesfromresource(r.xml.setting); } everything work fine need margin left , right 0dip (the pic below) i had try find in abs source code failed custom it. has before? update: upload more detail image setting.xml content: <?xml version="1.0" encoding="utf-8"?> <preferencescreen xmlns:android="http://schemas.android.com/apk/res/android" > <preferencecategory android:title="@string/system_setting" > <checkboxpreference android:defaultvalue="true" android:key="mode_on_off" android:summaryoff="sub setting 1" android:summaryon="sub setting 1 on" android:title="setting 1" /> ...

How to make Jquery work with google closure compiler -

i have been going through posts related gcc jquery unable find solution. jquery still not compatible work gcc? if not can please refer appropriate link or provide example? the main distribution of jquery not compatible closure-compiler advanced_optimizations. use main build of jquery must reference appropriate jquery extern file in closure-compiler contrib folder . i have experimental jquery 1.9.1 build compatible adavanced_optimizations. available on github account . a version of jquery 2.0.x branch compatible under development, not yet complete.

Does dygraph assume the independent variables are ordered? -

it seems default l/h of x-axis determined first/last point of series rather min/max. is there way change behavior in dygraph? considered bug? or should sorting? generally, data given dygraphs should sorted. functionality works without being sorted, number of functions expect first column sorted. believe logs warning when data not sorted.

c++ - glClearBufferData - Usage Example? -

Image
void glclearbufferdata(glenum target, glenum internalformat, glenum format, glenum type, const void* data); i'm not quite sure how use method properly. more internalformat , format parameters. official documentation vague these are, , i'm having trouble finding list of available targets these. these set targets, or need pass size data or something? couldn't find usage examples of function online... provide me one, or perhaps list of targets? target target destination buffer bound. internalformat must set 1 of format tokens given opengl format , type specify format , type of source data. data converted data passed buffer reference: http://www.opengl.org/registry/specs/arb/clear_buffer_object.txt you can find list of internal formats here: http://www.opengl.org/sdk/docs/man/xhtml/glteximage2d.xml though cannot seem find table 3.15 text references. example: you can find article here

linux - Glob is different value error opening a file and reading -

sub open_files { @files = @_; @lines; foreach (@files){ print "$_\[1\]\n"; } foreach $f (@files){ print "$f\[2\]\n"; open(my $fh,'<',$f) or die " '$f' $!"; print "$fh\[3\]\n"; push(@lines,<$fh>); close($fh); } return @lines; } hi having problems opening files absolute path stored in array. what want go through array , open each file , store data inside @lines array , close file handle. however able open .html files stored in first child directory .e.g /a/abc.html or /b/bcd.html not opening (or parsing ) files in sub-child directories such /a/aa/abc.html or /b/bb/bcd.html i have put in print statements in script , numbered output different print lines e.g. [1] [2] [3] . this result of executing above code: the full code : pastebin full code /mnt/hgfs/perl/assignment/test/a/aa/1 - copy - copy (2).htm[1] /mnt/hgfs/perl/...

Dealing with awkward XML layout in c# using XmlTextReader -

so have xml document i'm trying import using xmltextreader in c#, , code works except 1 part, that's tag line not on same line text/content, example product_name: <product> <sku>27939</sku> <product_name> sof-therm warm-up jacket </product_name> <supplier_number>alnn1064</supplier_number> </product> my code try sort xml document such: while (reader.read()) { switch (reader.name) { case "sku": newele = new xmlelement(); newele.sku = reader.readstring(); break; case "product_name": newele.productname = reader.readstring(); break; case "supplier_number": newele.suppliernumber = reader.readstring(...

CSS: margin-right and absolute positioning -

i have single div in page. now, when specify position absolute , give margin-left == 20px: i understand that. div element should shift right 20 px thee exists margin 0f 20px between div , body. now when provide margin of 20px right side, shouldn't whole div move towards right side gap of 20px body. http://jsfiddle.net/2jfpj/ .container{ position: absolute; background-color:gray; margin-right: 50px; height: 200px; } i know can position div giving values of left , right. real question margin left works margin-right doesnt! why so? appreciated! its not margin-right looking right please see fiddle update: jsfiddle right and if want sit @ bottom of screen add bottom try updated fiddle: jsfiddle bottom margin-right not work because add margin div area itself, while right position value. if @ box model shows margin added to. margin used give box space other objects around itself.

Popup window in winform c# -

i'm working on project need popup window. thing want able add textboxes etc in popup window thru form designer. so have button , when click on it open window i've designed in form designer. i've been doing googling haven't found needed yet hoping guys me! just create form (lets call formpopoup ) using visual studio. in button handler write followng code: var form = new formpopoup(); form.show(this); // if need non-modal window if need non-modal window use: form.show(); . if need dialog (so code hangs on invocation until close opened form) use: form.showdialog()

Breeze and mobile memory management -

at point references entitymanager containers in memory released in mobile browser app? getting out of browser app release cache memory? realize can entitymanger.clear(), of course, users cut out of mobile browser. how can know if cache memory of container released? there tool observe this? i'm wondering if need concern myself concept of garbage collection. if "getting out of browser app" mean either navigating away hosting web page or closing browser ... yes, either release memory formerly consumed app.

Multiple javascript window.onload solution -

before ask questions, ever post questions don't understand implement in code. have code this window.onload = function() { var url = getqueryvariable("url"); document.getelementbyid('view').src = url; } window.onload = function() { var linkdirect = document.getelementsbyclassname("frame"); (var = 0; < linkdirect.length; i++) { linkdirect[i].href = "http://namablog.blogspot.com/p/demo.html?url=" + linkdirect[i].href } } then, how can make code execution using 1 window.onload you can use addeventlistener or jquery equivalent. window.addeventlistener('load', function (){ alert('function #1'); }); window.addeventlistener('load', function (){ alert('function #2'); }); be sure call these before window loaded.

nullpointerexception - Android Crash after using SharedPreferences -

i developing android application, keep me logged in functionality using sharedpreferences application started crash. this line add preferences; sharedpreferences pref = getapplicationcontext().getsharedpreferences("rs_remember" , getapplicationcontext().mode_private); i pretty sure line causing error because works fine if remove it. error message says: java.lang.runtime: unable create application com.x.x.x : java.lang.nullpointerexception. any idea abot shuold do? edit public activity activity; sharedpreferences pref; private rscurrentusermanager() { super(); pref = this.activity.getsharedpreferences("rallyspark_remember",0); } +05-09 18:02:56.221: e/androidruntime(31760): fatal exception: main +05-09 18:02:56.221: e/androidruntime(31760): java.lang.runtimeexception: unable create application com.x.x.general.rsapplication: java.lang.nullpointerexception +05-09 18:02:56.221: e/androidruntime(31760): @...

django - Caught VariableDoesNotExist while rendering: Failed lookup for key [time_filter] in u'[{}, -

views.py def when(request): user = request.user report = report.objects.get(user=request.user) reportform = reportform(instance=report) settings = settings.objects.get(user=request.user) settingsform = settingsform(instance=settings) settings=settings.objects.get(user=2) if settings.date_format == '0': date_filter = 'd/m/y' else: date_filter = 'm/d/y' if settings.time_format == '0': time_filter = 'i:mp' else: time_filter = 'h:m' if request.method == 'post': reportform = reportform(instance=report,data=request.post) if reportform.is_valid(): report = reportform.save(commit=false) report.user = request.user report.save() return redirect('/member/media/') return render_to_response('incident/when.html',{ 'newreport_menu': true, ...

sql - how to create trigger to split datetime into date -

why trigger not work ? try create trigger insert single date datetime. example : when insert datetime, trigger insert date, month, year, dayname, age in other column. the datetime, date month, year, dayname, age in same table. ╔══════════════════════════════╦══════╦═══════╦══════╦═════════╦══════════╗ ║ datetime ║ date ║ month ║ year ║ dayname ║ age ║ ╠══════════════════════════════╬══════╬═══════╬══════╬═════════╬══════════╣ ║ april, 06 1982 00:00:00+0000 ║ 4 ║ 6 ║ 1982 ║ friday ║ 31 ║ ╚══════════════════════════════╩══════╩═══════╩══════╩═════════╩══════════╝ create trigger tgl on penduduk insert declare @mydate char(11) select @mydate=tgl_lahir inserted insert penduduk(tgl) values (datename(day,@mydate)) when try code above got message msg 2714, level 16, state 2, procedure tgl, line 8 there object named 'tgl' in database. should create column date, month year, dayname , ag...

xslt send variable to another template -

i have xml example this: <p class="exer_header" style="display: none;"> <image-input size="5" value="val1" /> </p> <p class="exer_header" style="display: none;"> <image-input size="5" value="val2" /> </p> <answers-img> <answer-img class="imagednd_answer1" value="val1"/> <answer-img class="imagednd_answer2" value="val2"/> </answers-img> and xslt ex. here: <xsl:template match="image-input"> <xsl:variable name="id" select="generate-id(.)"/> <xsl:element name="input"> <xsl:attribute name="id"><xsl:value-of select="$id"/></xsl:attribute> <xsl:attribute name="class">exer_input</xsl:attribute> </xsl:element> </xsl:template...

javascript - Options for logging Windows Store apps -

so i'm creating many windows (8) store apps , i'm wondering best choices users possible bugs (if ever occour). i thinking log4net solution rollingfile. or maybe on appcrashed event send crash report own server. what options? what's "best" option? i'd recommend using new google analytics service. add free google analytics sdk windows 8 app , automatically track unhandled exceptions (or add 1 line of code track them manually). super easy, plus ton of great analytics tracking app.

linux - How to parse numbers from an array in codes like this? -

i need parse numbers codes this: p1 <- c(1, 2, 100, 23, 0.12, 0.03, 0) p2 <- c(100, 200, 1, 23, 0.12, 0.03, 0) p30 <- c(100, 200, 1, 23, 0.12, 0.03, 0) p300 <- c(100, 200, 1, 23, 2, 1, 0) more variables starts p... other codes... the results this: 1 2 100 23 0.12 0.03 0 100 200 1 23 0.12 0.03 0 100 200 1 23 0.12 0.03 0 100 200 1 23 2 1 0 in each row represent array of variable. i tried sed , awk , doesn't work out it. have ideas this? thanks! using gnu sed (for -r , eres): $ cat file p1 <- c(1, 2, 100, 23, 0.12, 0.03, 0) p2 <- c(100, 200, 1, 23, 0.12, 0.03, 0) p30 <- c(100, 200, 1, 23, 0.12, 0.03, 0) p300 <- c(100, 200, 1, 23, 2, 1, 0) $ sed -r 's/.*\(|[,)]//g' file 1 2 100 23 0.12 0.03 0 100 200 1 23 0.12 0.03 0 100 200 1 23 0.12 0.03 0 100 200 1 23 2 1 0

php - How do I embed a select in a select or call another function from a select? -

i have select statement this: select c.id courseid, u.id userid mdl_user_enrolments ue join mdl_enrol e on e.id = ue.enrolid join mdl_user u on u.id = ue.userid join mdl_course c on c.id = e.courseid i have piece of data want not have direct relationship current tables. have been calling function in output loop, function getlastcourseaccessbyuser($courseid, $userid){ global $db; return $db->get_record_sql(' select from_unixtime(time, "%m/%d/%y") ftime mdl_log course = '.$courseid.' , userid = '.$userid.' order time desc limit 1 '); } but rather data once, , not call db. i trying this: select c.id courseid, u.id userid ( select from_unixtime(time, "%m/%d/%y") ftime mdl_log course = c.id , userid = u.id ) lastaccessdate mdl_user_enrolments ue join mdl_enrol e on ...

c# - WCF multiple instances of a service, 1 per thread -

im trying set distributed computing environment using wcf. have large amount of data process, have managed split discrete blocks. is possible create multiple instance, 1 per core of pc, of same class (called numbercruncher) , assign each specific endpoint on servicehost? far ive understood, each endpoint needs abc (address (unique), binding info, contract), long assign unique endpoint address each instance of numbercruncher should able access each thread, contains single instance of numbercruncher? if above work poor solution, i'd appreciate suggestions on possible alternative.

ASP.NET MVC4 repository injection to controller that depends on currently logged user -

let's creating "todo list" web application following features: have ability register/login users each user has it's own todo list independent other users so i've created simple model has class todoitem. i'd use practices created generic repository should fetch todo items database: public interface irepository<t> { iqueryable<t> findall(); iqueryable<t> find(expression<func<t, bool>> predicate); void add(t newentity); void remove(t entity); t findbyid(long id); } (implementation done ef , code-first approach that's not important right now) this repository injected controller allows user list, add, remove, edit todo items. done via custom controller factory i've created uses ninject di container resolve repository interface concrete implementation. controller looks this: public class homecontroller : controller { irepository<todoitem> _repository; public homecontroller...

php - Using DirectoryIterator to loop through a D: drive directory -

i trying loop through directory: $path = "d:\\import\\statsummary\\"; here code: $path = "d:\\import\\statsummary\\"; //$path = "c:\\test"; //function load_csv($path, $filename){ if(is_null($filename)){ header('content-type: text/plain'); $output = array(); foreach (new directoryiterator($path) $file){ if($file->isfile()){ $output[] = $i++ . " " . $file->getfilename() . "\n"; $output[] = file($file->getpathname()); $output[] = "\n------------\n"; } } } echo implode('', $output); when run script, error: fatal error: uncaught exception 'unexpectedvalueexception' message 'directoryiterator::__construct(d:\import\statsummary\,d:\import\statsummary\): access denied. (code: 5)' in c:\inetpub\wwwroot\include\file_importer.php:10 stack trace: #0 c:\inetpub\wwwroot\i...

sql - DATALENGTH() or ISNULL() to retrieve fields that are not null and not empty -

quite simply, of following methods better in where clause retrieve records field_name not null , not empty where datalength(field_name) > 0 or where isnull(field_name, '') <> '' update i have been informed first method gives spurious results types of fields... agree? firstly, select * table column <> '' will give same results as select * table isnull(column, '') <> '' because records condition unknown rather false still filtered out. go first option. datalength counts trailing spaces, comparison '' not. whether want ' ' compare unequal '' . if do, need datalength . if don't, compare '' . note text / ntext types, comparisons not supported, datalength is.

python - Work with tuple of dictionaries -

i have following tuple of dictionaries: td=({'associatedframe': none, 'cyclicmodenumber': none, 'description': 'increment 10: arc length = 7.2813e-02', 'domain': 'arc_length', 'fieldoutputs': 'repository object', 'frameid': 10, 'framevalue': 0.0728124976158142, 'frequency': none, 'incrementnumber': 10, 'isimaginary': false, 'loadcase': none, 'mode': none}) i'd value associated key frameid . don't have many experience tuples , dictionaries , questions i've found dictionaries of tuples, ask help. thanks edit: had tried solution forgot mention i'm using python results program. program has specific organisation in order work had write td.frameid . if have, dictionary. td['frameid'] will work. parenthesis don't make tuple. comma makes tuple. foo = (1) #intege...

java - JCache API usage with invalidation clustered cache -

clustered invalidation key-value caches sending remove commands on network. when value of key changed or removed on 1 node remove command sent key every other node need data persistent store (or re-calculate it) next time need it. my question is: how defined based on javax.cache.cache interface? there put, putifabsent, replace, ... functions there. using infinispan-jcache not have behaviour when same key exists on 2 different node. asked same question on user forum @ https://community.jboss.org/thread/228039 think more common question jsr-107 implementations affected. i checked draft specification not find clustering , invalidation there. the way infinispan working correct. invalidation means when node receives put/replace/putifabsent/remove calls, send message other nodes remove entry. so, when entry stored in cache2, it's removed cache1. doesn't verify if value same or not. jsr-107 not specify how caches should behave in cluster. jsr-107 focuses on local...

javascript - open virtual keyboard from chrome (osk.exe) -

it's 1 of these questions again (execute local.exe file chrome web browser). i know not possible (at least not in easy way) what want open virtual keyboard on windows machines stored in folder c:/windows/system32/osk.exe i know simple <a href="file:///c:/windows/system32/osk.exe">run virtual keyborad</a> don't work (for obvious reasons). so how can make work? if not possible this, how can solve issue? need able open virtual keyboard clicking on link on webpage. any other virtual keyboards can make use of user don't have download in order make use of through web-page? specs i run website in kiosk mode (in chrome) using 27" acer touch monitor (there no physical keyboard), running on windows7 computer. i'm using wamp webserver, i.e webpage accessed through local network. thanks in advance =) it not possible. live it. can not execute program on client machine. browser sandboxed. can make javascript equivalent...

oracle adf - Get Input text value programatically using id in ADF mobile -

i input text value programatically using id in adf mobile adf. below code use in adf value input text programatically. facescontext facescontext = facescontext.getcurrentinstance(); uiviewroot root = facescontext.getviewroot(); richinputtext inputtext = (richinputtext)root.findcomponent("it1"); string val=inputtext.getvalue(); but can't value in adf mobile. try access value page definition, instead of finding component root. dciteratorbinding iterator = (dciteratorbinding)dcbindings.get("someiteratorid"); string attribute = (string) iterator.getcurrentrow().getattribute("someattributename");

c++ - Asynchronous input and output/Get input after prefix -

i'm searching function print string before input made. know possible printf , gets , want string stay on last line input given. output handled in main thread, input handled in thread started main thread. for example current console window (i have input stop -command, '>' prefix string): [12:00:00] starting server... >stop when console outputs new line, want input on bottom line, this: [12:00:00] starting server... [12:00:01] server started >stop i using embarcadero c++builder xe2 win32 , vcl support. edit: i'm using code, resulting in printing output after '>' prefix: char buf[256]; printf(">"); gets(buf); what looking called asynchronous input/output. what did accomplish keeping track of each key being pressed , append string. when press backspace deletes last character added string , when press enter submit current command. when output comes along clear line typing on, print output, , move cursor down ...

ruby on rails - How do I pull the correct image URL from this Wikipedia table? -

i built scraper pull information out of wikipedia table , upload database. until realized pulling wrong url on images, , wanted actual image url " http://upload.wikimedia.org/wikipedia/commons/thumb/3/38/baconbutty.jpg " , not "/wiki/file:baconbutty.jpg" apt give me. here code far: def initialize @url = "http://en.wikipedia.org/wiki/list_of_sandwiches" @nodes = nokogiri::html(open(@url)) end def summary sammich_data = @nodes sammiches = sammich_data.css('div.mw-content-ltr table.wikitable tr') sammich_data.search('sup').remove sammich_hashes = sammiches.map {|x| if content = x.css('td')[0] name = content.text end if content = x.css('td a.image').map {|link| link ['href']} image =content[0] end if content = x.css('td')[2] origin = content.text end if content = x.css('td')[3] description =content.tex...

javascript - Limit JSON stringification depth -

when stringifying object using json.stringify (or similar) there way limit stringification depth, i.e. go n levels deep object tree , ignore comes after (or better: put placeholders in there, indicating left out)? i know json.stringify takes replacer function of form function (key, value) didn't find way depth in original object of current key-value-pair handed replacer function. is there way default json.stringify implementation? or have reached point should implement stringification myself? or there stringification library can recommend has option? make deep clone of object (with library such low-dash ), ever pruning want , pass json.stringify. not try re-invent json.stringify, effort in wrong place. [edit] looks did suggesting: json.stringify deep objects i wouldn't recommend though because native json.stringify going faster , more robust [edit] here library seems want: http://philogb.github.io/jit/static/v20/docs/files/core/core-js.html# $jit....

c# - Azure Media Services upload from HTML from -

i have mvc4 site allowing video uploaded. it's hosted on azure azure website. as such don't have access local storage in cache video before shipping off azure media services transcode/deliver. the upload process html5 chunked upload going straight webapi controller. controller called each uploaded chunk of file. what best option getting whole uploaded video ams convert? i presumed appending data blob right way it. however, can't seem find information on how append existing blob. also, i'm concerned cause concurrency issues if there random delay in handler causing data corruption. and videos of size uploading? free mode websites give 1g, shared , reserved - 10g. check out this project , mvc4 media services explorer. also check out this blog post on how upload directly blob storage using html5. upload asset via html5, must first shared access locator , upload files container sas media service.

Is MySQL commit synchronous when executed from PHP PDO? -

using php pdo interface mysql, suppose have code end transaction (assuming begun): $pdo->query('commit'); when function returns, have writes log been flushed? is, transaction committed, or have merely made request committed? assuming have not set options delay flushing, such as, example, setting innodb_flush_log_at_trx_commit zero. i ask because, if follow code above this: echo 'transaction has been committed.'; i wouldn't want caught in lie. update: see comments below. i'm not asking how innodb works. i'm asking whether pdo interface waits innodb engine execute command before returning. update #2: should have said commit performed call pdo::commit, how it, in case there's difference between , doing sql.

android - Holo theme make my button bigger -

Image
i have little concern when applying holo theme on devices api >= version 11 custom buttons bigger (in height, width seems same) this without holo them this holo them may tell me causing this? , if possible keep same button size without holo theme? ps: button shape: <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" > <solid android:color="#f000" /> <stroke android:width="1px" android:color="#bb000000" /> <padding android:bottom="7dp" android:left="10dp" android:right="10dp" android:top="7dp" /> <corners android:bottomleftradius="5dp" android:bottomrightradius="5dp" android:topleftradius="5dp" android:toprightradius="5dp" /> <gradient ...

visual c++ - Environment passed in from Python is different in release and debug modes -

i'm building python plugin, using visual studios 2012, , generating 64 bit code. in addition, we're using bloomberg library blpapi . in python module loads our plugin, set environment variable before loading; code looks like: import os import imp directory = os.path.dirname(os.path.realpath(__file__)) os.environ['__python_sys_path_for_prog__'] = directory fp, pathname, description = imp.find_module('pyprog', [ directory ]) if fp not none: try: _mod = imp.load_module('pyprog', fp, pathname, description) finally: fp.close() there file pyprog.pyd in path, , works fine. if import blpapi before, however, works in debug mode, not in release: function initpyprog basically: pymodinit_func initpyprog() { try { char const* syspath = getenv( "__python_sys_path_for_prog__" ); std::string path = syspath != null ? syspath : ""; bool verbose = getenv( "__python_prog_verbose__...

How to optimize all javascript files in a directory with requirejs -

i have folder structure this: . ├── autocomplete │   ├── core.js │   ├── search.js │   └── user.js ├── build.js ├── collapsible_lists.js ├── griffgrabber │   ├── canvasobject.js │   ├── cargame.js │   ├── car.js │   ├── griffdrawer.js │   ├── keylistener.js │   ├── run.js │   └── victim.js ├── main.js ├── newsfeed.js ├── require.js ├── shortcut.js └── sidebar.js 3 directories, 20 files main.js startup file. file requires couple of files, not of them. rest of files included with <script> require(['shortcut'], function(shortcut){ // ... }) </script> in html files. this build.js file far: { baseurl: ".", name: "main", out: "main-built.js", } but includes files required main.js. possible optimize javascript files in 1 run? (to expand @ryan lynch's suggestion) : use include option, per documentation: you can explicitly add modules not found via optimizer's static analysi...

python - How to establish a connection from a wxpython desktop app to a remote msyql database? -

i'm writing desktop app in wxpython. simplicity sake let's it's frame button in it. when clicks button record inserted remote mysql table public ip click made from. create table clicks( click_id int(10) unsigned not null auto_increment, ip_address varchar(128), exec_datetime datetime, primary key(click_id) ) what best method establish connection remote mysql database , insert record desktop application? one way wrap mysql calls in web service (api). clients make web requests webservice through http/s creating web service allow control authorization/authentication of clients. (the wxpython app) this can because port 80/443 (http/https) open. if connect directly mysql database using python, there possiblity port not open. also, using webservice can better throttle/control requests database, gives additional place cache used data, direct connection might not facilitate.

underscore.js - Attaching el to an existing element in Backbone.js but nothing being rendered? -

i'm trying inject backbone view existing div id of "myview". index1a.html: <!doctype html> <html> <head> <meta charset="utf-8"> <title>hello-backbonejs</title> </head> <body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"> </script> <script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script> <script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"> </script> <script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script> <script src="1a.js"></script> <div id = 'myview'></div> </body> </html> 1a.js (function($){ var myview = backbone.view.extend({ // el: $('body'), // el: '#myview', initialize: function(){ ...

What's the purpose of javascript parameters that are overwritten in the function? -

i have code snippet include in project, , i'd know if there's purpose why written or if should clean up. there optimization trick don't know about? here's (sanitized) code snippet. notice a,b,c,d passed in , assigned in function. (function (a, b, c, d) { = '//url/to/js/file.js'; b = document; c = 'script'; d = b.createelement(c); d.src = a; d.type = 'text/java' + c; d.async = true; = b.getelementsbytagname(c)[0]; a.parentnode.insertbefore(d, a); })(); i found this answer after writing question up. reason? that way can make local scoped variable without explicitly declaring using var statement. iirc it's commonly used code minifiers.

Android- XML database from the ASSETS -

i want pull out data xml database placed in assets folder. // sample of database <?xml version="1.0" encoding="utf-8" ?> <levels> <level id ="0"> <start>3,2</start> <one>1,1</one> </level> <level id ="1"> <start>3,2</start> <one>4,1</one> </level> </levels> i want data pull id example id=0 returns < start>3,2< /start> < one>1,1< /one>. there 1 problem - dont know how please me //--------------------------------------------------------------------------------------- edit : im getting error please check xmlparser class: package com.example.com.worfield.barak; import java.io.ioexception; import java.io.stringreader; import javax.xml.parsers.documentbuilder; import javax.xml.parsers.documentbuilderfactory; import javax.xml.parsers.parserconfigurationexception; import org.apache.htt...

CakePHP saveAssociated not saving HasMany Through Model Data -

i'm trying associated models in cakephp 2.3 save properly, i'm having issues. i'm storing posts, , want know links in posts. each of links, i'd store anchor text if available. database set in following diagram. database diagram http://derekperkins.com/wp-content/uploads/cakephp-database.png anchor model class anchor extends appmodel { public $hasmany = array( 'postsurl' => array( 'classname' => 'postsurl', 'foreignkey' => 'anchor_id', 'dependent' => false ) ); public function save($data = null, $validate = true, $fieldlist = array()) { $id = anchor::find('first', array( 'fields' => array('id'), 'recursive' => -1, 'conditions' => array('anchor' => $data['anchor']) )); ...

c# 4.0 - Task.wait in task array -

i need execute line completed after tasks completed.i thought task.waitall(tasks) take care after executing callback method completed line gets executed.is there way block main thread untill task aray completes it. taskpprcessor.batchstart(definition) public void batchstart(list<taskdefinition> definition) { int = 0; tasks = new task[definition.count]; definition.foreach((a) => { tasks[i] = task<taskresult>.factory.startnew(() => (taskresult)a.methodtocall.dynamicinvoke(a.arguments)); tasks[i].continuewith(task => runtaskretobjresultins((task<taskresult>)task, a.completemethod)); i++; }); task.waitall(tasks); console.writeline("completed"); } i try this: public void batchstart(list<taskdefinition> definition) { task.waitall( definition.select (a => task<taskresult...

WPF Prism MVVM - Same "Partial View with Command" in one page, how to subscribe the Command? -

my project using mvvm design pattern using prism , unity, following famous prism video brian lagunas, video didn't mention how create/use partial view, user control used in other user controls. i'm trying create custom partial view(usercontrol) can reused in other page (user control). example, view contains "browse" button binding selectfilecommand , publish file path when done. if have 2 of view in 1 page, how can subscribe correct command? both commands called same name. for using partial view: register view type in module this: container.registertype<ipartialview, partialview>(); and use view directly in page this: <views:partialview datacontext="{binding partialviewmodel}" /> i'm not sure if correct way implement prism mvvm pattern. please let me know if wrong idea, , how implement these kind of partial view. thanks lot. i'm not sure understand need i'll give try. if partial view in module, first, ca...

Rails 4 strong params error: no implicit conversion of Symbol into String -

i importing data spreadsheet app database. the data parsed rows. each parsed row looks like: {:department=>{ :school=>"graduate school of business", :name=>"graduate school of business", :program=>"mba program", :url=>"http://www.gsb.stanford.edu/mba", :intro=>"the stanford mba program two-year, full-time, residential program.", :students_number=>"approximately 80 annually", :students_with_aids_number=>nil, :gre_scroe=>nil, :toefl_score=>nil, :world_rank=>nil, :us_rank=>nil, :without_aid_deadline=>nil, :with_aid_deadline=>nil, :salary=>nil, :institute_id=>1} } to create department: # att hash shown above department = department.new(department_params(att)) if !department.save puts "error: \n department can't save: #{department.errors.full_messages}" end def department_params params params.require(:de...

java - How do I handle digits in a reverse polish notation calculator? -

import java.util.arraylist; import java.util.linkedlist; import java.util.list; import java.util.scanner; import java.util.stack; public class postfixeval { static scanner input = new scanner(system.in); static string expression; static stack<integer> calcstack = new stack<integer>(); static list<string> expressionlist = new arraylist<string>(); static boolean flag = false; public static void main(string[] args) { system.out.print("enter expression: "); while (flag == false){ expression = input.next(); system.out.println(""); expression = whitespaceremover(expression); if (expression.substring(expression.length() - 1) == ";"){ expressionlist.add(expression); } else if (expression.substring(expression.length() - 1) == "@"){ expressionlist.add(expression); flag = true; ...

jquery - Post with AJAX and PHP - How is this really working -

1.) post content (i.e. text) id , variables in php in post.php file? 2.) call php, "if ($_post['promotion'])". how define _post in ajax , in php? basically want php make post. html: <input type="text" id="promo_headline"> <button id="btnpostpromotion">post promotion</button> jquery: $(document).ready(function(){ $('#btnpostpromotion').click(function() { $.ajax({ type : 'post', url : 'post.php', datatype : 'json', data: $('#promo_headline').val(), success : function(data){ if (data.error === true) $('#errormodal').modal("show"); }, error : function(xmlhttprequest, textstatus, errorthrown) { $('#errormodal').modal("show"); } }); return false; }); }); php: if ($_post['promotion']) { $pr...

How to encode javascript function -

how can encode parameters in javascript? this function , parameter called newvalue <script> function selectchanged(newvalue) { location.href="tester?restid=" + newvalue; } </script> this how tried adeneos suggestion window.location.href = "tester?restid=" + encodeuricomponent(newvalue); but not work. this getting: tester?restid=38619 this want want tester%3frestid%3d38619%21 function selectchanged(newvalue) { window.location.href = encodeuricomponent("tester?restid=" + newvalue); }

c++ - setRoomName does not change the variable roomName -

im taking in rooms text file , trying use information in variables after take info in add linkedlist, search room want room id , use setroomname = room finds name. isnt working... can see problem ? here code: #include "rooms.h" #include "doublylinkedlist.h" #include <string> using namespace std; doublylinkedlist<rooms> roomslist; doublylinkedlistiterator<rooms> itr = roomslist.getiterator(); rooms :: rooms() { this->roomid = 0; this->roomname = ""; this->roomexits = ""; } rooms :: rooms(int roomid,string roomname,string roomexits) { this->roomid = roomid; this->roomname = roomname; this->roomexits = roomexits; } int rooms :: getroomid() { return roomid; } void rooms :: setroomid(int roomid) { this->roomid = roomid; } string rooms :: getroomname() { return roomname; } void rooms ::setroomname(string roomname...