Posts

Showing posts from January, 2012

ruby on rails - Generate month end dates for last 12 months -

i need method generates array containing month end date each of past 12 months. i've come solution below. works, however, there's more elegant way solve problem. suggestions? there more efficient way generate array? advice appreciated. require 'active_support/time' ... def months last_month_end = (date.today - 1.month).end_of_month months = [last_month_end] 11.times month_end = (last_month_end - 1.month).end_of_month months << month_end end months end usually when want array of things start thinking map . while you're @ why not generalize such method can n months wish: def last_end_dates(count = 12) count.times.map { |i| (date.today - (i+1).month).end_of_month } end >> pp last_end_dates(5) [sun, 30 jun 2013, fri, 31 may 2013, tue, 30 apr 2013, sun, 31 mar 2013, thu, 28 feb 2013]

c# - TPL Dataflow. Cannot attach BatchBlock to ActionBlock. Type argument cannot be inferred from usage? -

i have batch block as var batchblock = new batchblock<ienumerable<string>>(10000, new groupingdataflowblockoptions { cancellationtoken = cancellationtoken, taskscheduler = taskscheduler } ); and actionblock var actionblock = new actionblock<ienumerable<string>>(enumerable => { (var = 0; < enumerable.count(); i++)

java - What is the proper separation of responsibilities between TableCellRenderer and TableModel when using JTables? -

i working on part of application displays tables statistical data video files represented class frameinfo. after had table model including formatting, refactored other extreme , had table model return frameinfo instance each row , let cellrenderer decide field render , how each column. great nice things switching display of e.g. timecode values between ticks, seconds or timecodes ("00:01:02:03") repaint. happy until copied , pasted table contents gdocs spreadsheet , noticed got output of tostring() of model objects in cells (which logical when started thinking not want). my options, far can see them now: 1) put model pros: have in clipboard displayed, when copy cons: - means triggering model events when switching display mode of timecodes - writing highlighters (i using jxtables btw.) become messy again, have string matching, can use model objects 2) leave , build custom copy action uses renderer , extracts text rendered label pros: - table code stays clean

classpath - Purpose of buildScript in Gradle -

