Posts

Showing posts from April, 2011

ios - Passing an existing and active gesture recognizer to a modal view controller -

i want launch modal view long press, , dismiss modal view when long press cancelled. how do this? i tried passing longpressrecognizer modal view , setting delegate, didn't work. i tried simpler- detecting touchesended, mean in modal view touch ended, doesn't fire either. is there way tell modal view gesture has started; want recognize end/cancellation of gesture or touch? viewcontroller.swift import uikit class viewcontroller: uiviewcontroller, uigesturerecognizerdelegate { var buttonview:uiview! var longpressrecognizer:uilongpressgesturerecognizer! override func viewdidload() { super.viewdidload() // additional setup after loading view, typically nib. self.longpressrecognizer = uilongpressgesturerecognizer(target: self, action: "longpressed:") self.longpressrecognizer.delegate = self self.view.addgesturerecognizer(self.longpressrecognizer) // add button buttonview = uiview(frame:

python - Pygame display.update() with dirty rects still updates the whole screen -

i ran trouble pygame while making character move on screen through path on grid. collecting dirty rects .update() method not taking account updates whole screen. happens on 1 loop inside main game loop. structure this: while not done: other stuff if character should move: step in path: while not in target: update coordinates couple pixels blit , collect dirty rects update(dirty_rects) #this 1 still updates whole screen update(dirty_rects) #this 1 works correctly, updating dirty places so inner loop moves character according steps in path given, , game goes main loop. problem is, inner .update() draws whole screen again if give tiny rect rect(0,0,10,10) input. outer .update() works fine. situation destroys framerate when character moving. takes around 70ms between each frame while outer loop takes around 5ms. there can it? i using python 3.4.2 on os x, updated 3.4.3 no effect. e: tried inst

npm - 404 on sudo apt-get update 404 not found chris-lea/node.js -

i'm trying use $ sudo add-apt-repository ppa:chris-lea/node.js $ sudo apt-get update to install , update npm , nodejs most of references repository i've found out of date 2011-2013 i 404 error during $ sudo apt-get update link http://ppa.launchpad.net/chris-lea/node.js/ubuntu/dists/wheezy/main/binary-armhf/packages 404 not found is there more updated version of this? https://github.com/joyent/node/wiki/installing-node.js-via-package-manager has instructions repository supersedes old ppa. (for me, top google hit node-js ppa .) curl -sl https://deb.nodesource.com/setup | sudo bash - sudo apt-get install -y nodejs (i don't particularly recommend running stuff download without auditing first, nor have tried these instructions.)

css3 - IE Select text align center -

i'm trying put item @ select in center @ ie. doesn't works. how can it? <style type="text/css"> select { width: 400px; text-align: center; } </style> <asp:listbox id="lsb" runat="server" width="250px"> <asp:listitem text="text" /> <asp:listitem text="text" /> <asp:listitem text="text" /> <asp:listitem text="text" /> <asp:listitem text="text" /> <asp:listitem text="text" /> </asp:listbox> there no way apply style in item select on internet explorer. sad, true.

javascript - Merge table rows based on row text and class -

i have found function here , suits needs. function iterates through first column of table, , row merges similar values. then, iterates through next column, , row merges values well, while taking account merges of column before it. in way, suits need. function mergecommonrows2(table, firstonly) { var firstcolumnbrakes = []; (var = 1; <= table.find('th').length; i++) { var previous = null, celltoextend = null, rowspan = 1; table.find("td:nth-child(" + + ")").each(function (index, el) { if (previous == $(el).text() && $(el).text() !== "" && $.inarray(index, firstcolumnbrakes) === -1) { $(el).addclass('hidden'); celltoextend.attr("rowspan", (rowspan = rowspan + 1)); } else { if (firstonly == 'first only') { if (i === 1) firstcolumnbrakes.push(index);

php - Internal server error while executing insert query in laravel -

so, have started out laravel. trying create create task api, save data database. this routes.php route::any('/createticket', 'clientscontroller@store'); this controllers code(clientscontroller): public function store(request $request) { echo "abc"; //exit(); $input = $request->all('client_name', 'client_state'); clients::storeclientdetails($input); print_r($input); } this models code(clients): public static function storeclientdetails($data){ echo "stor"; $id = db::table('client_details')->insertgetid($data); print_r($data); print_r($id); } i data store function. but, nothing saved in database. what exact issue here???

winforms - How can I neatly line up right-aligned check boxes with with other controls? -

Image
the visual studio winforms designer lets snap text boxes, list boxes, buttons, , forth reasonably well. however, check box checkalign=middleright not work quite others, because has 2 components: built-in label, , check box itself. if line text other labels, check box left floating , not automatically line up. can turn off autosize , attempt size checkbox control check box lines up, touchy , thrown off custom font sizes. in example, i've almost lined check box other controls, not quite: if had several check boxes real headache, autosize turned off position of check box relative end of text, each control has individually sized pixel pixel. what's best way line check boxes other controls? one workaround not include text checkbox , instead have separate label control. however, doing lose ability click on label toggle check box. on high-resolution screen, clicking 10x10 pixel finicky, poor ux experience. add onclick event label, of course, seems solving wron

ios - Swift compatibility -

this might stupid question, trying grasp concept of new swift versions not clear me. along ios 8.3, apple introduced swift 1.2. if developing app compatible ios 8.0.0 , in swift, how new swift version affect older ios versions? can safely use newest swift syntax without concern users still on ios 8.0.0? feedback. best regards it's not stupid question. don't worry, because right swift interpreter built each individual app , not system runs on. changes in swift don't change anything: each app continues run, because contains swift version compiled with.

SSH Client Session in C# -

i trying use sshnet (renci) create ssh client session in c# application. cannot seem understand how work. essentially, can connection server, when try submit commands, not getting returned server. using sshclient , sshshell perform communication. doing wrong? ssh.connect(); var input = new memorystream(); var sr = new streamwriter(input); var output = console.openstandardoutput(); idictionary<renci.sshnet.common.terminalmodes, uint> termkvp = new dictionary<renci.sshnet.common.terminalmodes, uint>(); termkvp.add(renci.sshnet.common.terminalmodes.echo, 53); var shell = ssh.createshell(input, output, output, "xterm", 80, 24, 800, 600, termkvp, 1024); shell.stopped += delegate { console.writeline("\ndisconnected..."); }; shell.start(); while (true) { string command = console.readline(); if (command == "exit") break; sr.writeline(command); sr.flush(); thread.sleep(1000 * 1); } shell.stop();

javascript - How can I beautify JSON programmatically in angular js? -

i know how beautify json programmatically using javascript. way can achieve: var obj = {"hello":"world", "test":["hello"]} document.body.innerhtml = ""; document.body.appendchild(document.createtextnode(json.stringify(obj, null, 4))); but tried in angular js. unable achieve this. step : <div class="btn btn-primary" ng-click="test()">press</div> <textarea json-formatter rows="20" cols="140" ng-model="json"> </textarea> $scope.test=function(){ var json=json.stringify($scope.json, null, "\t"); /*here if $scope.json {"hello":"world", "test":["hello"]} json return "{\"hello\":\"world\", \"test\":[\"hello\"]}" */ } here if $scope.json {"hello":"world", "test":["hello"]} json return "{\&q

android - How to center the text inside a Button regardless of drawableLeft? -

Image
i want text centered in button . whenever add android:drawableleft xml attribute button , offsets text. how can fix that? the way managed fix setting negative number in android:drawablepadding : but i'm looking cleaner solution achieve it. so ended going lesser of evils, , that's placing drawable , text inside relativelayout : <relativelayout android:layout_width="match_parent" android:layout_height="wrap_content" style="@style/button.buttongray" android:id="@+id/share_button"> <imageview android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/btn_share"/> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:textcolor="@android:color/black" android:textstyle="bold" a

How can I generate an array of PSCustomObjects from an array of hashes in Powershell v3? -

suppose have array of hashes in powershell v3: > $hashes = 1..5 | foreach { @{name="item $_"; value=$_}} i can convert single hash pscustomobject this: > $co = [pscustomobject] $hashes[0] > $co | ft -autosize value name ----- ---- 1 item 1 > $co.gettype() ispublic isserial name basetype -------- -------- ---- -------- true false pscustomobject system.object so far, good. problem occurs when try convert entire hash array pscustomobjects in pipeline: > ($hashes | foreach { [pscustomobject] $_})[0].gettype() ispublic isserial name basetype -------- -------- ---- -------- true true hashtable system.object as see, i'm getting array of hashtable objects, not pscustomobjects . why different behavior, , how can accomplis

algorithm - Finding a majority of unorderable items -

i have 1 problem finding solution task. you have n students , n courses. student can attend 1 course , 1 course can attended many students. 2 students classmates if attending same course. how find out if there n/2 classmates in n students this? conditions: can take 2 students , ask if classmates , answer can "yes" or "no". , need in o(n*log(n)). i need idea how make it, pseudo code fine. guess divide list of students merge sort, gives me logarithmic part of complexity. ideas great. first, pair off each student (1&2, 3&4, 5&6... etc), , check , see pairs in same class. first student of pair gets "promoted". if there "oddball" student, in own class, promoted well. if single class contains >=50% of students, >=50% of promoted students in class. if no students promoted, if single class contains >=50% of students either first or second student must in class, promote both of them. leads cas

xslt - Convert String to Tree Structure -

i'm new xslt (1.0), anyhow want start difficult .... given source xml stringvalue "432565" ( <line>432565</line> ) output should xml <element id="1">4</element> <element id="2">43</element> <element id="3">432</element> <element id="4">4325</element> <element id="5">43256</element> <element id="6">432565</element> currently i've recursive template <xsl:template match="line" name="letters"> <xsl:param name="text" select="."/> <xsl:if test="$text != ''"> <xsl:variable name="letter" select="substring($text, 1, 1)"/> <element> <xsl:value-of select="$letter"/> </element> <xsl:call-template name="letters"> <xsl:with-param na

d3.js - Hyperlinks in Treemap Layout -

i have been trying follow guidelines on hyperlinks in d3.js objects: indented tree , original scripts 2 layouts different cannot wrap head around it.. i need simple thing: attach links each node in treemap layout i tried adding d3.json("my_json.json", function(error, root) { var node = div.datum(root).selectall(".node") .data(treemap.nodes) .enter().append("div") .attr("class", "node") .call(position) .style("background", function(d) { return d.children ? color(d.name) : null; }) .text(function(d) { return d.children ? null : d.name; }); node.append('a') .attr("xlink:href", function(d){return d.url;}) }); but not work.. can please me out it? update: tried switching a , div elements, still no clickable objects. var node = div.datum(root).selectall(".node") .data(treemap.nodes) .enter() .append('a') .att

Neo4jclient C# get all nodes and relationships to JSON -

i want nodes , relationships json. if execute in neo4j-browser want. ( http://neo4j.com/developer/guide-data-visualization/ ) :post /db/data/transaction/commit {"statements":[{"statement":"match path = (n)-[r]->(m) return path", "resultdatacontents":["graph"]}]} using neo4jclient in asp.net application, , don't know how translate that. have checked example project have on site, doesn't me. eventually use result present d3. cant json work. i think you're looking like: http://geekswithblogs.net/cskardon/archive/2013/07/23/neo4jclient-ndash-getting-path-results.aspx the code on page older cypher way - aside using .start no longer need - should work you.

java - 2D arrays issue -

i have problem 2d array. want print 20 lines a..j letters on each line. can't print row 9, 19, 20 following code. also, code prints 19x9 lines of null. ideas?! thanks. that's code: public class cinema_seats { string[][] seats = new string[20][10]; for(int row=0; row<seats.length-1; row++){ for(int column=0; column<seats[row].length-1; column++){ if(row!=0) system.out.print("row" + row + " " + 'a' + " " + 'b' + " " + 'c' + " " + 'd' + " " + 'e' + " " + 'f' + " " + 'g' + " " + 'h' + " " + 'i' + " " +'j' + "\n") else system.out.println(); row++; } system.out.println(); } for(int row=0; row

Unexplained non-Android entry in my Android app Google Analytics page -

i observed output of google analytics android app , noticed following strange "macintosh intel 10.10" entry: mobile app analytics chart http://transsymmetrix.com:8080/tmp/googleanalyticsreport.png see yellow segment representing 9.6% of os versions. have idea why macintosh os showing android os version ???! thnx in advance.

Ruby on Rails Form_for resource in other file -

well have problem form_for,with gem devise. before have in users/session/new.html.erb <h2>log in</h2> <%= form_for(resource, as: resource_name, url: session_path(resource_name), html: {class: 'form-horizontal'}) |f| %> <div class="form-group"> <%= f.label :email, class: "col-sm-2 control-label" %> <div class="col-sm-6"> <%= f.email_field :email, autofocus: true , class: "form-control" %> </div> </div> but try code in bootstrap modal, in other file, in app/views/layouts/_header.html.erb because have button "log in". when put there -> undefined local variable or method `resource' for a solution? or need put code? the trick defining resource_name , resource , devise_mapping helper methods in applicationhelper. assuming devise model called user , place following methods in application helper: # application_he

sql - Get data based on other row -

Image
when row of id void, not show cc_type, need cc_type void rows. case when cc_type = 'credit' or voided = 'yes' 'credit' when cc_type = 'debit or voided = 'yes' 'debit' end obviously, approach wouldn't work. row 3 consider credit since satisfy condition voided = 'yes'. my logic if id , name same append cc_type value voided row, don't know how work. thanks you can use window function: select id, name, max(cc_type) on (partition id, name) cc_type, voided yourtable

jquery mouseover / mouseout to change scroll position -

i new jquery , struggling following: from research have come quick jsfiddle . it's not quite working yet, achieve is: i want 'link30' go top when mouseover 'div 1' (and 'link30' remain @ top on mouseout). then want 'link50' go top when mouseover 'div 2' (and 'link50' remain @ top on mouseout). i want mouseover divs number of times , still have relevant links go top of scrolling div each time. at moment mouseover 'div 1' , 'link30' goes top when mouseover 'div 2' stays @ 'link30' rather moving 'link50' like. hope makes sense. thanks. here sample of code best seeing jsfiddle . $( "div.overout1" ) .mouseover(function() { $( ).find( "span" ).text( "mouse on " ); $('a').filter(function(index) { return $(this).text() === 'link30'; }).addclass('on'); var offset = $('.on').offset().top - $('.links').scrolltop(

bash - how to get the command and output logged in shell? -

we need log command , output. example if run following command. need log text file. cat script.sh find / -name sshd_config -print /etc/ssh/sshd_config cat log.out --should below <server_name>$ find / -name sshd_config -print /etc/ssh/sshd_config if use set-x in script, can log command gives information. there alternate way use in scripts? i curious , followed up: here's expect script makes shell script interactive: #!/usr/bin/env expect set script [lindex $argv 0] if { ! [file readable $script]} { error "cannot read $script" } set fid [open $script r] set lines [split [read -nonewline $fid] \n] close $fid set shebang [lindex $lines 0] if {[string match {#!*} $shebang]} { spawn -noecho {*}[string range $shebang 2 end] } else { spawn -noecho $env(shell) } foreach line $lines { # skip blank lines if {[string trim $line] eq ""} continue # skip comments if {[string match {#*} [string trim $line]]} continu

swing - Java getting the wrong number of jbuttons in grid layout -

Image
so i'm new java , im new swing. i've got 80 x 80 array thats going used maze. need gui have 80 x 80 buttons can tied values in array. i cant figure out why i'm getting 5 or 6 large buttons code. if can tell me how can work thank in advance because i'm stumped. just run , you'll see mean...also guess i've not figured out how change color of buttons , changed background color instead. heres code: public static void draw() { jframe f = new jframe(); f.settitle("maze"); f.setsize(800, 800); f.setvisible(true); f.setdefaultcloseoperation(exit_on_close); jpanel c = (jpanel)f.getcontentpane(); gridlayout gridlayout = new gridlayout(); c.setlayout(gridlayout); for(int =0;i<80;i++){ for(int j =0;j<80;j++){ jbutton b = new jbutton(); c.add(b, i,j); b.setsize(10, 10); b.setopaque(true); b.setbackground(color.red); } } } }

c - Why is the stack size different in different runs of the same program? -

consider following program. takes argument command line , unrolls recursive function limit. #include <stdio.h> #include <stdlib.h> int rec(int x, int limit) { if (x == limit) { return limit; } int r = rec(x + 1, limit); return r - 1; } int main(int arc, char* argv[]) { int result, limit; limit = atoi(argv[1]); printf("stack: %p\n", &result); result = rec(0, limit); printf("%d\n", result); } if compile expect run out of stack fixed input argument limit. else happens. dejan@raven:~/test/stack$ gcc stack.c dejan@raven:~/test/stack$ ./a.out 174580 stack: 0x7fff42fd58f0 segmentation fault (core dumped) dejan@raven:~/test/stack$ ./a.out 174580 stack: 0x7ffdd2dd8b20 0 in 2 different runs, stack size seems different. doesn't seem compiler issue same thing happens clang, , disassembly doesn't involve strange. why stack sizes on different runs different? i have added /proc/self/maps parser program (same a

awt - Show a panel in CardLayout in Java -

i wrote following code showing 3 panels depending upon of 3 buttons clicked @ bottom. import java.awt.borderlayout; import java.awt.button; import java.awt.cardlayout; import java.awt.color; import java.awt.frame; import java.awt.panel; import java.awt.event.actionevent; import java.awt.event.actionlistener; import java.awt.event.windowadapter; import java.awt.event.windowevent; public class cart extends frame implements actionlistener { panel cardpanel; panel firstp, secondp, thirdp; panel buttonp; button b1, b2, b3; cardlayout clayout; cart() { cardpanel = new panel(); clayout = new cardlayout(); cardpanel.setlayout(clayout); firstp = new panel(); firstp.setbackground(color.blue); secondp = new panel(); secondp.setbackground(color.red); thirdp = new panel(); thirdp.setbackground(color.yellow); b1 = new button("first"); b2 = new button("second"); b3 = new button("third"); b1.addactionlist

javascript - Insert a delay between every .each -

i've found few other questions pertaining this, answers didn't work me, i'm checking see if there's newer or work. essentially, i'm updating divs in .each in jquery, want them update couple seconds apart. here's i've tried: function randomcolor() { $('div').each(function(i) { settimeout(function() { var colors = ['blue', 'green']; var n = math.floor(math.random() * colors.length); var color = colors[n]; $(this).addclass(color); }, 500 + (i * 500)); }); } i've tried using separate function: function randomcolor() { $('div').each(function(i) { var time = 500; settimeout(function() { applycolor($(this)); }, time); time += 500; }); } function applycolor(div) { var colors = ['blue', 'green']; var n = math.floor(math.random() * colors.length); var color = colors[n]; $(div).addclass(color); } both of these return no err

c++ - How do you know how to deallocate an array of pointers? -

if have array of pointers this: char* p[3]; p[0] = new char; p[1] = new char[10]; p[2] = &c; assuming cannot use std::string , how know how deallocate without seeing definition? how know use delete or delete[] while iterating through array, or whether points stack variable or on heap? short answer: don't, unless know how allocated way code written. long answer: there no (generic, portable way) determine how or if allocated individual element new char or array new char[10]; or not allocated @ all. in theory, check if address "within heap" if know heap is, there no simple way know heap, stack , global data without intimate knowledge of memory layout of particular system, , compile same code on different os or different processor architecture of same os, , changes. find out if it's single or array allocation harder, if @ possible [most c++ runtime not detect , complain when char *p = new char[10]; delete p; - crash/misbehave or "work any

iOS status bar active app -

when google maps ios app running in background, or when phone call running in background, status bar shows "google maps using location" , phone call app changes status bar too. how make app show similar bar when running in background? the green "in call" bar shows when using phone app or voip apps on active call. blue "using navigation" bar shows navigation apps actively providing navigation. there's no general support show colored bar other uses. if app voip app or navigation app, ios show proper bar @ proper time.

sql - How to find the recent date -

data : id |status| date | what_i_need ------------------------------- 1 |c |jan-15 |jan-15 1 |c |feb-15 |feb-15 1 |d |mar-15 |feb-15 1 |d |apr-15 |feb-15 1 |c |may-15 |may-15 1 |c |jun-15 |jun-15 1 |d |jul-15 |jun-15 1 |d |aug-15 |jun-15 need capture max date when status changes d . what tried : select t.id, t.status, t.date, case when status = 'd' d.last_current else t.date end what_i_need table t left outer join ( select id, max(date) last_current table t status = 'c' group id) d on d.id= t.id the error top part is returning below result : id |status| date | what_i_need ---------------------------------- 1 |c |jan-15 | jan-15 1 |c |feb-15 |feb-15 1 |d |mar-15 |jun-15 <----this wrong should feb 15 1 |d |apr-15 |jun-15 <----this wrong should feb 15 1 |c |may-15 |may-15 1 |c |jun-15 |jun-15 1 |d |jul-15 |jun-15 1 |d |aug-15 |

sentiment analysis - stanford-nlp How to predict document level -

i using stanford-corenlp-3.4.1 version. have question if give sentence has multiple sentence, how calculate prediction. for eg : string text = "it fantastic experience. pathetice experience"; i getting prediction of it fantastic experience : positive. it pathetice experience : negative. i getting prediction based on each sentence level.how document level. based on reading total text need either positive or negative. here sample code: properties props = new properties(); props.setproperty("annotators","tokenize, ssplit, pos, lemma, parse, sentiment"); stanfordcorenlp pipeline = new stanfordcorenlp(props); annotation annotation = new annotation("it fantastic experience. pathetice experience"); pipeline.annotate(annotation); list<coremap> sentences = annotation.get(coreannotations.sentencesannotation.class); (coremap sentence : sentences) { string sentiment = sentence.get(sentimentcoreannotati

c# - WinForms ScrollableControl's scrollbars capture mouse wheel? -

i have custom zoombox control based on scrollablecontrol controls scrollbars through autoscrollminsize property. able handle wm_mousewheel events adjust control's zoom. made necessary steps make sure control receives mouse events when not in focus, filtering them on parent form. it seems though events reach onmousewheel method if control not have scrollbars active. if does, appears mousewheel events being redirected scrollbars handle them (by scrolling). i scrollbars there controlled in "traditional way", i.e. dragging slider or clicking on arrows etc. , handle wheel myself. possible achieve that? inherit scrollablecontrol in question , override onmousewheel() . in method don't call base.onmousewheel() . as far can tell there's no other way stop scrollablecontrol scrolling if scroll bars present. a side effect no longer mousewheel events. fixing question. conceptually want call base.base.onmousewheel().

Multi color Range Bar based on values in ssrs 2008 -

i designed range bar using ssrs 2008. scenario having issue follows: my range bar based on "activity name", start date & time, end date & time. eg: activity starts on 1st april @ 5am , ends @6pm. requirement range bar should show 5am 10am in 1 color, 10 2 pm in 1 color , 2pm till 6 pm in color. basically trying show shifts involved in completing activity. hope requirement clear. please help. it's hard visualize chart if displaying total number of activities (activity name) in 1 bar , data has date/time field, can use charts's series properties' fill property. on chart values, click drop-down value series , go fill tab. color expression, you'll want like: =iif(format(fields!yourdatetimefield.value, "hh") >= 5 , format(fields!yourdatetimefield.value, "hh") < 10, "blue", iif(format(fields!yourdatetimefield.value, "hh") >= 10 , format(fields!yourdatetimefield.value, "hh&quo

javascript - Horizontal Scroll on click -

does knows how implement horizontal scrolling on event? trying replicate functionality: http://www.spotify-valentines.com/#/home first, scrolls fullpage right. then, scrolls half way right. scrolls full page, right, , becomes normal screen vertical scrolling. site seems built angular, not sure how functionality accomplished. thanks! it can accomplish using fullpage.js . just create single section multiple slides in. can create custom buttons , associate them action $.fn.fullpage.moveto() or $.fn.fullpage.moveslideright() or $.fn.fullpage.moveslideleft() .

view - Marker with Profile Image -

i want show marker image of profile picture using picasso library. i can't determine how. userprofilepicture url of profile picture of user, , storing on userprofilepicturereceived . public class googlemaps extends activity implements onmapreadycallback { protected googlemap map; protected string usernamereceived; protected string userprofilepicturereceived; protected bitmap bmp; protected bitmapdescriptor icon; protected canvas canvas1; protected imageview icon2; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.fragment_maps); mapfragment mapfragment = (mapfragment) getfragmentmanager().findfragmentbyid(r.id.map); mapfragment.getmapasync(this); usernamereceived = mainactivity.username;//using global variable username mainactivity class userprofilepicturereceived = mainactivity.userprofilepicture; // icon2 =

python - TypeError: can't compare offset-naive and offset-aware datetimes -

the server hosts db in u.s . when add item db , want time stored using australia/sydney time. regardless of country user in, if retrieve record, should returned using australia/sydney time. doing this: tz = pytz.timezone('australia/sydney') orderdate = datetime.now(tz) return add_order_to_db(orderid, orderdate, ordercost) # adds order object db the issue arises when want update orderdate above order object. tz = pytz.timezone('australia/sydney') orderdate = datetime.now(tz) contextlib.closing(dbsession()) session: try: existingorder = session.query(order).filter_by(ordersid=orderid).first() existingorder.ordersdate = orderdate session.commit() except exc.sqlalchemyerror, error: session.rollback() raise_database_error(error) order object class order(base): __tablename__ = 'orders' ordersid = column(integer, primary_key=true) ordersdate = column(datetime, nullable=false) orderscost = column(numer

php - Select the latest entry from two tables? -

now title might bit confusing, hard explain in few words. so have table topics , posts. both have row "posted" represents time thread/post posted. need compare these , choose 1 entry , entry latest one. i can kinda demonstrate mean. have now. $postsq = $db->query("select t.posted, p.userid, p.topicid, t.id posts p, topics t t.forumid = '$forumsub[id]' , t.id = p.topicid order t.posted desc limit 1,1"); not best code know. i know doesn't work show idea of want, here how query look $postsq = $db->query("select (p.posted , t.posted) tpposted, p.userid, p.topicid, t.id posts p, topics t t.forumid = '$forumsub[id]' , t.id = p.topicid order tpposted desc limit 1,1"); anyone know how can achieve this? you can union homogenised versions of tables together, , sort them in descending order posted , limit result. try this: select * ( select id, posted, userid, 'post' posts unio

haskell - Return JSON based on Persistent Query from yesod handler -

this additional question @konstantinerybnikov return json yesod handler . what if want have persistent query selectlist , result data must return json format? code it? here code (adopt code of @konstantinerybnikov): -- json import data.aeson (object, (.=)) import qualified data.aeson j import yesod.core.json (returnjson) getimagesr :: handler value getimagesr = images <- rundb $ selectlist [imagesfilename !=. ""] [desc imagesdate] return $ object (if null images [] else [] -- want result of perstent in json format) `` hope me thank you. i guess main problem selectlist returns list of entity record (where record type querying) instead of record , we'll have list of records using map entityval ( entityval defined in entity ). handler : getimagesr = images <- rundb $ selectlist [imagesfilename !=. ""] [desc imagesdate] returnjson (map entityval images

Spark Unable to find JDBC Driver -

so i've been using sbt assembly package dependencies single jar spark jobs. i've got several jobs using c3p0 setup connection pool information, broadcast out, , use foreachpartition on rdd grab connection, , insert data database. in sbt build script, include "mysql" % "mysql-connector-java" % "5.1.33" this makes sure jdbc connector packaged job. works great. so started playing around sparksql , realized it's easier take dataframe , save jdbc source new features in 1.3.0 i'm getting following exception : java.sql.sqlexception: no suitable driver found jdbc:mysql://some.domain.com/myschema?user=user&password=password @ java.sql.drivermanager.getconnection(drivermanager.java:596) @ java.sql.drivermanager.getconnection(drivermanager.java:233) when running locally got around setting spark_classpath=/path/where/mysql-connector-is.jar ultimately i'm wanting know is, why job not capable of finding dri

c++ - OpenCV Mahalanobis function to calculate distance between two images -

i'm using opencv test similarity between 2 images taken same environment. i have series of photos of same moving environment. being , b 2 binary images of edges of 2 sequential images of environment, following: mat mean; mean.create(a.rows, a.cols, a.type()); mean += a; mean += b; mean/=2; mat covar, mean; calccovarmatrix(mean, covar, mean, covar_normal | covar_rows, cv_8uc1); mat icovar = covar.inv(); std::cout<<"type a:"<<a.type()<<"\n"; std::cout<<"type b:"<<b.type()<<"\n"; std::cout<<"icovar type:"<<icovar.type()<<"\n"; std::cout<<"a cols:"<<a.cols<<"\n"; std::cout<<"a rows:"<<a.rows<<"\n"; std::cout<<"b cols:"<<b.cols<<"\n"; std::cout<<"b rows:"<<b.rows<<"\n"; std::cout<<"icovar cols:"&l

Removing a json object from a json file in Java -

i have json file downloaded online: { "price": 1, "empty": [ 0, 0, 0, 0, 0 ], "lowvalue": 0, "highvalue": 0 }, and want delete "empty": [ to ], i've spent few hours looking @ regex stuff , can't seem figure out how make want do. edit: annamalai thangaraj's method works until add more file. { "price": 1, "empty": [ 0, 0, 0, 0, 0 ], "lowvalue": 0, "highvalue": 0 }, { "price": 500, "empty": [ 5, 0, 3, 6, 9 ], "lowvalue": 4, "highvalue": 2 } which i'm given error: exception in thread "main" java.lang.classcastexception: com.google.gson.jsonarray cannot cast com.google.gson.jsonobject my code exactly: public static void go() throws ioexception { jsonobject jsonobject = (jsonobject)jsonparser.parse(new filereader(location)); jsonobject.remove("empty"

gumbo-d bindings with DUB -

i'm trying use gumbo-d in project dub failing. here's dub output: building: myproject (default) performing main compilation... dub build "myproject" "--build=plain" building package myproject in c:\users\matt\documents\projects\myproject\ target vibe-d 0.7.23 date. use --force rebuild. target gumbo-d 0.2.2 date. use --force rebuild. building myproject ~master configuration "application", build type plain. compiling using dmd... linking... optlink (r) win32 release 8.00.15 copyright (c) digital mars 1989-2013 rights reserved. http://www.digitalmars.com/ctg/optlink.html ..\..\..\appdata\roaming\dub\packages\gumbo-d-0.2.2\gumbo-d.lib(parse) error 42: symbol undefined _gumbo_destroy_output ..\..\..\appdata\roaming\dub\packages\gumbo-d-0.2.2\gumbo-d.lib(parse) error 42: symbol undefined _gumbo_parse --- errorlevel 2 fail .dub\build\application-plain-windows-x86-dmd_2066-946d41e793c045166b4dfd37035481ae\ myproject executable error executi

html - Why does styling the background of the body element affect the entire screen? -

when style background of body element, why styling affect entire screen , not body element itself? let's create following rule: body {width: 700px; border: 1px dotted red; background-color: blue;} i find border shows 700px wide expect, background color occupies entire browser viewport. why? quote http://www.w3.org/tr/css21/colors.html the background of root element becomes background of canvas , covers entire canvas, anchored (for 'background-position') @ same point if painted root element itself. root element not paint background again. the body element root-element, , thus, required css rules loses background style , background style applied containing canvas (the webpage area in browser), therefor entire screen blue. other properties stay element (e.g. border ).

c# - SqlDataAdapter does not delete the rows from the table -

i have set of ids in c# datatable. @ same time, have table containing ids , other data too. requirement delete records contains ids specified in data table ( if there tuples ids). i'm using sqldataadapter that. sqlcommand command = new sqlcommand(text, con); command.updatedrowsource = updaterowsource.none; preparecommand(command, con, null, type, text, commandparas); sqldataadapter adpt = new sqldataadapter(); adpt.deletecommand = command; adpt.updatebatchsize = 2; adpt.update(datatable); connection.close(); here mean by, - "text" name of stored procedure containing delete command. argument given stored procedure id ( picked list of ids contained in data table) - "commandparas" argument passed stored procedure. - "datatable" contains ids used delete rows sql table. contains 1 column several rows. but not result in specified rows being removed table. edit i have given stored procedure below create procedure somename(@id int

javascript - Why does HTML5 Drag n Drop target child? (Sortable List) -

when attempt create sortable list html5 drag n drop, target of drop event ( e.target ) child of drop-zone element, rather drop-zone element itself. bad. i want value of e.target in following code div contains ondrop="drop(event)" rather it's <p> child. link jsfiddle full example. function drop(e) { e.preventdefault(); var data = e.datatransfer.getdata("text"); e.target.appendchild(document.getelementbyid(data)); } is happening because of event bubbling, or similar? best fix me create drag n drop sortable list? edit: looking understand native html5 , javascript, not use jquery library or such. you trying append target element, hence facing problem. you should try insert element before target element. function drop(e) { e.preventdefault(); var data = e.datatransfer.getdata("text"); var list = document.getelementbyid("list"); list.insertbefore(document.getelementbyid(data), e

Does the scala compiler do anything to optimize implicit classes? -

say have implicit class like: implicit class richstring(str: string) { def sayhello(): string = s"hello, ${str}!" } we can use method sayhello if defined on string class "world".sayhello does scala compiler optimize static call avoid overhead of constructing richstring object? scala compiler optimises method call if specify class extends anyval. these called value classes. example docs, link given below: class richint(val self: int) extends anyval { def tohexstring: string = java.lang.integer.tohexstring(self) } http://docs.scala-lang.org/overviews/core/value-classes.html

android - how can i change the color of ListPreference title? -

my xml code this: <preferencecategory android:title="title"> <listpreference android:title="@string/pref_theme" android:entryvalues="@array/pref_theme_values" android:entries="@array/pref_theme_entries" android:key="theme"> </listpreference> </preferencecategory> how can change color of title here? new android create prefernce style in style.xml file , define primary secondary , tertiary colors there. for example: <style name="settingsfragmentstyle"> <item name="colorprimary">@color/toolbar_color</item> <item name="colorprimarydark">@color/toolbar_color_dark</item> <item name="android:textcolorprimary">@color/toolbar_color_dark</item> <item name="android:textcolorsecondary&q

java - Should I close and create a new statement after every time I call execute()? -

if create statement jdbc , execute query, need close said statement , create new 1 before executing again? eclipse doesn't complain second case. try { connection = datasource.getconnection(); try { statement = connection.createstatement(); statement.execute("set search_path '...'"); } { utils.tryclose(statement); } try { statement = connection.createstatement(); statement.execute("set statement_timeout " + (query_timeout_seconds * 1000)); } { utils.tryclose(statement); } try { statement = connection.createstatement(); statement.execute(query); } { utils.tryclose(statement); } } { utils.tryclose(connection); } as opposed to: try { connection = datasource.getconnection(); statement = connection.createstatement(); statement.execute("set s

Imitate Powerpoint slider zoom values in WPF -

i've been trying @ properties of slider in wpf imitate slider zoom of powerpoint, can't find way imitate it. in powerpoint, min value = 10 , max value = 400. center value equal 100. in slider in wpf, if min value = 10 , max value = 400. center value not 100. evenly distributed. not in powerpoint. you have idea on how imitate powerpoint zoom slider? i guess this topic you're looking for. put slider this: <slider name="myslider" minimum="0.1" maximum="2" value="1" largechange="0.1" smallchange="0.01" tickplacement="both" ticks="0,0.5,1,1.5,2"/> and e.g. square myslider.value desired zoom factor.

c - Shifting a char value by 24 bits -

static unsigned int read24(unsigned char *ptr) { unsigned char b0; unsigned char b1; unsigned int b2; b0 = *ptr++; //b0 = 00 b1 = *ptr++; //b1 = aa b2 = *ptr; //b2 = bb b0 = (b0 & 0x000000ff) ; b1 = (b1 << 8) & 0x0000ff00); b2 = (b2 & 0x000000ff) << 16; return (b0 | b1 | b2) ; } code 2 static unsigned int read24(unsigned char *ptr) { unsigned char b0; unsigned char b1; unsigned char b2; b0 = *ptr++; b1 = *ptr++; b2 = *ptr; return ( ((b0 & 0x000000ff)) | ((b1 & 0x000000ff) << 8 | ((b2 << 16) & 0x00ff0000) | ); } here confused shifting operation done b1 , b2 . shifting char b1 8 or more 8 make value zero? better strategy,first shifting , anding or first anding , shifting. want return value should bbaa00. have done right thing? in case wrong ..is second code correct? the asymmetry in handling of shift-by-8 , shift-by-16 odd,

java - Count method invocation of method variable instance -

i have code this: class foobar { private string statefoo; public foobar(string statefoo){ this.statefoo = statefoo; } public void foo() { fooinst f = fooinstfactory.createsomefooinst(anotherstaticfooconfig.getsomepath); f.justcountme(); } } my goal make sure f.justcountme() executed once. know how in general mockito. don't know how inject mocked version of fooinst foo method? can count invocation? is possible so? if possible; suggest avoid using mocking libraries temper static fields (in way powermock/mockito do) - comes undesired side effects (for example many "coverage" tools produce invalid results when static mocking takes places). so suggestion: re-design class under test. instead of fetching f static factory; provide constructor either factory or f; can mock corresponding object; without need turn mighty dangerous "powerxyz" stuff.