Posts

Showing posts from March, 2015

sql server - How to change a normal column to "computed" column -

i have table in mssql server 2008. change 1 of column in table computed column. tell me how do ? preserve the old data: exec sp_rename 'mytable.oldcol', 'renamedoldcol', 'column'; add computed column alter table mytable add computedcol (some expression); then, when you're happy alter table mytable drop column renamedoldcol;

iphone - Displaying a big image in a small frame UIImageView still costs much memory? -

i have several big images size of 1.5 mb. display each of them in uiimageview uiviewcontentmodescalefit. the frame size of uiimageviews 150 * 150. my question is i understand if display big images full screens, memory go tremendously. but if in small uiimageview, still cost memory? thanks they won't cost in terms of frame buffer memory (i.e. memory holding pixels display), holding unscaled images in memory still incur sizeable cost. if 1.5mb compressed size. that's high (ios uses approximately 4 bytes * width * height per image store uncompressed uiimage s). such images interact poorly automatic memory management kernel perform when app goes background - backing stores released when memory pressure occurs, backing image isn't. the best way work out if problem (and if should resize them yourself, store smaller versions, , release large ones) run app through instruments using vm tracker. if regions storing images excessive, you'll able diagnose t

Linked list in Java - comparing two lists -

i need create recursive method in java checks 2 char lists. if second list includes chars in first list @ least once , in same order should return true, else should return false. example: list 1: "abbcd"(every char in node), list 2: "abbcccddd"(every char in node) should return true. example 2: "abbcd", list 2: "abcd" should return false. i have ideas can't reach definite solution. ideas anyone? i'll assume use usual node structure data element , reference next node. 1 can define function follows: contains(null, haystack) = true (since every string contains empty string) contains(pattern, null) = false (since empty string doesn't contain patterns) contains(pattern, haystack) = contains(pattern.next, haystack.next) if pattern.data = haystack.data (we found match , proceed next item in both lists) contains(pattern, haystack) = contains(pattern.next, haystack.next) else (we found no match , try next character in

java - A regular expression for harvesting include and require directives -

i trying harvest inclusion directives php file using a regular expression (in java). the expression should pick have file names expressed unconcatenated string literals. ones constants or variables not necessary. detection should work both single , double quotes, include -s , require -s, plus additional trickery _once , last not least, both keyword- , function-style invocations. a rough input sample: <?php require('a.php'); require 'b.php'; require("c.php"); require "d.php"; include('e.php'); include 'f.php'; include("g.php"); include "h.php"; require_once('i.php'); require_once 'j.php'; require_once("k.php"); require_once "l.php"; include_once('m.php'); include_once 'n.php'; include_once("o.php"); include_once "p.php"; ?> and output: ["a.php","b.php","c.php","d.php","f.p

objective c - Change UIPicker's row color or row text color -

i have uipicker i'm using toggle layers on , off. want able either change color of row within picker indicate if layer on, or change font color of text indicate if layer on. if neither possible, append nsstring add x @ end of before return (so "streets" become "streets x" if layer on). i'm not sure how either. know can type of buffing number, not sure nsstring . know picker can display 27 characters, maybe set string length 26 , set char @ location 26 x? don't know how set length of string. any ideas either path? for custom rows in uipickerview have implement pickerview:viewforrow:forcomponent:reusingview: instead of pickerview:titleforrow:forcomponent: . in case you'd use uilabel view, , change text colour , text string each row. assuming have 1 component: - (uiview *)pickerview:(uipickerview *)pickerview viewforrow:(nsinteger)row forcomponent:(nsinteger)component reusingview:(uiview *)view { uilabel *label

ruby on rails - Order Users with most Songs Desc -

hopefully simple question. have several models, 2 of them, :users , :songs , interact data database. a user has_many :songs . i'm trying find users songs in user index action, i.e list 10 users songs, user songs @ top, descending. so far have in users_controller in index ; @users = user.all and far can in view, users/index ; <% @users.each |user| %> <%= user.name %><%= user.songs.count %> <% end %> works, counts songs how order users songs? i have been looking @ sort_by inside block , guess done listing songs , grouping them user, feel not efficient enough. -as can see i'm not advanced developer. please tell me guys think , answer solution if possible. thing confusing me ordering list generating table data generated table. must simple haven't done before can't head around it. thanks in advance. how user.all(:limit => 10, :order => "(select count(user_id) songs user_id = users.id) desc")

google app engine - Why Objectify instead of JDO? -

i approaching gwt + gae world. my essential need send on gwt-rpc wire entity classes, without duplicating them dtos. objectify promise pretty well. claims hide "jdo complexity". i never worked jpa or jdo technologies. where's complexity? i mean, can provide me simple examples complex tasks in jdo, made trivial objectify? maybe relationships? i think jdo/jpa easy play on "hello world" level. changes need more real such composite keys, multiply relationships between entities , etc. jdo gae implementation quite complex , hard grasp beginners, partly due unsupported features, workarounds , extensions. jdo designed work "everywhere", means highly abstracted , general in nature. great portability, means might not perfect match specific engine gae quite unique datastore. datanucleus/jdo/jpa jars quite big (~2.3 mb in total), while objectify's jar pretty small. jdo/jpa might perform class path scanning @ startup find , register entit

math - Working out point location relative to other point when rotated - C# XNA -

i have small rectangle, point @ center. have point, outside of rectangle, 10 pixels left of rectangle's center point when rectangle sitting vertically, not rotated. how go keeping outside point in same place relative rectangle when rectangle rotated center? thanks here example of how rotate 1 point around point in xna: public vector2 rotatepoint(vector2 pointtorotate, vector2 centerofrotation, float angleofrotation) { matrix rotationmatrix = matrix.createrotationz(angleofrotation); return vector2.transform(pointtorotate - centerofrotation, rotationmatrix); }

php - rendering different view engine in zend depending on extension -

i have normal phtml template , 1 in haml. somewhere in bootstrap.php: protected function _initview() { $view = new haml_view(); $viewrenderer = new zend_controller_action_helper_viewrenderer(); $viewrenderer->setview($view); zend_controller_action_helperbroker::addhelper($viewrenderer); return $view } i initialize use haml_view, want if script filename has extension .haml, it'll use haml_view if not, it'll use regular zend_view. so guess question is, there way find out current view script filename use? thanks the basic workflow of zf mvc request follows: application bootstrapping routing dispatch zend_application takes care of first item in list, bootstrapping. @ time, have no idea request -- happens during routing. it's after have routed know module, controller, , action requested. source: http://weierophinney.net/matthew/archives/234-module-bootstraps-in-zend-framework-dos-and-dont

c# - UrlReferrer - need to find out where it's coming from -

i need find out page request coming from. instance have button in page , when clicked redirects follows http://...../clientname/names.aspx?nameid=4, page a's url = "http://...../maintenance/names.aspx?nameid=4" in page b, want able determine if it's coming page a. notice page , page b have same ending in different folders... how can know in page b if it's coming names.aspx in folder maintenance? thank you one hint: url referrer sent browser (request header). not reliable, since (for instance) security tools might remove request, proxies. have used same concept years back, later failed because of reason. example: http://darklaunch.com/2011/05/07/chrome-disable-referer-headers on other hand, if can rely on referrer - e.g. because in intranet, go ahead - ft / kuru said use httpcontext.current.request.urlreferrer . easy use. we have later solved on application level: give different html forms different logical names you can use hidden

XML parsing using perl -

i tried research on simple question have couldn't it. trying data web in xml , parse using perl. now, know how loop on repeating elements. but, stuck when not repeating (i know might silly). if elements repeating, put in array , data. but, when there single element throws , error saying 'not array reference'. want code such can parse @ both time (for single , multiple elements). code using follows: use lwp::simple; use xml::simple; use data::dumper; open (fh, ">:utf8","xmlparsed1.txt"); $db1 = "pubmed"; $query = "13054692"; $q = 16354118; #for multiple mesh terms $xml = new xml::simple; $urlxml = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=$db1&id=$query&retmode=xml&rettype=abstract"; $dataxml = get($urlxml); $data = $xml->xmlin("$dataxml"); #print fh dumper($data); foreach $e(@{$data->{pubmedarticle}->{medlinecitation}->{meshheadinglist}->{meshheadi

asp.net - How do I send emails programatically via .NET with an Exchange server that doesn't have a public SMTP? (NOT SMTP) -

question says all, server i'm working doesn't have , smtp port me access can connect via iphones "connect exchange server" in mail app, , people can send , receive emails surely should able via .net somehow. ports available on server defaults http , https. i'm guessing there protocol using other smtp? if @ least point me in right direction? i try exchange web services . there nice .net interface, managed api . need administrator enable ews, per documentation . to discover service endpoint, can either use auto-discovery , if administrator wants enable it, or can explicitly set ur l access, https://machine.domain.contoso.com/ews/exchange.asmx .

How to get column index matrix of an array in R? -

imagine have simple 4x3x2 array in r. > x <- array(1:24,c(4,3,2), dimnames=list(c('a','b','c','d'),c('x','y','z'),1:2)) > x , , 1 x y z 1 5 9 b 2 6 10 c 3 7 11 d 4 8 12 , , 2 x y z 13 17 21 b 14 18 22 c 15 19 23 d 16 20 24 what i'd like, simple function on array gives me name of index of each element arbitrary dimension. in case, dimension 2. the function behave this: > arraydims(x,2) #where 2 dimension want names for. , , 1 [,1] [,2] [,3] [1,] "x" "y" "z" [2,] "x" "y" "z" [3,] "x" "y" "z" [4,] "x" "y" "z" , , 2 [,1] [,2] [,3] [1,] "x" "y" "z" [2,] "x" "y" "z" [3,] "x" "y" "z" [4,] "x" "y" "z" the function

core graphics - iPhone - CGPoint distance in pixels and screen resolution -

i have code - (void)drawmaprect:(mkmaprect)maprect zoomscale:(mkzoomscale)zoomscale incontext:(cgcontextref)context method (into mkoverlayview subclass) prevent drawing segments less 10 pixels long on map overlay : cgpoint origin = [self pointformappoint:poly.points[0]]; cgpoint lastpoint = origin; cgcontextmovetopoint(context, origin.x, origin.y); (int i=1; i<poly.pointcount; i++) { cgpoint point = [self pointformappoint:poly.points[i]]; cgfloat xdist = (point.x - lastpoint.x); cgfloat ydist = (point.y - lastpoint.y); cgfloat distance = sqrt((xdist * xdist) + (ydist * ydist)) * zoomscale; if (distance >= 10.0) { lastpoint = point; cgcontextaddlinetopoint(context, point.x, point.y); } } will test >= 10.0 take care screen resolution, or may introduce [uiscreen mainscreen].

cookies - Jquery Style switcher - How to remove style flickering while a .css loads? -

i have simple code change styles simple clic. works fine has style flickering prevent - little timeout between 1 disabled , other not totaly loaded - also add cookie user won't have select prefered style everytime he/she enters. i'm not sure how i'm new jquery. if able me great! thanks reading! i have code switch styles on site: html call main style , main color <style type="text/css"> @import url("style.css");</style> <link href="yellow.css" rel="stylesheet" type="text/css" title="yellow theme" /> then call scripts usual <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript" src="script.js"></script> each button has this: <a class="colorbox colorred" href="?theme=red" title="red theme"><img src="red.p

C# Assign MySql Connection per thread -

i guess simple question, how create new connection per thread? umm i'm using windows service call in 3 instances of same process, each of them must have own connection. i'm using right grab connection. public static mysqlconnection connection { get; set; } public static mysqlconnection opencon() { mysqlconnection masteropencon = new mysqlconnection(staticstringclass.masterconstring); masteropencon.open(); return masteropencon; } trying resolve error: there open datareader associated connection despite initial urges, i'm not going critique design. i'm answering question given code snippet you've presented: [threadstatic] private static mysqlconnection _connection; public static mysqlconnection getconnection() { // no need locks on threadstatic field, obviously. if (_connection == null) { _connection = new mysqlconnection(...); _connection.open(); } return _connection; } hope

unit testing - Simulating user input for TDD JavaScript -

i'm finding increasingly difficult simulate actual user events using jquery or native element trigger functions. example, if have text input , don't want user able add character, can call e.preventdefault() jquery-normalised event object on keydown event. however, there no way programatically verify test scenario. the following test passes without call preventdefault because jquery keydown trigger isn't "real" event. input.val('test').trigger(jquery.event({ which: 68 }); expect(input).tohavevalue('test'); without correct code, test should fail because input should have value of 'testd' (68 character code 'd'). does know methods or libraries simulate real browser ui events? simulate real event quite complicated. must first determine type of event need , create document.createevent . call different init*event initialize event object. finally, use element.dispatchevent dispatch event target object.

regex - url encoding javascript of $0 value -

i want encode value being pass $0 in jsp, how can that? below snippet of code: ..href='"url+"$0'>$0" try using: url+encodeuricomponent($0)

java - Get the data from databases for each primaryKey in parallel -

i have list of primary keys ex: empids , want employee information each emplid database. or rather, i want data different databases based on different types of empids using multiple threads . currently i'm fetching first employee information , save java bean , fetch second employee , saved bean on. adding these beans arraylist , want data databases in parallel. means @ time want employee information each employee , save bean. basically i'm looking parallel processing rather sequentially improve performance. i don't think you're looking parallelism in case. looking single query return employees id in collection of ids have. 1 database connection, 1 thread, 1 query, , result set. if using hibernate, super easy hibernate criteria can use restrictions.in on employeeid , pass collection of ids. query underneath select a, b, c, ..., n employee employee_id in (1,2,3,4...,m) if using straight jdbc, can achieve same in native query, need change resultset

sql server 2008 - can't find SQL code for XSD schema tables -

Image
the following snippet below came *.xsd (xml schema built in visual studio) file. i'm trying figure out sql code lives data can retrieved these typed .net tables. looked everywhere, , cannot find it. 2 of tables match actual table names in database. these primary , foreign keys configured in visual studio xsd or these keys found in sql database? if double click *.xsd, can see tables, don't know data queried database unless use sql profiler. if can explain, great. found pdf best resource online far: http://oreilly.com/catalog/visualstudiohks/chapter/hack49.pdf strongly typed datasets starts on page 49. problem isn't helping me answer question had. when drag table server explorer *.xsd file, tableadaptor gets created method called fill,getdata(). when created manually, doesn't created. says automatically updates web.config file connection string information. however, tables i'm trying figure out don't have tableadaptor. keys don't

php - Remove item from an array Options - Mongodb -

how remove array item mongodb field . example , how remove guitar list of interest . php functions or approaches help. { "_id" : objectid("4d1cb5de451600000000497a"), "name" : "dannie", "interests" : [ "guitar", "programming", "gadgets", "reading" ] } unset($array['interests']['guitar']) if array in php

php - How to block all users from a site in case of emergency? -

i'm developing game in php+mysql hosted in shared web hosting. i'm concerned of security, because in games common people try cheat or broke game. until now, have tested xss, sql injection, check permissions of folders, secure passwords, ... well, know limitations , want prepared in case unexpected happens (i don't know, maybe techique don't know, or check miss, guessed password ...) if realize of of this, first action think should block access users, isolate site , check , repair bug. (it's free game, think can afford downtime). how can this? you can make .htaccess file in root of webserver contents: order deny,allow deny allow 192.168.1.1 -- here ip it block requests except mentioned ip

extjs - Sencha Touch for mobile platforms -

i have been hearing sencha touch html/css/jquery things. want start samples. have basic questions: which ide use ? how portable application 1 mobile platforms other ? can use device hardware sensors in our application ? please guide me can start learning curve. thanks in advance. doesn't matter since javascript isn't compiled: debugging in browser, not ide. it's worth, i've been using visual studio, lightweight notepad++ should work well. anything web-kit browser can run it. ios, android, blackberry 6.0+. not work on windows phone now. to use device sensors, need have emulate native access; there framework called phonegap wraps around web app this. sencha touch has built-in phonegap integration support.

performance - How to reduce Rails form loading time -

i have form has 4 associations , 2 javascript calls. taking load minimum of 10 seconds load,even new form. out of 10 seconds, active record taking in 100 ms , remaining 9990ms taking load views. (in views page,i loading tiny mice editor,autocomplete javascript libraries) is possible load page loading 4 associations,including 2 javascript libraries in less 3 seconds? if yes, pleas body me in loading form faster? thanks in advance, prem. i suggest check http://www.railsinside.com/tutorials/230-scaling-rails-a-free-13-part-series-of-screencasts.html . as said if have 4 associations may have eager_loading or may better write sql , use find_by_sql. regarding javascript or view loading may have research minifying javascript , css. need consider using image sprites.

android - Handling SMS BroadcastReceiver into Another Acitivity -

i have inbox class extends activitygroup implements onitemclicklistener. inbox class has menuitem name get, when called have method name getsms(); now have class: public class inboxsmsreciever extends broadcastreceiver{ list<string> inboxemails; @override public void onreceive(context context, intent intent) { inboxemails = new arraylist<string>();; inboxemails = getsmsasemails(intent); } private list<string> getsmsasemails(intent intent){ list<string> inboxemails = new arraylist<string>(); bundle bundle = intent.getextras(); smsmessage[] smsmessage=null; if(bundle !=null){ object[] pdus = (object[]) bundle.get("pdus"); smsmessage = new smsmessage[pdus.length]; for(int i=0;i<smsmessage.length;i++){ smsmessage[i]=smsmessage.createfrompdu((byte[])pdus[i]); inboxemails.add(smsmessage[i].getmessagebody()); } } return inboxemails; }} how r

c# - How to return an exception thrown in one project to another? -

is there way catch , return exception thrown 1 project another? for example, i'm keeping codes in different projects . , b. if engine part , b ui part, exception occurred in engine should caught in ui well.please help. if want catch exceptions @ ui level can not catch them @ engine level. for running application there no difference in assembly (every project creates assembly) exception thrown. if have catch , re-throw exception @ engine level re-throw correctly catch(exception ex) { // whatever logic throw; } or wrap it catch(exception ex) { // whatever logic throw new yourengineexception("some message", ex); } if want log it, don't it, if not cross process boundaries. catch, log, re-throw anti pattern in opinion. creates bazillion log entries, catching @ highest possible level should enough if don't destroy stack trace. use wrapping if can provide extra information exception. example if have 1 method loads da

apache - what's the rewrite rule meaning? -

rewriteengine on rewriterule ^(.*)$ http://$1 [r=301,l] what's meaning of line ( rewriterule ^(.*)$ http://$1 [r=301,l] ). thank you. it's 301 (permanent) redirect whatever path on relative domain name: http://<your website>.com/example.com redirect http://example.com . rewriterule ^(.*)$ http://$1 [r=301,l] it literally saying, "ok, found in folder should considered permanently redirected domain". ^(.*)$ means select , call $1 http://$1 means go domain stored in $1 r=301 refers status code 301 , "permanently moved" redirect. l means final instruction matching pattern. no other redirect rule after 1 effect these redirects.

winforms - Avoid expansion of certain TreeNode nodes upon TreeNode.ExpandAll? -

nobody asked before: what efficient way avoid expansion of treenode class descendants in winforms treeview when user "expand all" thing, still let him expand such nodes clicking on + symbol? sure can handle beforeexpand , have hard time setting e.cancel true if expandall operation. wonder how can determine this? subclass treeview , override expandall -- 1 cannot overriden... seems standard .net treeview doesn`t have way other described: trigger flag before expandall, handle beforeexpand , enable e.cancel appropriate nodes when flag enabled. as expandall method isn`t virtual have these ways follow: inherit treeview class , add expandallex method trigger flag. no 1 because need cast tree class everywhere use tree instance. add extension method treeview class use tree.tag property flag. more useful way minimal changes in existing code.

css - CSS3 color transition from transparent does not work for a textbox, how to solve? -

i posted following on chrome forum no luck, same problem exists -moz version of css3 rules. i'm using chrome 12.0.742.122 on windows xp sp3. want use css3 transistion text in text box transparent color (red). starting css rule text in span , textbox no color style (i.e. default black) works both. starting transparent color style (or color), works span not text box, though rules complete analogous. following excerpt show problem. after clicking on button, first 2 text examples starting default colors, 1 in span , 1 in textbox, both turn red expected. second 2 text examples, again 1 in span , 1 in textbox, span text turns red , textbox text remains transparent. how can textbox color transition transparent red? example code showing problem: <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>change color test</title> <script type="text/javascript" s

c# - Validating a collection with Dataannotations -

just started on asp.net mvc, , i'm having trouble applying datannotations collection - i'm either missing basic, or going whole thing in wrong way. i have viewmodel pass strongly-typed view: public class addcostingviewmodel { [required] [range(120,190)] public int somevalue {get; set;} public list<grade> grades { get; set; } public list<int> gradevalues { get; set; } } i have no idea if number of objects in either grades list remain constant in future, can't pass in "grade1, grade2" etc - passing in list , building cshtml page seems obvious way ensure have form contains possible grades, , returns right values. cshtml looks something this: <tr> @foreach (var g in model.grades) { <th>@g.gradename</th> } </tr> <tr> @for (int = 0; < model.grades.count(); i++) { <td> <div class="editor-field"> @h

html - How to select an INPUT element with Javascript -

i don't know term, it's when have non empty html input text while focus on before input's tabindex, hit tab key, has blue selection around text. how do javascript? i think mean "selection". @ javascript dom functions select() , focus() . e.g. <input type="text" id="mytextbox" /> <script type="text/javascript"> var mytextbox = document.getelementbyid('mytextbox'); mytextbox.select(); mytextbox.focus(); </script>

What are these php Curl response headers indicative of? -

i trying use curl communicate api of server: $ch = curl_init(); curl_setopt($ch, curlopt_url, 'pilot-payflowpro.paypal.com'); curl_setopt($ch, curlopt_httpheader, $headers); curl_setopt($ch, curlopt_useragent, $user_agent); curl_setopt($ch, curlopt_header, 1); // tells curl include headers in response curl_setopt($ch, curlopt_returntransfer, 1); // return variable curl_setopt($ch, curlopt_timeout, 45); // times out after 45 secs curl_setopt($ch, curlopt_followlocation, 0); curl_setopt($ch, curlopt_ssl_verifypeer, 0); // line makes work under https curl_setopt($ch, curlopt_postfields, $plist); //adding post data curl_setopt($ch, curlopt_ssl_verifyhost, 2); //verifies ssl certificate curl_setopt($ch, curlopt_forbid_reuse, true); //forces closure of connection when done curl_setopt($ch, curlopt_post, 1); //data sent post $result = curl_exec($ch); $headers = curl_getinfo($ch); print_r($headers); however, $result variable empty, returntra

PHP String Replacement -

i wish have 1 string contains instance (mystring): file config.php $mystring = "hello name $name , got $school"; file index.php include('config.php'); $name = $_get['name']; $school = $_get['school']; echo $mystring; would work ? or there better ways $string = 'hello, name %s , go %s'; printf($string, $_get['name'], $_get['school']); or $string = 'hello, name :name , go :school'; echo str_replace(array(':name', ':school'), array($_get['name'], $_get['school']), $string); you can automate last 1 like: function value_replace($values, $string) { return str_replace(array_map(function ($v) { return ":$v"; }, array_keys($values)), $values, $string); } $string = 'hello, name :name , go :school'; echo values_replace($_get, $string);

java - XMLBeans bounded Atom, setting content of entry -

this question similar 1 : xmlbeans - set content of complex type not quite same. trying set content of contententry in atom feed. here atom xsd definition contenttype, i.e. content tag entry in atom feed. <xs:complextype name="contenttype" mixed="true"> <xs:annotation> <xs:documentation> atom content construct defined in section 4.1.3 of format spec. </xs:documentation> </xs:annotation> <xs:sequence> <xs:any namespace="##other" minoccurs="0" maxoccurs="unbounded" /> </xs:sequence> <xs:attribute name="type" type="xs:string"/> <xs:attribute name="src" type="xs:anyuri"/> <xs:attributegroup ref="atom:commonattributes"/> </xs:complextype> after compilation xmlbean' scomp, nice jar file makes me able following. entrytype curentry; curentry = a

html5 - Zooming with canvas -

in test application have canvas simple rectangle on it. method draw called every 100ms. as can see code i'm using mousewheel scale everything. happens is, scaled, i.e. when rectangle @ 10px,10px , have mouse right on rectangle not under mouse anymore after scaling. (which of course right because units scaled to. but want is, mouseposition "center of zooming action" in google maps content under mouse before scaling, under mouse afterwards well. made few attemps translating, can't figure out, how that. thanks in advance. here's code: <script type="text/javascript"> var scroll = 0; var scale = 1.0; /** high-level function. * must react delta being more/less zero. */ function handle(delta) { var canvas = document.getelementbyid("mycanvas"); var ctx = canvas.getcontext("2d"); scroll = delta;

.net - How to simulate Control.Invoke() in two NON-UI threads -

suppose there's thread ui thread. thread creates thread b non ui thread. when thread b wants raise event in thread has if(form1.invokerequired) form1.invoke(same method) , call event within same method right? simple. question if want same thing if both , b non-ui threads? theres no form object call invoke() thread b. if winforms apps why isn't there mechanism non-ui threads? missing something? there similar method raise event in 1 non-ui thread non-ui thread? thanks in advance. p.s. producer/consumer model answers not ones i'm looking here. in first scenario, since thread b knows isn't ui thread, might call .invoke(...) . when there 2 non-ui threads, going have use kind of message passing / queue. can't interrupt thread run work; must code thread (for example) check queue work, dequeue item , execute it. pretty winforms does, courtesy of windows message loop. doesn't matter if isn't answer you're looking - is.

c++ explicit keyword for function without arguments -

possible duplicate: what explicit keyword in c++ mean? is there reason use explicit keyword function doesn't take arguments? have effect? i'm wondering because came across line explicit char_separator() near end of page documenting boost::char_separator ( http://www.boost.org/doc/libs/1_47_0/libs/tokenizer/char_separator.htm ), it's not explained further there. reading explanation of members : explicit char_separator(const char* dropped_delims, const char* kept_delims = "", empty_token_policy empty_tokens = drop_empty_tokens) explicit char_separator() the explicit keyword 1st constructor requires explicit creation of objects of char_separator type. what explicit keyword mean in c++? covers explicit keyword well. the explicit keyword 2nd constructor noise , ignored. edit from c++ standard : 7.1.2 p6 tells : the explicit specifier shall used in declarations of cons

Determining Bluetooth stack version programatically on an Android device -

how find bluetooth stack version on android device programatically? for example, way find android version android.os.build.version.release . so, there similar way find out bluetooth stack version? int version = integer.parseint(build.version.sdk); string bluezstack = ""; switch (version) { case build.version_codes.base: case build.version_codes.base_1_1: case build.version_codes.cupcake: case build.version_codes.donut: bluezstack = "bluez 3.36"; break; case build.version_codes.eclair: case build.version_codes.eclair_0_1: case build.version_codes.eclair_mr1: case build.version_codes.froyo: bluezstack = "bluez 4.47"; break; case build.version_codes.gingerbread: case build.version_codes.gingerbread_mr1: case build.version_codes.honeycomb: case build.version_codes.honeycomb_mr1: case build.version_codes.honeycomb_mr2: bluezstack = "bluez 4.69";

ajax - Get JSON data from a PHP file to jQuery and put it on selectbox -

i have big problem here. want receive data php file. i this: $("#id_categoria").change(function(){ var id = $(this).val(); $.ajax({ type: "post", url: "<?php echo root . '/control/functions.php'; ?>", data: "action=getsubbycat&id="+id, success: function(data){ alert(data); } }); }); alert(data) returns [{"id_subcategoria":"1","nome":"port\u00e1teis"},{"id_subcategoria":"2","nome":"desktop"}] . and how can consume this? , put in <option value="2">desktop</option> ? and why portáteis equal port\u00e1teis ? because database in utf-8? you use parsejson turn string json object, either build object insert dom using jquery, or document.write() desired output.

proxy - Need help with Android Emulator Networking -

here cmd line "c:\progra~2\android\android-sdk\tools\emulator.exe" -avd touch -netspeed full -netdelay none -http-proxy localhost:3128 -debug-proxy here console out when try open google.com emulator: server name 'localhost' resolved 127.0.0.1:3128 proxy_http_setup: creating http proxy service connecting to: localhost:3128 server name 'localhost' resolved 127.0.0.1:3128 proxy_http_setup: creating http proxy service footer (len=2): ' ' http_service_connect: trying connect (null) http_service_connect: using http rewriter tcp:(null)(880): connecting tcp:(null)(880): connected http proxy, sending header tcp:(null)(880): sending 27 bytes: >> 43 4f 4e 4e 45 43 54 20 28 6e 75 6c 6c 29 20 48 connect (null) h >> 54 54 50 2f 31 2e 31 0d 0a 0d 0a ttp/1.1.... tcp:(null)(880): header sent, receiving first answer line tcp:(null)(880): received 'http/1.0 400 bad request' tcp:(null)(880): connection refused, error=400

Custom Web service wrapper for SharePoint 2010? -

our team has found there things can't done in out of box sharepoint web services, we've decided build our own web service wrapper, wrap around microsoft.sharepoint.dll , microsoft.office.server.userprofiles.dll. my problem is, dlls 64 bit, web service must 64 bit. when set project x64 bit, asp.net throws badimageformatexception. is there working web service can call sharepoint 2010 native libraries use see work around, or know work around? grateful! how microsoft dll's referenced? if in web services's /bin folder, remove them there, .net attempts load them gac. ive developed several wrappers , never had 32/64 bit issue when deployed service sharepoint.

Communicating with peripherals and I/O ports from Silverlight? -

before moving towards silverlight.. want know if latest version of silverlight 5 capable of communicating , interacting directly i/o ports or other usb hid devices/ peripherals? i think way run in browser , use pinvoke calls.

Python: Modify a dict to make the key a value, and a value the key -

say have dictionary dict, following values: dict1 = {'1': ['a','b', 'c', 'd'], '2': ['e','f', 'g', 'h']} how make 1 of values key in new dictionary, dict1? dict2 = {'d': ['a','b', 'c', '1'], 'h': ['e','f', 'g', '2']} in [12]: d = {'1': ['a','b', 'c', 'd'], '2': ['e','f', 'g', 'h']} in [13]: dict((v[-1],v[:-1]+[k]) k,v in d.iteritems()) out[13]: {'d': ['a', 'b', 'c', '1'], 'h': ['e', 'f', 'g', '2']} k original key, v original value (the list). in result, v[-1] becomes new key , v[:-1]+[k] becomes new value. edit pointed out adrien plisson, python 3 not support iteritems . also, in python 2.7+ , 3, 1 can use dictionary comprehension: {v[-1]: v

asp.net - SQL SUM negative value not being returned -

i have sql query looks - create procedure [dbo].[getmemberfundunits] -- add parameters stored procedure here @member int, @fundcode varchar(15), @closingdate datetime begin -- set nocount on added prevent result sets -- interfering select statements. set nocount on; -- insert statements procedure here select (case when sum(units) null 0 else sum(units) end) fundunits pe_minv pmi_member = @member , pmi_fund = @fundcode , pmi_invested <= @closingdate end when run stored procedure - declare @return_value float /*int*/ exec @return_value = [dbo].[getfundunits] @member = 9738, @fundcode = n'58193', @closingdate = n'07/21/2011' select 'return value' = @return_value i 2 results. first correct 1 -0.0060 , second @return_value 0 this case when call stored procedure code, 0 instead of -0.0060 want. this how calling stored procedure code: dim ds new dataset() dim c

java - implementing a dao class properly to manage transactions -

i working on java web application calls database backend through hibernate.i use servlets,jsp , tomcat test/deployment.most books on java-ee suggested using dao classes database calls.as per examples given in books( hibernate recipes gary mak ),i created generic base class , specific subclass below. class basedao{ private class persistentclass; public basedao(class persistentclass) { super(); this.persistentclass = persistentclass; } public object findbyid(long id) { sessionfactory factory = hibernateutil.getsessionfactory(); session session = factory.opensession(); object object = null; try { object = (object) session.get(persistentclass, id); return object; } { session.close(); } } @override public void saveorupdate(object obj) { sessionfactory factory = hibernateutil.getsessionfactory(); session session = factory.opensession();

jQuery Validation plugin - Custom message -

i new jquery , using jquery validation plugin . i ask, how override default messages display text in label associated form element. i message this: field password required. instead of default this field required . field postcode must contain @ least 3 characters. instead of default please enter @ least 3 characters. i need override default behaviour of plugin, because not want specify custom message each item every type of validation. is possible? $("#signupform") .validate({ rules: { password: "required", postcode: { required: true, minlength: 3 } }, messages: { password: "field password required", postcode: { required: "field postcode required", minlength: "field postcode must contain @ least 3 characters" } });

visual studio 2008 - What governs the Package/Deploy/Quick Deploy Solution commands -

i have inherited sharepoint 2007 web part project, 2 branches in svn. when load trunk branch sln vs2008 , right click on solution see following commands. build solution rebuild solution package solution deploy solution quick deploy solution > retract solution clean solution ... etc. but when view old support branch, few months old see following: build solution rebuild solution clean solution ... etc. where package/deploy/quick deploy/retract commands come from? ok, answer ridiculous. turns out if use solution folders tidy sharepoint application, vsewss loses package, deploy, etc. commands. bad microsoft! in bed!

visual studio 2010 - teamcity is not executing msbuild command -

i have configuration in teamcity package , deploys. using following package , deploy on remote server /m /p:configuration=%env.configuration% /p:deployonbuild=true /p:deploytarget=msdeploypublish /p:msdeployserviceurl=%env.targetserver%/msdeployagentservice /p:msdeploypublishmethod=remoteagent /p:createpackageonpublish=true /p:username=%env.username% /p:password=%env.password% it not doing thing building project. idea missing here. process makes package missing build. validating web deploy package/publish. plz help have @ you're deploying wrong! teamcity, subversion & web deploy series. suspicion either web deploy not configured correctly on server (i.e. service not started) or credentials incorrect. try going through steps in series above , getting basics work work leaving teamcity until end. deploying visual studio command line , work there.

html - JQuery show or hide effect -

i tried slide open effect couldn't. @ last found couldn't integrate page. please help. this works way want: http://jsfiddle.net/hftpc/17/ this attempt: http://jsfiddle.net/lgu8e/ edit: said don't understand want? explain detailed: did see this? : http://jsfiddle.net/hftpc/17/ want page: http://jsfiddle.net/lgu8e/ while mouse on quickstartdiv, effect (i give it:http://jsfiddle.net/lgu8e/) runs , visiblepanel div opens this=http://jsfiddle.net/lgu8e/ not vertical, horizontal.. hope can explain it.. your fiddle requires work make pure html , appropriate javascript. first, need use jquery , jquery ui (for animations) instead of mootools. second, can't use asp tags in fiddle, need convert html. don't need document ready handler, jsfiddle allows specify in options (ondomready chose). had problems css since isn't designed work in fiddle environment -- absolute positioning moves things outside display area. after bit of tweaking, came this fiddl

include - php including file -

i have include in php script files located on 2nd level subdirectory. problem in xampp fails include these files. in netbeans if click on path open files. require_once("../../config/bootstrap.php"); require_once("../../config/config.php"); what may problem? thanks. try require_once(dirname(__file__) . "/../../config/bootstrap.php"); require_once(dirname(__file__) . "/../../config/config.php"); or in php 5.3+ require_once(__dir__ . "/../../config/bootstrap.php"); require_once(__dir__ . "/../../config/config.php");

Selectively turning off Eclipse formatting of XML files -

there way turn off eclipse formatting(of java code) selectively (see here ). is there equivalent formatting of xml files? no. thing can select "preserve whitespace in tags pcdata content"

ASP.NET MVC Jquery Validation Returns True Always -

why when forms show validation has not passed, return value following code still returns true. forms indicating validated fields in error code below adds wait no matter because valid method returns true. $(document).ready(function () { $("input[type=submit]").click(function () { if ($("input[type=submit]").valid() == true || $(this).attr("name") == "savedraft") { $("*").css("cursor", "wait"); } }); }); this basic unobtrusive validation built .net. i had reference element directly instead of how doing it. $("#mysubmitbutton"). instead of $("input[type=submit]").

Reading multiple .csv files into Matlab while organizing them into new matrices -

i have lots of .csv files want read matlab, doing organization along way my first problem data looks this: [... file1 ex1 6;0 8;0 9;1 file1 ex2 7;0 8;1 3;2 file1 ex3 7;0 8;1 3;2 the import wizard on matlab reason takes first header text data set below , throws away when reaches next text header. how can organize file looks instead? [... file1......file1.....file1 ex1.......ex2.......ex3 6;0.......7;0.......7;0 8;0.......8;1.......8;1 9;1.......3;2.......3;2 note: number of rows different ex's different, can't spilt file regular chunks. my second problem compare same experiments different files. want take columns below "ex1" different files , line horizontally against each other in new matrix. looks this: file1.....file2.....file3..... ex1.......ex1.......ex1....... 6;0.......6;0.......6;0....... 8;0.......8;0.......8;0....... 9;1.......9;1.......9;1....... note: ex's in different files in d

c++ - Assigning a value to a pointer -

if have following example: int *x; x = func(a); for statement: x = func(a); , returning address x ? or, how read it? edit : is eligible returning pointer x ? if so, can explain how done exactly? mean, how returning pointer? x pointer, int. should obvious there 2 memory locations used. 1 pointer , 1 memory it's pointing (assuming pointer not null). the pointer holds memory address, location of memory it's pointing to. 0xa456e4fa. yes, func() returning pointer. prototype of func following.. int * func(someobj a); //i don't know datatype of parameter, //so i'm making up. notice return type pointer int. , said previously, should obvious return. of form 0xyyyyyy, or memory address/pointer. memory address goes x pointer. remember pointer not holding data it's pointing to, address. there's no reason can't return pointer. however, need careful in return. not want return address of local variable becaus

java - Context failed to start when deploy web-service in netbeans to tomcat-apache -

i try follow getting started jax-ws web services tutorial on netbeans site. create web-service-app (java ee 6 web, tomcat 7.0), when add web-service class netbeans asks me if want use metro (because server does't jsr-109), yes , adds metro libraries. now webservice using javax.ejb.stateless selected "implement web service stateless session bean" checkbox, no library containing class added , error in netbeans: import javax.ejb.stateless; ... @webservice(servicename = "webservicetest") @stateless() public class webservicetest {...} "cannot find symbol: class stateless" ofcourse can't. when add "java ee web 6 api library - javaee-web-api-6.0.jar" error solved, when deploy project error thats whole lot more difficult, , error actual problem... deployment in progress... deploy?config=file%3a%2fc%3a%2fusers%2ftjen%2fappdata%2flocal%2ftemp%2fcontext6376466830057976095.xml&path=/calculatorwsapplication fail - deployed applicati

shell - Perl as a batch-script tool - fully piping child processes? -

apologies if of terminology may slighlty off here. feel free correct me if use wrong term something. is possible use perl "advanced shell" running "batch" scripts? (on windows) the problem face when replacing .bat / .cmd script that's getting complicated perl script can't run sub processes shell does. that is, same thing perl script shell when invoking child process, is, "connecting" stdin, stdout , stderr. example: foo.bat - @echo off echo hello, simple script. set param_x=really-simple :: next line allow me "use" tool on shell have open, :: stdout + stderr of tool displayed on stdout + stderr , if :: enter on keyboard sent tools stdin interactive_commandline_tool.exe %param_x% echo tool returned %errolevel% however, have no clue how fully implement in perl (is possible @ all?): foo.pl - print "hello, not simple script.\n"; $param_x = get_more_complicated_parameter(); # magic: sub executes process ,

php - Search an array[key] for any integer but one -

i stumped while searching answer, have array contains information relating tournament, seen below. i search through array of arrays opponent key, , determine if -2. because logic -2 bye, if people have -2 opponent, means brackets have been finished. my initial thought array_search(!(-2), $anarray) , didn't work , hit myself on head thinking easy haha. thanks. ex: array ( [0] => array ( [did] => 11 [uid] => 3 [id] => 1 [round] => 0 [opponent] => 3 [bracket] => 0 ) [1] => array ( [did] => 11 [uid] => 5 [id] => 2 [round] => 0 [opponent] => -2 [bracket] => 1 ) [2] => array ( [did] => 11 [uid] => 10 [id] => 3 [round] => 0 [opponent] => 1 [bracket] => 0 ) ) this function return true if opponents -2 , false if there single opponent != -2: function all_opponent_search($arr){ for($i = 0; $i < count($arr); $i++) if($arr[$i]['opponent'] != -2) return false;

php - Strange PHPCS error message -

i have following snippet in php class: $returnarray = array(); while($row = mysql_fetch_assoc($rhandle)) { $returnarray[] = $row; } phpcs complains 'while' line: 161 | error | expected "while (...) {\n"; found "while(...){\n" the problem cs (in case) expects space after while. need write code this: while ($row = mysql_fetch_assoc($rhandle)) { } edit: also, see cs reporting missing space between ) , { when closing while, think fixed when posting question :)

ruby on rails - POSTing from a controller. Need help -

i have bit of strange situation. in process of modifying fat_free_crm client. want lightweight crm automatically create few followup tasks in weeks following customer's entry system. in contacts controller, writing method run when create action performed. action automatically create 4 necessary tasks. have data saved in several hashes. is there way can these queries without changing pages? is, query create contact going through task.new(hash_name).save doesn't seem function intended or @ least, intended. any ideas? def autotask(user,contact) user.id t=time.now task1 = [ :hash_data => here ] task2 =[ :hash_data => here ] task3 =[ :hash_data => here ] task4 =[ :hash_data => here ] task=task.new(task1) task.save task=task.new(task2) task.save task=task.new(task3) task.save task=task.new(task4) task.save end task1 = [ :hash_data => here ] makes task1 array instead of hash. if want ha

java - Problem with PrimeFaces and Composite Components -

i have piece of code similar "data table - instant row selection". however, when break down composite components selection values not displayed. have suspicion it's caused primefaces code. below code doesn't work: viewapplicationconfig.xhtml <ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.prime.com.tr/ui" xmlns:dti="http://java.sun.com/jsf/composite/dti" template="../../templates/basetemplate.xhtml"> <f:metadata> <f:viewparam name="contextapplicationid" value="#{viewapplicationconfig.contextapplicationid}"/> </f:metadata> <ui:define name="title">#{viewapplicationconf