i new gradle , reading documentation don't understand parts of it. 1 of these parts connected buildscript block. purpose? if build script needs use external libraries, can add them script's classpath in build script itself. using buildscript() method, passing in closure declares build script classpath. buildscript { repositories { mavencentral() } dependencies { classpath group: 'commons-codec', name: 'commons-codec', version: '1.2' } } ok difference with: repositories { mavencentral() } dependencies { compile group: 'commons-codec', name: 'commons-codec', version: '1.2' } for example, why necessary use buildscript ? the buildscript block determines plugins, task classes, , other classes available use in rest of build script . without buildscript block, can use ships gradle out-of-the-box. if additionally want use third-party plugins, task classes, or other classes (in build script

select - MySQL insert into table with auto-increment while selecting from another table -

i have table auto-increment primary key: create table rt_table ( rtid int primary key auto_increment, rt_user_id bigint, /*user being retweeted*/ rt_user_name varchar(70), /*user name of rt_user_id*/ source_user_id bigint, /*user tweeting rt_user_id*/ source_user_name varchar(70), /*user name of source_user_id*/ tweet_id bigint, /*fk table tweets*/ foreign key (tweet_id) references tweets(tweet_id) ); i wish populate table parts of table: insert rt_table select rt_user_id, (select user_name users u u.user_id = t.rt_user_id), source_user_id, (select user_name users u u.user_id = t.source_user_id), tweet_id tweets t rt_user_id != -1; i error says number of columns not match up, because of primary key (which auto-incremented value , not need set). how around this? you need explicitly list columns in insert statement: insert rt_table (rt_user_id, rt_user_name, source_user_id, source_

Accessing route URLs in the controller in ASP.Net MVC -

asp.net mvc has nice features making sure have correct url route want. can use htmlhelper class correct url views:- @html.routelink("link text", new {controller = "articles", action = "tag"}) now great. however, find myself in situation want know url not writing view. question best way information in controller? have read various posts show how sneakily create instance of htmlhelper there must more straightforward way of doing this. thanks. you can try urlhelper.routeurl . urlhelper accessible via url property on controller.

css - Notication bars like Facebook -

i'm looking notification bar of facebook; ones how many "friend requests", "notification" or "messages" have. there fancy implemented bootstrap, foundation or... can use? or need use css and.. create own? thanks bootstrap have concept built in, calls them badges: http://twitter.github.io/bootstrap/components.html#labels-badges seems has has idea before library called cakephp , can't see easy way pull information out: https://github.com/beeman/cakephp-bootstrap-notifications/blob/master/readme.md i found nice example snippet here, notification badge on left rather in top right: http://jsfiddle.net/wbtf8/1/ which has markup this: <div class="navbar" style="position: static;"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".navbar-inverse-collapse">

C# Multithreading Pass by value or reference? -

i saw piece of code online states calling thread causes non-deterministic output "0223557799" or of kind.(you point) for (int = 0; < 10; i++) new thread (() => console.write (i)).start(); this reason given this: "the problem variable refers same memory location throughout loop’s lifetime. therefore, each thread calls console.write on variable value may change running!" but, conventionally speaking when argument passed value - each new thread call should send i incremental order right ? if values pass reference above mentioned reason holds good. so, in c# multi-threading, values pass reference ? i'm new c#,please understand if question naive. there more 1 problem here. starts for() loop variable capture problem, described in blog post . tends produce "10" output, there's no guarantee happens since thread may execute while loop still being iterated. but program suffers core threading problem, there's no guara

curl - php Getting value from standalone javascript -

i'm using curl remote page.. have local js file.. called main.js . i want execute js file on curl page. my main.js file outputs result json string. i assign string in php variable. can me? to execute javascript need javascript engine. can in headless browser phantomjs ,or can try v8 js extension php

git - Remote repository isn't up to date -

when try push changes remote bare repository git says it's date use 'post-receive' hook loads files directory can doesn't it's date. can find out what's wrong? my code post-receive hook: #!/bin/sh git_work_tree=/var/www/empirik/data/www/mywebsite git checkout -f try 1) sure have correct file permission. 2) git add /path/your_files git commit -m "changes" git push origin master ( check in correct repo git branch )

javascript - Prevent browser from keeping iframe url when reloading the parent -

i have form inside iframe. user saved data redirect iframe page nothing more reloading main page (as other content depends on inserted inside iframe). data outside iframe ist updated , form should appear again. the problem: @ least firefox (haven't tested in other browsers yet) keeps "new" url of iframe redirected page , not 1 set sourcecode. similar autocompletion input fields. i reload parent.location.reload(); is there maybe way force real reload without keeping information history of containing iframes? btw: may use jquery if helps. thanks. you try along these lines ( http://jsfiddle.net/akykz/ ): document.queryselector('button').addeventlistener('click', function() { document.queryselector('iframe').setattribute('src', document.queryselector('iframe').getattribute('src')); window.top.location.reload(); return false; }, false); in fiddle, click link in iframe, , hit reload button.

html - Safari Allows Text to Flow into Footer Only when Length Doesn't Cause Scrolling -

i have problem appears in safari 6.0.5 on os x 10.8.4 under condition. works fine in firefox , chrome on os x under tested conditions. haven't tested ie or on windows. the problem 3 column layout uses floats position columns. in example code included, if text in third column short enough allow space between , footer , entire page fits in viewport, displays correctly. if bit longer, column text flows footer. if long enough flow out of viewport causing scrolling, works correctly. can test moving bottom of browser window , down. the page has code creates sticky footer. see of code in #force-full-page , #push in style.css. don't think have problem if wasn't using it. given works in firefox , chrome, suspect safari bug. there wrong code , got lucky other browsers? if bug, there work in safari? don't have problem pages don't use floats. i remember there site load code people test. don't remember name of it. still around? if so, i'll load code it. the

php - How to upload file to FTP using cron jobs -

i want able upload csv file once day (locally pc) ftp. going insert csv file mysql table. i've created cron job pick csv , insert database, i'm struggling how figure out how pick file on loacl pc , upload ftp. has got ideas? thanks adi you can using ftp extension in php, like: $conn = ftp_connect("destination.host", 21) or die("failed connect"); ftp_login($conn, $user, $pass) or die("failed login"); ftp_put($conn, "/path/on/ftp/server", "/path/on/your/local", ftp_binary) or die("failed upload); more details: http://us2.php.net/manual/en/book.ftp.php

javascript - getStylesheet depending if class exists -

i need add css stylesheet if css class exists in page. i.e. editing following js: <script> <!-- function getstylesheet() { var currenttime = new date().gethours(); if (0 <= currenttime&&currenttime < 5) { document.write("<link rel='stylesheet' href='night.css' type='text/css'>"); } if (5 <= currenttime&&currenttime < 11) { document.write("<link rel='stylesheet' href='morning.css' type='text/css'>"); } if (11 <= currenttime&&currenttime < 16) { document.write("<link rel='stylesheet' href='day.css' type='text/css'>"); } if (16 <= currenttime&&currenttime < 22) { document.write("<link rel='stylesheet' href='evening.css' type='text/css'>"); } } getstylesheet(); --> </script

git - Handling project files when multiple users are commiting -

i'm not sure workflow supposed when working other users making changes repository. here's situation: repository created colleague , makes first commit. ended using git clone project onto computer work on. after working on project, commits bunch of updated files. now, repository different have locally. have not committed own changes yet not know best way proceed. commit , whatever changes made automatically added file along colleague's changes? however, locally not have updated files repository... you have fetch changes remote repository local repository can know them. can either git fetch origin to fetch changes, around , merge/rebase. or: git pull optional --rebase . this way merge or rebase local changes on top of incomming changes upstream.

c++ - CL_MEM_ALLOC_HOST_PTR slower than CL_MEM_USE_HOST_PTR -

so i've been playing around opencl bit , testing speeds of memory transfer between host , device. using intel opencl sdk , running on intel i5 processor integrated graphics. discovered clenqueuemapbuffer instead of clenqueuewritebuffer turned out faster 10 times when using pinned memory so: int amt = 16*1024*1024; ... k_a = clcreatebuffer(context,cl_mem_read_only | cl_mem_use_host_ptr, sizeof(int)*amt, a, null); k_b = clcreatebuffer(context,cl_mem_read_only | cl_mem_use_host_ptr, sizeof(int)*amt, b, null); k_c = clcreatebuffer(context,cl_mem_write_only | cl_mem_use_host_ptr, sizeof(int)*amt, ret, null); int* map_a = (int*) clenqueuemapbuffer(c_q, k_a, cl_true, cl_map_read, 0, sizeof(int)*amt, 0, null, null, &error); int* map_b = (int*) clenqueuemapbuffer(c_q, k_b, cl_true, cl_map_read, 0, sizeof(int)*amt, 0, null, null, &error); int* map_c = (int*) clenqueuemapbuffer(c_q, k_c, cl_true, cl_map_write, 0, sizeof(int)*amt, 0, null, null, &error); clfinish(c_q);

assembly - When are the carry flags set? -

what meant "applying neg instruction nonzero operand sets carry flag." why substracting 2 1 set carry flag? 00000001 (1) + 11111110 (-2) [in 2-complement form] --------------------- cf:1 11111111 (-1) [ why carry flag set here???] you view neg a equivalent sub 0, a . if a non-zero, set carry flag (as always result in unsigned overflow).

java - How to get both the attributes and the data list with XmlList -

i have xml files contain elements so: <element attribute1="a" attribute2="b" attribute3="c"> b c d e f g </element> is there way both attributes , value list? i use @xmllist list [a, b, c, d, e, f, g], not have attributes. make class element , use @xmlattribute , @xmlvalue, value not list. if there no way this, make class element in getter method returns string value array or list, , simple enough, wondering if there correct way have xml unmarshalled in first place. the @xmlvalue can applied list property. mapping list items represented space separated list in xml. can following: element import java.util.list; import javax.xml.bind.annotation.*; @xmlrootelement @xmlaccessortype(xmlaccesstype.field) public class element { @xmlattribute private string attribute1; @xmlattribute private string attribute2; @xmlattribute private string attribute3; @xmlvalue private list<string&g

postgresql - How do you filter records by the time of day in Rails? -

i have bunch of records have datetime stored on them used pull out time of day (i.e. 6:00 p.m.) , i'd filter them time of day. example, i'd records time of day between 10:00 a.m. , 2:00 p.m., regardless of day timestamp for. is there way in rails? realize datetime might not easiest/best way store data, i'm open changing that. also, i'm using postgres. with postgres can use typecasting convert datetime/timestamp fields time, example: select * posts created_at::time between '10:00:00' , '14:00:00'; so, in rails, should able do: post.where('start_at::time between ? , ?', '10:00:00', '14:00:00') and postgres smart enough understand am/pm format also: post.where('start_at::time between ? , ?', '10:00:00 am', '02:00:00 pm')

php - i have issue with POST, (im new and need help) -

im following book tutorial , im stuck. here html orderform (orderform.html) <!doctype html> <html> <head> </head> <body> <form action='processorder.php' method="post"> <table border=0> <tr bgcolor=#cccccc> <td width=150>item</td> <td width=15>quantity</td> </tr> <tr> <td>tires</td> <td align=center><input type="text" name="tireqty" size=3 maxlength=3></td> </tr> <tr> <td>oil</td> <td align=center><input type="text" name="oilqty" size=3 maxlength=3></td> </tr> <tr> <td>spark plugs</td> <td align=center><input type="text" name="sparkqty" size=3 maxlength=3></td> </tr> <tr> <td colspan=2 align=center><input type=submit value="submit order"></td> </td> </table&

sql server - sql command error in C# -

i have written code retrieve information 2 tables in database. when run error column 'eaten_food.cardserial' invalid in select list because not contained in either aggregate function or group clause. code: private void button8_click(object sender, eventargs e) { using (sqlconnection con = new sqlconnection(wf_abspres_food.properties.settings.default.dbconnectionstring)) { con.open(); sqldataadapter = new sqldataadapter("select eaten_food.cardserial , eaten_food.date , eaten_food.turn , avb_food_count , reserve_count reserve inner join eaten_food on reserve.cardserial = eaten_food.cardserial group eaten_food.date", con); sqlcommandbuilder comdbuilder = new sqlcommandbuilder(a); datatable t = new datatable(); //t.locale = system.globalization.cultureinfo.invariantculture; a.fill(t); bindingsource3.datasource = t; /// bind grid view binding sou

android - How to dynamically create a SurfaceView with rounded corners -

i'm working on xamarin.android project involves dynamically creating view hierarchies represent controls. 1 such control uses androidgameview class, inherits surfaceview , allows drawing opengl es. i'm trying figure how give view rounded corners. i've tinkered overriding ondraw method or applying drawable background clip, haven't had success. this question seems similar goal, not figure out how dynamically instead of using axml. possible dynamically give surfaceview rounded corners? there no direct support on android. i think best approach create rounded rectangle shape want large triangle fan defines rounded corners , position behind scene , make opaque. format surfaceview must bitmap.config.argb_8888 , use setopaque(0) , setalpha(1.0). glclearcolor() must transparent black blend android canvas: glclearcolor(0.0f, 0.0f, 0.0f, 0.0f); glclear(gl_depth_buffer_bit | gl_color_buffer_bit);

javascript - Socket.io does not connect when using $location.path() in angular -

i want use socket.io @ 1 section of webapp. use socket.io's set('authorization', fn) handshaking current context(express session , page-id). works great when refresh current page, not when routing handled $location.path(url). socket.io code(view controller): .controller('viewctrl', function ($scope, $routeparams, $http, $location, socket) { socket.connect('', { query: 'id=' + $routeparams.id }); socket.emit('msg', { data: 'key'}); //debug socket.on('connect', function(){ console.log('socket connected'); }); socket.on('disconnect', function(){ console.log('socket disconnected'); }); ... routing code(main controller, frontpage): if (data.owner == "yes") $location.path('/view/' + $scope.id()); routing of course secured server-side also. socket.io service: .factory('socket', function ($rootscope) { var disconnecting = false; var socket =

arrays - Creating table with .NET using httpwebrequest for information -

hello problem need information server , put array , , information out of it this code used work , doesn't no-longer me , gives me first-chance exception: dim table() string = split(responsefromserver, ":") table_update = split(table(0), "<pre>") this code should responsefromhttprequest , seperate ":" because output server this: 01010:username:-sessionid , need third thing arraylist array(3) should give me sessionid , doesn't work , , need working minecraft login system , have tried 1 hour , , can't figure out how it. any appriciated :)

PHP Drop Down Boxes always Isset -

hi have 2 drop down boxes used filter data mysql table, problem boxes show if set when use isset determin if of them have values selected. here code drop boxes. <?php if (isset($_post['referrer']) && $_post['referrer'] != "referrer") { $select = $_post['referrer']; } ?> <select name="referrer"> <option value="">referrer</option> <?php // records database (table "name_list"). $list=mysql_query("select distinct referrer masterip_details country_code='gb' , trim(ifnull(referrer,'')) <> '' order referrer desc"); // show records while loop. while($row_l

c# - Why does RedirectStandardInput has no effect when ProcessStartInfo.CreateNoWindow is set to true? -

i use system.diagnostics.process interact third party console application of stdin/out/err have been redirected (the external program written in c++ , not have no control on it). processstartinfo info = new processstartinfo(filename, arg); info.createnowindow = false; // <- if true, stdin writes don't make through info.useshellexecute = false; info.redirectstandardinput = true; info.redirectstandardoutput = true; info.redirectstandarderror = true; var proc = new process() { startinfo = info }; proc.outputdatareceived += new datareceivedeventhandler(myoutputhandler); proc.errordatareceived += new datareceivedeventhandler(myerrorhandler); proc.start(); proc.beginoutputreadline(); proc.beginerrorreadline(); later... proc.standardinput.writeline("some-short-command"); works ok in test console app when info.createnowindow = false; has no effect when info.createnowindow = true; the output , error redirection work fine in both cases. the above code part o

How to design a database for modular widgets -

i'm stumped , hoping smart people out there can me! my knowledge of database design middle of road @ best. enough me in trouble really. i'm programmer first , foremost. i'm trying build website , design of back-end database has got me stumped. i'm going give contrived example here sake of explanation, example spot on need achieve. image minute building database old school fans of game car wars, or similar. in game player can pick 1 of several base cars, , customize use in game. there attributes every base car have player customize, such engine, transmission, , armor. every car has these slots, , player's can drop appropriate items these slots. in addition these common slots, each car has n number of mounts. varies per car, though every car has @ least one, , large car have dozen or more. players can place weapons, or utility items these mounts. once player has configured car, saved build. build defines, base car chose, choices engine, transmis

jquery - Problems with Chaining in javascript -

i have following problem, i'm trying make small chained. (function(window){ window.de=de={} de.one=function(s){if(s){var y=document.getelementbyid(s); return y;} return this;} de.two=function(s2){alert(s2); return this;} })(window) this try to: de.one("id").two("hello!"); but console gives me error: typeerror: object # has no method 'two' to give idea: live demo (function(window){ var mylibrary = (function( s ) { var d = document, e = d.getelementbyid( s ), methods = { 1 : function(val){ alert(val); return this; // maintain chainability }, 2 : function(val){ alert(val); return this; // maintain chainability }, css : function( property, val){ if(!val && typeof property == "object" ){ // styles in object notation for(var key in property){ e.style[key] = proper

javascript - $scope.$watch isn't firing after load in angular.js -

i'm using angular.js , trying use $watch fire function when variable changes. fires when data loaded, not after. i'm not sure going on here? code pasted below: function gradechart($scope, $http) { $http.get('studentdata.json').success(function(data) { $scope.students = data; }); $scope.$watch('students',function(change){ console.log('this fires on load not after'); }); } it not clear code runs "after" , updates $scope.students . however, here 2 common problems related updating $scope arrays: if reassign $scope.students new array, $watch may still looking @ previous array (reference). try using angular.copy() in "after" code: angular.copy(data, $scope.students); if changing 1 of elements of array, you'll need use either $watchcollection (if available in version of angular using) or check object equality instead of reference (note 3rd parameter): $scope.$watch('students&#

java - running an algorithm without a Main class? -

i'm learning java introduction java programming 9th ed. liang y. d. , having difficulty 1 of examples, pertaining arrays. execute sorting procedure following: public class selectionsort { public static void selectionsort (double[] list) { (int = 0; < list.length - 1; i++) { double currentmin = list[i]; int currentminindex = i; (int j = + 1; j < list.length; j++) { if (currentmin > list[j]) { currentmin = list[j]; currentminindex = i; } } if (currentminindex != i) { list[currentminindex] = list[i]; list[i] = currentmin; } } } } the problem there no main (string[] args) instead have: selectionsort (double[] list) now execute above double[] list = {1, 9, 4.5, 6.6, 5.7, -4.5}; selectionsort.selectionsort(list) or other combintion, keep getting error: not find or load main class. there way

objective c - How to pass a SEL to dispatch_async method -

i trying create generic method takes sel parameter , passes dispatch_async execution, clueless how execute passed in sel. can here me please. // test.m -(void) executeme { nslog(@"hello"); } - (void)viewdidload { [super viewdidload]; sel executesel = @selector(executeme); [_pinst common_dispatch: executesel]; } // common.m -(void) common_dispatch:(sel) aselector { dispatch_async(idispatchworkerqueue, ^(void) { // how execute aselector here? }); } you need have "target" parameter on common_dispatch method since need call selector on specific object. - (void)viewdidload { [super viewdidload]; sel executesel = @selector(executeme); [_pinst common_dispatch:executesel target:self]; } - (void)common_dispatch:(sel)aselector target:(id)target { dispatch_async(idispatchworkerqueue, ^(void) { [target performselector:aselector]; }); } btw - standard naming conventions state method names shou

sql - python: update an existing sqlite db -

have python script creates sqlite database: import sqlite3 con = sqlite3.connect('some.db',detect_types=sqlite3.parse_decltypes) con: cur = con.cursor() cur.execute("create table title(id int, ...)") and later populates db content list: <id> = <whatever> <var1> = <you point> altogether = (id, var1...) cur.execute("insert title values(?,?,...)", altogether) con.commit() i want write modified version of script takes existing some.db , updates it, if id doesn't exist in database. how i: open some.db read/write update values only query db make sure id of item i'm iterating through not exist in db? way i'm populating variables making api calls external service i'd able skip if entry in db. same way did. don't. make column unique , handle exception on insert .

Why setting src of img by jquery in Django does not have to include {{MEDIA_URL}} -

just curious question. in order display image image in {{media_url}}, need in django: <img src="{{media_url}} + file-url "> with jquery, don't have include {{media_url}}: $('.myimg').attr('src',"file-url"); why? because django don't parse .js files. include media_url in js files should in base template in head section: <script type="text/javascript"> var mediaurl = '{{ media_url }}'; </script> then can use in scripts: $('.myimg').attr('src', mediaurl + file-url);

ajax - Passing array of integers to WebAPI method in URI params? -

i have following: [httpdelete] public httpresponsemessage deletefolder(int[] ids) { and i'm trying use this: delete http://localhost:24144/api/folder/1483; delete http://localhost:24144/api/folder/[1483] but these coming null within delete method - how send data without putting in body (since delete request)? my routing has this: routes.maphttproute( name: "folder", routetemplate: "api/folder/{id}", defaults: new { controller = "folder", id = routeparameter.optional } ); nevermind, found this: http://blog.codelab.co.nz/2012/10/16/passing-arrays-into-asp-net-web-api-as-parameters/ couldn't find answer on though i'll leave here. exerpt above linked page: [httpget()] public httpresponsemessage findbymembers([fromuri]int32[] ids = null) { //do stuff return request.createresponsemessage(httpstatuscode.ok); } the url http://mywebsite/api

error while compiling gcc -

i'm trying compile gcc-code-assist has code completion feature in order use emacs. have been getting error message while compilinng checking exception model use... configure: error: unable detect exception model make[1]: *** [configure-target-libstdc++-v3] error 1 make[1]: leaving directory `/home/dev/workspace/trash/gcc-code-assist-0.1-4.4.4' make: *** [all] error 2 i'm running ubuntu 12.04 64bit can overcome problem i found right way compile ... didn't have knowledge of how compile gcc (my first time) after reading through faq of building gcc found problem. turned out had run configure script , make outside source directory ( called gcc-build) directory list looked this gcc-source/ gcc-build/ then compiled smoothly here's link faq http://gcc.gnu.org/wiki/faq#configure

javascript - discrepancy between Float32Array and DataView -

thought understood how float32array works, looks i'm not quite there. in simplest example possible: buffer = new arraybuffer(128); dataview = new dataview(buffer); floatarray = new float32array(buffer); dataview.setfloat32(8, 7); console.log(floatarray[2]); //prints gibberesh the way understood it, data view should set float starting @ 8th byte 7, third float in float array expect 7. what missing here? thanks this makes work, last parameter being littleendian dataview.setfloat32(8, 7, true); this might better, although can't sure. presumably float32array uses system's littleendian, while dataview can use either. var littleendian = (function() { var buffer = new arraybuffer(2); new dataview(buffer).setint16(0, 256, true); return new int16array(buffer)[0] === 256; })(); dataview.setfloat32(8, 7, littleendian);

json - Is there a data serialization language that allows objects to be used as the name for another object? -

i have found json , yaml both lacking. i wish (in yaml): nodes: node: "name node": - data - - - node (in json): {"nodes": {"node":"name node": { ["data","for","this","node"] }} } but these both invalid in data serialization languages. does know of data serialization language can use object name object, basically? think it's stupid can't in yaml, though forgive json since designed simple opposed being flexible. actually, yaml can that. try complex-key syntax (see bottom of spec section 2.2 ) nodes: ? node: name node : - data - - - node that's map single key, used key. if perhaps after list key: nodes: ? - nodename1 - nodename2 : - data - - - node

c++ - CImage to CArchive -

c++, visual studio 2010, mfc. how save lot of cimages disk , later load it? i'd use carchive, << , >> operators can't used cimage. i think should serialize object if want write them disk,when want upload them memory can read them , unserialize. you can use google's protobuf serialization or boost_serialization !

How to list the Connected USB Port Number using Vendor id and product id using java -

what best api in java display connected usb port number using vendor id , product id? you can list serial ports using simple javax.comm api import javax.comm.*; import java.util.enumeration; public class listports { public static void main(string args[]) { enumeration ports = commportidentifier.getportidentifiers(); while (ports.hasmoreelements()) { commportidentifier port = (commportidentifier)ports.nextelement(); string type; switch (port.getporttype()) { case commportidentifier.port_serial: type = "serial"; break; default: /// shouldn't happen type = "unknown"; break; } system.out.println(port.getname() + ": " + type); } } } the output like com1: serial com2: serial com7: serial edit : see blog on creating , using real-time port monitoring application powered ibm lotus . using jusb for windows , for linux can read , write operation want.you find a example here

android - How to open browser as a foreground activity like some custom dialog? -

i using below code onclick of listview opens link in browser. there way open same browser in catchy small foreground activity custom dialog or popup ? has tried ? public void onitemclick(adapterview<?> parent, view view, int pos, long id) { intent = new intent(intent.action_view); i.setdata(uri.parse(listitems.get(pos).getlink())); activity.startactivity(i); } thanks, advance editing code per tarun suggestion : public class listlistener extends activity implements onitemclicklistener { // list item's reference list<rssitem> listitems; // calling activity reference activity activity; public listlistener(list<rssitem> alistitems, activity anactivity) { listitems = alistitems; activity = anactivity; } /** * start browser url rss item. */ public void onitemclick(adapterview<?> parent, view view, int pos, long id) { /*intent = new intent(intent.action_view); i.setdata(uri.parse(listitems.get(pos).getlink())); ac

java - Receive entity by newest created first on Google App Engine -

Image
i'm using android , built project google app engine. when receive list of entities come me first created. need them come in opposite direction, or 100 newest. can put limit on how many receive actually. cannot find on google or stackoverflow. has questions or examples on this. quick help? you want commit dateproperty field index=true , auto_now_add=true. can sort descending on field fetch limit. there may slicker ways, tried , true. imho - idea include date_created property on every important entity. whether or not index depends on use. noted tomasz, entity ids - while ascending - not guaranteed so. not rely on them. if ever find needing progress sequentially though model, happy have "datec" field. (also idea include "version" integerproperty on every record proves useful whenever need read/write way through existing entities ensure recent property change applied them all.) given these potential benefits, ask costs keep ending each model these 2 p