Posts

Showing posts from March, 2014

c# - TreeViewItem to notify ViewModel when it is hovered -

i using code this blogpost in order have treeview highlight items, hovered mouse. working intended, want treeviewitems notify attached viewmodels when hovered / not hovered. however i'm @ loss on how can achieve this. corresponding xaml code looks following: <style targettype="{x:type treeviewitem}"> <style.triggers> <trigger property="controls:treeviewhelper.ismousedirectlyoveritem" value="true"> <setter property="background" value="green" /> </trigger> </stile.triggers> </style> how can bind property viewmodel, named treenodemodel.ishovered treeviewitem (or attached dependency property ismousedirectlyoveritem) can react on changes within code? all examples found via google explained how set background color. in advance time on trivial answer. in style , try adding setter binds ismousedirectlyoveritem ishovered , , use onewaytosour

java - Calculating the connection count of a network -

the question calculate connection count of connected mesh topology network. total number of connections can calculated formula (n x (n-1)) / 2. implement public class connectioncount method recursively , else given us. problem can't compile. trying figure out how call method on later program compile i'm confused. please help, have far: public class connectioncount { private int n; public int connectioncalc(int n){ if(n > 0){ return(n-1) + connectioncalc(n-1); return connectioncalc(n); } else{ return 0; } } public static int connectioncount(int n) { return 0; } public static void main(string [] args) { (int = 0; < 20; i++) { system.out.println("connectioncount(" + + ") returns " + connectioncount(i)); } } } just remove second return in code. it's unreachable, compiler undoubtedly telling you.

javascript - How can I fix custom Kendo UI theme CSS which causes an IE 8 glitch? -

trying: kendo ui mendu demo custom theme ( kendo ui custom themes or modified theme css) i've customized bootstrap theme, , encountered glitch in ie 8 when mousing on menu item, when using custom theme css. customized bootstrap theme example: http://jsbin.com/ovufef/1/edit (glitch in ie 8) original bootstrap theme example: http://jsbin.com/urinev/1/edit (works expected) kendo ui menu: <ul id="menu"> <li> stores <ul> <li> <div style="padding: 50px;"> <h2>around globe</h2> </div> </li> </ul> </li> </ul> <script> $(document).ready(function() { $("#menu").kendomenu(); }); </script> view css in jsbins, long include here since kendo themes. basically glitch when mouse on item, not drop sub item down immediately, must move mouse on sub item disp

java - SWT Button Dropdown Control -

Image
is there standard swt control resembles button displays arrow , opens dropdown menu when pressed , not toolbar-only control ? it this: it similar combo box control, except "button" area act more actual button - text not change based on selection, appear depressed when clicked, , items used actions or navigational purposes instead of selection. it's similar control available toolbars, need use on regular composite instead. this doable using regular button , popup-menu controls - however, not believe can display arrow next text on button way. anyway, since kind of control seems common, assumed there standard way use these 2 things one. i think, should drop down menu behavior create menu style swt.drop_down create menuitems on menu if want button create button style swt.arrow | swt.down add selectionlistener in selectionlistener , create menu style swt.pop_up , position menu @ button location. //code public static void main(stri

php - Insert nested array from json response into mysql -

i have following json response received client: { "name": "joel", "cities_visited": [{ "city1": "chicago", "city2": "seattle" }], "active": true } i using json_decode results having problems inserting cities_visited 1 single set of data mysql. have tried json_decode($json, true) no luck. can give me insight how data formatted prepared can insert db? i need somehow cities_visited array 1 entry row on mysql , able out , return same json_encode if have 1 column cities_visited , need put multiple values it, need serialized somehow. since you're dealing json might turn json send database. $user = json_decode($input); $user->cities_visited = json_encode($user->cities_visited); something that. isn't best solution though, want create many-to-man relationship between users , cities users id (int) name (string) status (string) citie

android - Wrap buttons ontop and in middle using Relative Layout -

Image
i have layout similar kinda feel guilty because asked question layouts had no idea needed this(nor did know hard), have researched view layouts , i've tried use layout.torightof etc etc. have left/right arrows, need add , down buttons <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:game_view="http://schemas.android.com/apk/res/pap.crowslanding" android:layout_width="fill_parent" android:layout_height="wrap_content" > <framelayout android:id="@+id/flayout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_above="@+id/button1" android:orientation="vertical" > <pap.crowslanding.gameview android:id="@+id/game_view" android:layout_width="fill_parent" android:layout_height=

java - Is this possible with regular expression? -

() [] {} these valid matches ({)} false, eg.: () - true ()[]- true ()[]{} - ture ([]) - false (){[}] - false. can use regular expression compute this? no, 1 of known limitations of regular expressions can't tell whether parentheses formed.

java - Android joystick won't show up -

i working on project right in android, , have been using edited joystick class has been great! however, when optimizing code project, used lint in eclipse identify trouble spots clean up. pointed out allocated memory objects in onmeasured method in dualjoystickview class, , suggested preallocate , reuse values creating since onmeasured used in draw. tried this, , code attaching reflects update. have commented out old code, in onmeasured method. problem is, preallocating , reusing values, joysticks don't show anymore! read post using joysticks in android, , poster able work around similar issue using if statement see if objects null or not, avoid wasting time updating them during draw, , tried no avail. can make joysticks show uncommenting old code, want efficient way can. suggestions appreciated! code: package ebork.myrobot.controllerside; import android.content.context; import android.graphics.canvas; import android.graphics.color; import android.graphics.paint; import an

algorithm - Limited space average computation -

let's have n integers, n can huge, each int guaranteed between 0 , cap m, m fits in signed 32-bit field. if want compute average of these n integers, can't sum , divide them in same signed 32-bit space - numerator carries risk of overflow if n large. 1 solution problem use 64-bit fields computation, hold larger n, solution doesn't scale - if m large 64-bit integer instead, same problem arise. does know of algorithm (preferably o(n)) can compute average of list of positive integers in same bit-space? without doing cheap using 2 integers simulate larger one. supposing know m initially, can keep 2 variables, 1 answer far divided m, , other remainder. for example, in c++: int ans = 0, remainder = 0; (int i=0;i<n;i++) { remainder += input[i]; // update remainder far ans += remainder/n; // move can remainder ans remainder%=n; // calculate what's left of remainder } at end of loop, answer found in ans , remainder in remainder (if need roundi

Google maps for ios probleam -

i learning develop ios. using google maps api ios map. i've putted in project view i've putted in inspector element gmsmapview. in code put code below: - (void) setmapview:(gmsmapview *)mapview { if (!mapview) { mapview = [[gmsmapview alloc] initwithframe:mapview.bounds]; } googlemap = mapview; } the map works want set camera on map. on viewdidload function i`ve putted code below: gmscameraposition *camera = [gmscameraposition camerawithlatitude:-33.8683 longitude:151.2086 zoom:12]; self.mapview = [gmsmapview mapwithframe:cgrectzero camera:camera]; but google maps load map on london don't know why. ths coordinates sidney. have tried googlemap = [gmsmapview mapwithframe:cgrectzero camera:camera]; don't works too. anybody can me? i had same problem. can fix animating camera position once map has been alloca

visual studio 2012 - Keep My.Settings Always VB.Net -

i have application , need have my.settings saved. notice cleared whenever change files location, or run on different computer. there ways prevent this. happens when application updates. thanks. here how can retain settings thru upgrade: (you need define project - properties - setting settings of 'applicationversion' string; can start off initial value of "not yet set") private sub setsettingsversion() dim system.reflection.assembly = system.reflection.assembly.getexecutingassembly() dim appversion version = a.getname().version dim appversionstring string = appversion.tostring if my.settings.applicationversion <> appversion.tostring my.settings.upgrade() my.settings.applicationversion = appversionstring end if end sub

Node HTTP Proxy 403 Post Request Forbidden -

i used node-http-proxy proxy request port sample.com:80 port sample.com:8080 sample below: var httpproxy = require('http-proxy'); httpproxy.createserver(8080, 'localhost').listen(80); http.createserver(function (req, res) { res.writehead(200, { 'content-type': 'text/plain' }); res.write('request proxied!' + '\n' + json.stringify(req.headers, true, 2)); res.end(); }).listen(9000); when do: curl post sample.com:80 , 403 forbidden response . when curl get, 301 permanent redirect . question is: is possible make post , behaves same, always return 200 status code instead of 403 or 301? thanks var fmt = require('fmt'); var httpproxy = require('http-proxy'); fmt.sep(); console.log(); fmt.title("\033[1;36mproxy server started\033[0m"); console.log(); fmt.field("\033[1;34mproxy port\033[0m", 80); fmt.field("\033[1;34mtarget port\033[0m", 8080); fmt.field("\033[1;34m

java - JLabel text is garbled -

i'm seeing strange issue involving jlabel used display range of numbers. text of label typically 0.0 - 100.0 (for example). problem select few users, text appears garbled. in example, text show /-/,0//-/ . here's know far: it appears sort of off-by-one bug since each character displayed 1 unicode character behind expected character. the dash character between 2 numbers hard-coded in application string literal. it's happening on various versions of oracle jvms including 1.6.x , 1.7.x. it's happening on few select windows 7 machines. what cause type of problem? else should investigate? thanks. this happens when you're setting font of jlabel font corrupted in windows font cache. to rebuild cache: administrator, delete file , reboot pc: del %windir%\system32\fntcache.dat

ajax - Spring Security to continue firing the same request after authentication -

when user clicks button, ajax post request fired if not logged in login dialog box opens handled spring security. when user logs in, want fire same ajax post request. how achieve this? in ajax post request, have both headers , request body. thanks in advance

sql works in libreoffice base but not libre basic -

i have classic question getting latest record table. here statement: select t1.item, t1.price, t1.odate order t1 join ( (select item, price, max(odate) maxdate order group item ) t2 ) on t1.item = t2.item , t1.odate = maxdate order t1.item asc this statement works on both phpmyadmin , libreoffice base, libreoffice basic gives me message: syntax error in sql expression. any help? maybe should remove "price" t2's selection. seems nonsense in join, , cause error message below in mssms 2008 in case. column 'order.price' invalid in select list because not contained in either aggregate function or group clause. try select t1.item, t1.price, t1.odate order t1 join (select item, max(odate) maxdate order group item ) t2 on t1.item = t2.item , t1.odate = maxdate order t1.item asc

kendo ui - How to using custom footer temple while binding field?It say Id undefined,but id is my table property -

how use custom footer template while binding field? says studentid undefined but studentid table property. my code's this: columns.bound(p => p.studentid); columns.bound(p => p.point) .clientgroupfootertemplate("<div>average: #=kendo.tostring(getpointby(studentid),'n0') #</div><div>max: #= max #</div><div>min: #= min #</div>");

c++ - Output to file giving wrong pointer values -

i have class word holds string , vector of structs, each struct containing pointer container class, so: struct doc { document* d; int timesmentioned = 0; }; i have output function outputs each word's string , every doc's key in word's doc vector. (d1, d2, d3, etc..) whenever output of them file, looks this: foo = d3, bar = d3, foobar = d3, etc. with every word outputting d3 (the last document looped through previous given input file. can post code if needed) the weird thing is, whenever output console, works fine. doc that's associated each word outputted correctly. idea why happen? thought may dangling pointer outputting console correctly curious. can post adding docs function or more code if needed. here code word class: void word::createword(string str) { removepunctuation(str); tolower(str); word = str; } void word::adddoc(document& d) { doc newdoc; newdoc.d = &d; newdoc.timesmentioned++; docs.push_back

ember.js - Just created entity with ember-data doesn't have its state set -

i use ember + ember data. when create entity after corresponding server side call state attributes (isloaded, isnew, isvalid, etc.) undefined. expectation these should set. example, before server side call expect isnew 'true' , after creation on server side expect isnew 'false'. i creating enity way: myentity = myapp.myentity.createrecord({attr1: "value1"}); ... myentity.transaction.commit(); what goes , forth is: sent: {"myentity":{"attr1":"value1"}} ... received: {"myentity":{"id":2,"attr1":"value1","attr2":"value2"}} the entity defined this: myapp.myentity = ds.model.extend({ attr1: ds.attr("string"), attr2: ds.attr("string") }); unfortunately before , after remote call 'myentity' has state attributes 'undefined'. missing something? thanks! i guess problem not following naming conventions of ember

coldfusion - Upload photo from my system to company Facebook page without having users authenticate individually -

i have application staff upload photos specific tours. priority have photos uploaded system use in site , product display. however, every time of staff upload photo in system, want send photo our corporate facebook presence. preferably little story each photo. everything have found seems require each user log in own facebook accounts individually. there way code authentication facebook account details regardless of user , take photo uploaded on system using cffile , send our corporate facebook presence? i post code attempts here, @ point still not sure if possible. guidance appreciated. thanks..... posting photo text possible on facebook using system. need visit developer.facebook.com , register app , required authentication key. , follow documentation of graph api. coldfusion facebook sdk available on git hub . makes job more easy.

ruby cast method input variable as string in ruby irb -

how coerce behavior of irb treat variable identifiers strings when used in method signatures? i trying create irb based calculation tool , want reduce typing of users use tool in irb shell. assume users not ruby programmers or know syntax of ruby. may have facility command line. i have file calculator.rb inside file is def calculate(value, units) ... logic end i instruct user fire irb so irb -r path/to/calculator.rb i instruct user type calculate(10, inches) get return value in irb how can without requiring user understand have wrap second parameter in quotation marks. in other words don't want user have type calculate(10, "inches") is possible cast user input string instead of variable identifier before passed method inside script? maybe want not possible without fundamentally breaking irb shell? if non-programmers how using puts , gets ? def calculate puts "which number convert?" number = gets.to_i puts "w

android - Using Context in FragmentPagerAdapter -

i couldn't use context in fragmentpageradapter . radiogroup(this) gives me undefined error. used getcontext() instead of couldn't achieve it private static class myfragmentpageradapter extends fragmentpageradapter { final radiogroup rg = new radiogroup(this); // can use instead of "this" ? } i not sure why instantiating radiogroup in fragmentpageradapter, anyway can context modifying constructor of class: private context context; /** constructor of class */ public myfragmentpageradapter(fragmentmanager fm, context c) { super(fm); context = c; } then can add context when create fragmentpageradapter.

graphics - When I run pcolor plots on Matlab the axis text appears smudged and unreadable -

Image
when run pcolor plots (only pcolor, plot fine) on matlab axis text appears smudged , unreadable. see attached figure. i running ubuntu 12.04 matlab r2012b under vmware virtual machine hosted win7. has ever seen before? you can change figure/axis property follows: 1 edit > axes properties 2 in font tab, change font size etc. make figure more legible.

Scala XML Match nodes using Attributes -

i loading xml file in scala looks this: <dataset> <item label="neutral" target="general" tweetid="936466790" username="b_e_x"> <content>jim lehrer directed debate audience ... 30 seconds ... #tweetdebate</content> </item> <item label="neutral" target="general" tweetid="936466992" username="jonathan fields"> <content>here go. #tweetdebate</content> </item> </dataset> now, trying labels of each of items using attributes, returns me none? tried several ways matching, parsing etc.: val rawxml = xml.loadfile(file).tolist rawxml.foreach(x => println(x.attribute("label"))) i tried matching follows: myxml match { case <dataset> {item @ <item>{thetext}</item>} </dataset> => println("an %s text: %s".format(item \ "@label", thetext)) there few

ios - How can I get the size of the keyboard on iPhone? -

Image
i want keyboard size without using nsnotification . when press plus button, can replace keyboard custom uiview this: then plus button pressed , view loaded: how can achieve this? i made same rookie mistake want here. problem write lot realize not want avoid standard flow provided ios team. example have bad time dealing issue 1 (there additional bar part of standard keyboard chinese locale): i solved using other people's work dakeyboardcontrol project . not need attach observer (or if use dakeyboardcontrol - block) directly bar buttons, controller , check user trying , animate bar accordingly. in sources can see how keyboard's animation duration , timing function. may sound more complicated indeed is, give try.

java - GAE - Should I chain asynchronous callbacks? -

i'm new using asynchronous callbacks , i'm not sure if i'm planning out appropriate way go doing things. i'm working google app engine along google web toolkit, , provide simple way perform asynchronous callback methods rpc service. i've got basic asynchronous callbacks working fine, i'm looking little more complicated. want set things part of web app that's available user loaded first there's user use quick possible. next available parts loaded , on. might want more complicated , load in order described unless user clicks else, load part first. the way i'm thinking doing using asynchronous function calls in gae , gwt , on success of 1 call start next one. should work, more parts need loaded more code becomes bit spaghetti. there better way make , organize these asynchronous calls? google provide better method organize don't know about? also, going down wrong road , should doing different? thank much! no, rpc calls not way load par

Weird issue with storing and unsetting session from redirect in Google Chrome with PHP -

i'm getting weird issue in google chrome . (it's fine in firefox, ie) code below recreate this. steps are: navigate page sets session variable , redirects the new destination page calls function that: reads session variable , stores in local variable unsets session variable returns local variable then page reads return value , echos html (or tries to) i see 2 things: if call echo before first output of page, echos browser but not actual source (i.e. "view source" not show text "echo"-ed) if call echo within html, doesn't echo , doesn't print source @ the page redirects (you can go directly page) <?php class landingredirector { private static $session_variable = "redirectedfrom"; function __construct() {} public function redirect() { //make sure have session session_start(); //set redirect variable $_session[ self::$session_variable ] = "red.php";

In PHP date function for before 2 months -

i need date functions. how find before 2 months date (using date() function) particular date or current date. use this echo date("y/m/d",strtotime("-2 months")); http://codepad.viper-7.com/z1his7 example 2013/feb/20

jQuery - both if else statements executing on page load -

edit: both if else statements executing. - have table buttons in it. on page load, if label of button 'hello', want change else. have if-else statement time, both if else statements being executed. not wrong here. $(document).ready( function() { if($('button').val() == "hello" ) { alert("hello in if"); $(this).removeclass('btn-danger'); $(this).addclass('btn-primary'); $(this).text('ifif'); } else { alert("hello in else"); $(this).removeclass('btn-primary'); $('button').addclass('btn-danger'); $('button').text('elseelse'); } }); everytime, label of button changes elseelse when initial label of button 'hello'. first goes inside if , changes label ifif , goes inside else too.it works fine if put in click event function. on page load not work correctly. your responses appreciated. thanks y

php - Using the "LIKE" with the "=" criterion together -

i not know how can intergrate "=" criteria "like" in following piece of code. the code searching multiple criterion. search cat_id okey expect want criteria not part of "like" criteria; instead should "=" can exact match in search. appreciated. $criteria = array('ctitle', 'csubject', 'creference', 'cat_id', 'cmaterial', 'ctechnic', 'cartist', 'csource', 'stolen'); $likes = ""; $url_criteria = ''; foreach ( $criteria $criterion ) { if ( ! empty($_post[$criterion]) ) { $value = ($_post[$criterion]); switch ($criterion) { case 'cat_id': $likes .= " , `$criterion`='$value'"; break; default: $likes .= " , `$criterion` '%$value%'"; break;

asp.net - How to generate a print preview in a single button click in report viewer? -

this aspx page.................. <asp:panel id="updatepanel1" runat="server" visible="false" > <rsweb:reportviewer id="reportingforprintingreportviewer" runat="server" width="100%" height="100%" font-names="verdana" font-size="8pt" interactivedeviceinfos="(collection)" waitmessagefont-names="verdana" waitmessagefont-size="14pt"> <localreport reportpath="report.rdlc"> <datasources> <rsweb:reportdatasource datasourceid="objectdatasource2" name="dataset1" /> </datasources> </localreport> </rsweb:reportviewer> <asp:objectdatasource id="objectdatasource2" runat="server" selectmethod="getdata" typename="dataset

xamarin - No phone state event received when ending second call in Android -

i registered phone_state listener in order detect when call started , ended user. in case anyone's wondering, i'm doing strictly fun , learning, there's no privacy concerns. anyway, noticed problem when experimenting telnet , emulator. in specific scenario when 1 call on hold , second call (the active one) ended, listener receives no event. expecting @ least receive offhook when first call activated again, if not both idle + offhook. there's nothing whatsoever. on related note, noticed there no phone state event defined putting call on hold, seems bit strange me, too. of course, android log entries correctly reflect these events. question is, how can reliably detect them in code? should monitor log (not sure if that's possible) instead of relying on phone state listeners? i'm testing on api 15 on emulator, via xamarin studio, code c# + xamarin.android on mono, not java directly. may behavior bug or omission in 1 of layers, it's more i'm miss

javascript - how to change the value of input box just for display in html 5 web page -

i have textfield in entering data want if user enter 1000 show 1,000 in textfield same value 1000 used in calculations further how solve if user enter 1000 display show 1,000 , if use in calcualtion same var shows 1000 calculating. <html> <body> <input type="text" id="test" value="" /> </body> <script> var c=document.getelementbyid(test); </script> </html> so if c user enter 1000 should dispaly 1,000 dispaly 1 , if user uses in script var test=c then test should show 1000 document.getelementbyid returns either null or reference unique element, in case input element. input elements have attribute value contains current value (as string). so can use var test = parseint(c.value, 10); to current value . means if didn't use predefined value test nan . however, evaluated once. in order change value you'll need add event listener, handles changes input

Increment of field default value in mysql/php -

$saa = "update aspirantdt set vote = 'vote'+1 'post_id' = '$id' "; when check database value didnt increase. me out. yuo have sintax mistake in update query, using quotest instead of backtick. use backticks column names , quotes values try change follow $saa = "update `aspirantdt` set `vote` = (`vote`+1) `post_id` = '".$id."' ";

java - Get only specific records of data in Liferay -

i using liferay develop module. part of involves fetching records form database leave status of employees pending. code have fetch "pending" records is: @suppresswarnings("unchecked") public static list<employee> getemployeedata() throws portalexception, systemexception{ list<employee> employeedetails; try{ int totalemployees = employeelocalserviceutil.getemployeescount(); for(employee emp: employeedetails { if(emp.getempstatus.equals("pending") { employeedetails= employeelocalserviceutil.getemployees(0,totalemployees); } } }catch(systemexception se){ employeedetails = collections.emptylist(); } return employeedetails; } the above code fetches details - pending non pending. know happens because of statement in above code: employeedetails= employeel

Shared test code in multi-project Maven Java environment -

i have maven multi-project set-up parent pom, 1 library-type jar , several application-jars using library. i'd take advantage of library-type jar's testing facility (especially api mocking features) in unit tests of applications avoid repeating same unit test code in of applications, doing now. seems not trivial. any of done this, or other solutions suggest problem? [edit] clarification: if have applications a, b , library l, , dependencies this: a -> l <- b i test code of above have dependencies correspondingly: a' -> l' <- b' so application's test code see library's test code.

java - Retrieving serial id from batch inserted rows in postgresql -

here code works: connection c = ds.getconnection(); c.setautocommit(false); preparedstatement stmt = c.preparestatement("insert items (name, description) values(?, ?)"); while (!(items = bus.take()).isempty()) { (item item : items) { stmt.setstring(1, item.name); stmt.setstring(2, item.description); stmt.addbatch(); } stmt.executebatch(); c.commit(); } but need populate table id foreign key. if use insert returning id executebatch fails "a result returned when none expected" error. i see several ways solve this do individual insert rather batch insert. replace serial id client generated guid. use kind of stored procedure perform batch insert , return list of ids. of 3 methods see last 1 seems preserve both efficiency of batch insert , return ids, complex me have never written stored procedures. is there better way batch insert ,

php - GAE - wordpress as a module inside a Python app -

google app engine added support modules. , i'm remember saying can have modules different runtimes. default app can python , module in java or php example. , module configuration file make specify runtime module. so why can not figure out how run php module inside python app? i have dispatch.yaml contains: dispatch: - url: "*/blog*" module: blog and blog.yaml module contains: module: blog version: wp runtime: php api_version: 1 and bunch of handlers wordpress. has else been able successfully? in case want run wordpress blog under http:/www.domain.com/blog instead of under sub-domain seo reasons. it seems appengine sdk not using module because if try go /blog gives me 404 error. i'll continue play , post update if find solution. i have working now. google fixed issues in version 1.8.5 making possible. it's not hard, have remember run appcfg.py update_dispatch in order make dispatch routing live. , when deploying appcfg.py upda

Django audit log - 'action_date' field is naive, how do I prevent warnings -

i'm using django-audit-log track changes data. works great other 1 small thing: whenever new entry being added log table warning generated: datetimefield received naive datetime while time zone support active. i traced , discovered action_date field in log table causing it. know how can make value timezone-aware? maybe pytz can come in handy here. can convert naive datetimes timezone aware ones. have here: http://pytz.sourceforge.net/ . if happen have naive date string " 2012-02-21 10:28:45 ", may proceed this: from django.utils.dateparse import parse_datetime naive = parse_datetime("2012-02-21 10:28:45") import pytz pytz.timezone("europe/helsinki").localize(naive, is_dst=none) datetime.datetime(2012, 2, 21, 10, 28, 45, tzinfo=<dsttzinfo 'europe/helsinki' eet+2:00:00 std> ( https://docs.djangoproject.com/en/dev/topics/i18n/timezones/#usage ).

How to manage and selectively stop a published subscription from Meteor server side code -

i'm developing competitive turn based game. when anonymous visitor visits page, automatically subscribing non-full instance of game can either observe or join action. there limited number of spots in each game instance. when joining game (taking spot), old subscription stopped , new 1 created includes private information based on chosen spot. far good. now want make server free spot whenever player doesn't complete turn in reasonable amount of time. the question how can make sure player kicked out of spot no longer receives updates intended go else occupying spot? has happen on server side clients cannot trusted. ideally kicked out user seamlessly become observer again. i know there method stop() can called inside publish() , how use stop published subscription 1 particular client when callback set meteor.settimeout() gets called on server? some heavily modified code of i'm trying (not meant work, give idea) if meteor.isclient publicgamehandle = mete

vb.net - "Type is not defined" error on project build -

i created new vb.net windows applications project , added reference utilities project have done many times before. when start coding, editor find utility namespace without difficulty when build "type my.utils.data not defined". i've compared project other projects , can't find difference. when try debug, dialog saying "visual studio cannot start debugging because debug target "c:.....\myproject.exe" missing you need make sure consuming project targeting .net framework version equal or higher other project referencing. if referenced project targeting higher version of framework, visual studio not give useful message like, "wrong framework version". instead, gives confusing error assembly being missing, though it's there.

Wordpress Gallery Shortcode Pregreplace -

basically need remove gallery shortcode wordpress content, i'm using echo preg_replace('/\[gallery ids=[^\]]+\]/', '', get_the_content() ); it removing gallery shortcode successfully, paragraph tags need keep. idea want output in content except gallery. you use wordpress strip_shortcode function . look @ example in codex. can create filter strips shortcodes: function remove_shortcode_from($content) { $content = strip_shortcodes( $content ); return $content; } and call when need (in template): add_filter('the_content', 'remove_shortcode_from'); the_content(); remove_filter('the_content', 'remove_shortcode_from') edit 1 another way (and answering comment) can use wordpress apply_filters function in content after remove undesirables shortcodes. //within loop $content = get_the_content(); $content = preg_replace('/\[gallery ids=[^\]]+\]/', '', $content ); $content = apply_filters('

java - Android - Bitmap cache takes a lot of memory -

i'm new memory management subject, there lot of things don't understand. i'm trying cache image in app, i'm having troubles memory consumption: all of bitmap chaching code pretty copy-pasted here: http://developer.android.com/training/displaying-bitmaps/index.html i debugged code , checked heap size in ddms view in eclipse, , there 15mb jump after these code lines: options.injustdecodebounds = false; return bitmapfactory.decoderesource(res, resid, options); in "decodesampledbitmapfromresource" method. the image 1024x800, 75kb jpg file. according i've seen on internet, amount of memory image supposed take 1024*800*4(bytes per pixel)=3.125mb all of threads regarding subject don't why it's taking more memory should. there way cache 1 image reasonable amount of memory? edit i tried using decodefile method suggested on @arshadparwez's answer below. using method, after bitmapfactory.decodestream method memory incr

bit manipulation - How to do a bitwise operation on some data in C? -

i have following code snippet in c function int i; (i = bytes; i>0; --i) { printf("byte: %d", data & 0xff); data>>= 8; } to split given data bytes in big endian way ( bytes number bytes in data ). data - int or 100 byte long character string. however, if data not int , code won't work ( invalid operands binary x ). for example, assuming data string content hello world expect following numbers: byte: 104 byte: 101 byte: 108 byte: 108 byte: 111 byte: 32 byte: 119 byte: 111 byte: 114 byte: 108 byte: 100 i need simple solution wotk in pure c without libraries besides standard ones. if want print bytes of raw binary data: void print_bytes(const void *data, size_t len) { const unsigned char *p = data; (size_t = 0; < len; i++) printf("%d ", p[i]); } you can call address of object, this: unsigned long long u = 1234567890; print_bytes(&u, sizeof u); // beware of endianness! const char *s = &quo

c# - how can I find out which items are selected in checkedlistbox? -

Image
i have checkedlistbox in c# language, want have multiselection, but problem when type checkedlistbox.selecteditems , contains properties of last selected item. whats solution ? you need set selectionmode of checkedlistbox multisimple or multiextended enable multiple selection. various modes - one - 1 item can selected. none - no items can selected. multisimple - multiple items can selected. multiextended - multiple items can selected, , user can use shift, ctrl, , arrow keys make selections edit you can't set multiple selection checkedlistbox per msdn - the selectionmode property determines whether 1 item in list box can selected or no items can selected. checkedlistbox objects, multiple selection not supported. can set mode 1 item or no items. even tried setting , stated throws argumentexception @ runtime -

xhtml - Batch .pdf files generation using seam <p:document> -

i want generate big pdf file using seam. seam have .xhtml support pdf generation tag facility work when there browser interaction. i didn't find way use seam pdf facilities background/batch way. there solution here. https://community.jboss.org/thread/180380#comment24174 and jira here make easier. since nothing done since 2008 might not done :) https://issues.jboss.org/browse/jbseam-2613

asp.net mvc - i get Error executing child request for handler -

my login partial view. pass model contain some fields of tbl_profile partial view , fill , pass filled model actionresult in [httppost] part , ... i'm trouble in [httpget] part . error on line of cod " * @html.action("logon","account")" *. code : [httpget] public actionresult logon(string returnurl) { using (var db = new mycontext()) { var allfeaturetolog = db.tbl_profile.select(u => new usersclass.logon { username = u.username, password_user = u.password_user }).tolist(); return partialview(allfeaturetolog); } } class: public class usersclass { public class logon { public string username { get; set; } public string password_user { get; set; } } } logon.cshtml: @model myproject.models.usersclass.logon @using (html.beginform()) { @html.antiforgerytoken() <form class="signin-form">

c# - How can I properly compose this sql subquery to values from another table instead of hard coding them? -

not sure if worded question correctly, have huge sql server handicap, may simple thing not seeing. have following query: select stu.systudentid, stu.firstname, stu.lastname, stu.startdate, enr.adprogramversionid, enr.adcatalogyearid, enr.gpa cumgpa, case when (stu.datelstmod > enr.datelstmod) stu.datelstmod else enr.datelstmod end datelstmod systudent stu inner join adenroll enr on enr.systudentid = stu.systudentid inner join syschoolstatus schsta on schsta.syschoolstatusid = enr.syschoolstatusid inner join systatus systa on systa.systatusid = schsta.systatusid systa.category in ('e','a') , stu.sycampusid = 6 , ( enr.adprogramversionid null or (enr.adprogramversionid = '52' , enr.adcatalogyearid='3') or (enr.adprogramversionid='53' , enr.adcatalogyearid='3') or (enr.adprogramversionid='50

php - if else statement not work in option input -

here code : var $myarray =array ('black','blue','brown','yellow') if ( $row['color']=="") { echo"<option value='' selected>---select---</option>"; } foreach ($myarray $color) { if ($row['color']!="" && $row['color']==$color) { echo"<option value='$color' selected>$color</option>"; }else { echo"<option value='$color'>$color</option>"; } } my question is how rid of (< option value='' selected>---select---</option>) if $row['color'] not null or not empty? i´ve tried many ways...but nothing helped. :s <?php $myarray =array ('black','blue','brown','yellow'); $row['color']=''; ?> <select name='whatever'> <?php if ($row['color']=='' || $row['