Tuesday, 15 January 2013

android - how to set heap size to minimum when application was closed -



android - how to set heap size to minimum when application was closed -

i developing 1 android application using more images resolution 640*960 approximately. these images loaded bitmaps proper scaling factor.

when loading bitmpas heap size increasing , not decreasing though recycling bitmpas. read few theory's regarding issue maximum says 1 time heap increased not decreased @ all.

my problem if close application when heap size 10mb , , when reopen application heap starts 10mb. causes vm exceeds maximum heap memory , out of memory after time.

what have this, , guarantee application never close out recycling bitmaps.

can 1 please suggest me how minimze heap memory , solve oom.

even faced same problem....you can refer link loading bitmaps http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

once heap size has exceeded limit garbage collector runs...and cleans unwanted object.so improve not phone call garbage collector run automatically.

applications running on api level 11+ can have android:largeheap="true" on element in manifest request larger-than-normal heap size

in oncreate method in activity can utilize this(i did'nt seek this) dalvik.system.vmruntime.getruntime().setminimumheapsize(yournumberhere);

android bitmap out-of-memory heap-memory

Paypal failed to login in Android 4.0 -



Paypal failed to login in Android 4.0 -

private class paypalintegrated extends asynctask<void, void, void> { @override protected void doinbackground(void... params) { seek { paypalpayment newpayment = new paypalpayment(); newpayment.setsubtotal(new bigdecimal( coinprices[positionclicked])); newpayment.setcurrencytype("myr"); newpayment.setrecipient("xxxxxxxxxxx"); newpayment.setmerchantname("draw me not"); paypal pp = paypal.getinstance(); if (pp == null) pp = paypal.initwithappid(coinscene.this, "my_app_id", paypal.env_sandbox); intent paypalintent = pp.checkout(newpayment, coinscene.this); coinscene.this.startactivityforresult(paypalintent, 1); } grab (exception ex) { } homecoming null; } @override protected void onpostexecute(void result) { } }

i tested different devices galaxy mini 2, 2.3.6 , htc sensation, 4.0.4.

however, mini 2 can proceed payment , checked in sandbox business relationship appear transaction not htc.

htc homecoming error with

error code = 10004

error message = please create sure fields have been entered

i think os version impact result.

is there solution?

android paypal

ruby - How to find out why rails server hangs at 100%? -



ruby - How to find out why rails server hangs at 100%? -

can think of way find out our rails production server hangs? cpu @ 99% assume gets lost in while/for/each loop. unfortunately can't find candidate loop.

the problem not occur in development , our test suit has 100% code coverage.

we attaching ruby via gdb, didn't know go there. ideas?

once have attached gdb busy looping process phone call rb_backtrace gdb:

> phone call rb_backtrace()

the output rb_backtrace similar crash report, , output go log files similar standard ruby error backtrace.

from there should step closer solution since see in ruby code process stuck.

you can check out more tips here: http://isotope11.com/blog/getting-a-ruby-backtrace-from-gnu-debugger

ruby-on-rails ruby debugging gdb

java - Suppressing GPG signing for Maven-based continous integration builds (Travis CI) -



java - Suppressing GPG signing for Maven-based continous integration builds (Travis CI) -

i'm using travis-ci provide continuous integration builds few java open source projects i'm working on.

normally works smoothly, have problem when pom specifies gpg signing, e.g.

<plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-gpg-plugin</artifactid> <version>1.4</version> <executions> <execution> <id>sign-artifacts</id> <phase>verify</phase> <goals> <goal>sign</goal> </goals> </execution> </executions> </plugin>

this causes travis build fail - apparently because not have passphrase available while running mvn install. see this build example.

what best way configure maven and/or travis skip gpg signing ci test builds, still perform gpg signing when proper release build?

you need create profile & create sure run when release build.

remove current plugin, , add together in profile this:

<profiles> <profile> <id>release-sign-artifacts</id> <activation> <property> <name>performrelease</name> <value>true</value> </property> </activation> <build> <plugins> <plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-gpg-plugin</artifactid> <version>1.4</version> <executions> <execution> <id>sign-artifacts</id> <phase>verify</phase> <goals> <goal>sign</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles>

and when need release, add together property mvn command:

mvn -dperformrelease=true ...

java maven continuous-integration gnupg travis-ci

mysql - Introducing a column of numbers that count from 1-381 -



mysql - Introducing a column of numbers that count from 1-381 -

i have table 381 records columns id,name,dept_id.

how introduce column called row_id numbers count 1-381 (to uniquely identify each row , need auto-increment point afterwards).

i need write in mysql. other way can think of manually entering take long.

add new column alter table table_name add together column row_id int() execute command select @i:=0;update table_name set row_id = @i:=@i+1then create primary key , set auto increment

mysql phpmyadmin

c# - Steps for using Google custom search API in .NET -



c# - Steps for using Google custom search API in .NET -

i trying utilize google custom search api in .net project. have api key provided company. have created custom search engine using google business relationship , copied 'cx' value.

i using next code:

string apikey = "my company key"; string cx = "cx"; string query = tbsearch.text; webclient webclient = new webclient(); webclient.headers.add("user-agent", "only test!"); string result = webclient.downloadstring(string.format("https://www.googleapis.com/customsearch/v1?key={0}&cx={1}&q={2}&alt=json", apikey, cx, query));

i getting next error: "the remote server returned error: (403) forbidden. "

i have tried next code too:

google.apis.customsearch.v1.customsearchservice svc = new google.apis.customsearch.v1.customsearchservice(); svc.key = apikey; google.apis.customsearch.v1.cseresource.listrequest listrequest = svc.cse.list(query); listrequest.cx = cx; google.apis.customsearch.v1.data.search search = listrequest.fetch(); foreach (google.apis.customsearch.v1.data.result result1 in search.items) { console.writeline("title: {0}", result1.title); console.writeline("link: {0}", result1.link); }

here next exception @ fetch():

google.apis.requests.requesterror access not configured [403] errors [message[access not configured] location[ - ] reason[accessnotconfigured] domain[usagelimits]

is cx parameter required? getting error because using key provided company , using cx parameter custom search engine using google account?

is there other way of getting 'cx'? don't want display google ads.

thank much in advance help.

i'm not sure if still interested in this.

to results without ads need pay it. info @ google

and yest cx required because specifies google custom search engine want utilize search. can create custom search engine this google page

and here current code retrieve search results current api version 1.3.0-beta

string apikey = "your api key"; string cx = "your custom search engine id"; string query = "your query"; var svc = new google.apis.customsearch.v1.customsearchservice(new baseclientservice.initializer { apikey = apikey }); var listrequest = svc.cse.list(query); listrequest.cx = cx; var search = listrequest.fetch(); foreach (var result in search.items) { response.output.writeline("title: {0}", result.title); response.output.writeline("link: {0}", result.link); }

hope helps

c# .net google-custom-search

html - Footer stick to the bottom with jQuery -



html - Footer stick to the bottom with jQuery -

i tried div.col-wrapper stick bottom on firefox on high res screens using position absolute reason messing jquery slide effect. ran out of possible solution except in jquery create stick bottom.

jquery

$(document).ready(function(){ $(".box").show(); $(".list").hide(); $(".wbut").click(function(){ $(".wbut").hide("fade"); $(".box").hide("fade"); $(".list").show("slide", { direction: "down" }, 1000); }); $(".wbut2").click(function(){ $(".box").show(); $(".wbut").show(); $(".list").hide("slide", { direction: "down" }, 1000); }); });

css

.list { background: #d1d1d1; } .col-wrapper { width: 100%; position: relative; bottom: 0; left: 0; background: #d1d1d1; box-shadow: 0px -5px 8px #777; }

i added position absolute wrong element. should .list not .col-wrapper

jquery html css firefox

ios - Adding new settings to NSUserDefaults -



ios - Adding new settings to NSUserDefaults -

this question has reply here:

nsuserdefaults intitial setup 2 answers

i utilize nsuserdefaults store app settings.

i need set default value settings.

so added isappfirstlaunch value defaults , set needed default(initial) values settings in on app first launch.

but add together new settings. in case isappfirstlaunch false , can't set default value have delete app , install againg.

so question is: how set new settings default values?.

as unserstand if app in appstore

[[[nsbundle mainbundle] infodictionary]objectforkey:@"cfbundleversion"]];

than can store app version in defaults , check if version changed set new defaults.

but debugging? should delete app clean defualts?

you can check whether setting exists (if different null) , if doesn't exist, set default value.

you can add together code app delegate's applicationdidfinishlaunching method checks if setting null , so, sets it. every setting in app.

ios objective-c nsuserdefaults

iphone - libFlurryAnalytics.a error -



iphone - libFlurryAnalytics.a error -

i have code senior developer have modify. changes done , runs on simulator. moment run on device, gives next error.

"ld: file universal (3 slices) not contain a(n) armv7s slice: /users/victorray/desktop/maxfashionretailiphone/maxfashionretailiphone/libflurryanalytics.a architecture armv7s clang: error: linker command failed exit code 1 (use -v see invocation)"

i tried searching hard solution, couln't find one. can please help?

go go build settings of project , there remove armv7s valid architecture or download new libflurryanalytics.a build ios 6.x

iphone compiler-errors

Android:Sending data periodically -



Android:Sending data periodically -

i have tried send info on bluetooth whenever slide seekbar using seekbar's onprogresschanged() method , every thing works fine.

when tried same using accelerometer's onsensorchanged() method,i.e when write code transmission in onsensorchanged() method,no date beingness written bluetooth

i guess accelerometer's onsensorchanged() method getting called tooo frequently(like 1000 times per second).i want cut down speed of writing info bluetooth.

is there way transmit info periodically? illustration 1 reading every 3 milliseconds.

i'm pretty sure can set sensitivity of sensor, or min alter before listener called 1 time again (a bit finding location).

if fails, can set in little check based on info alter min amount, or using scheme time calculate difference lastly time allowed write data, , check whatever time want delay.

android

html - Two iframe's. A menu with links. The other, where the websites appear. I need the websites to always appear in the iframe -



html - Two iframe's. A menu with links. The other, where the websites appear. I need the websites to always appear in the iframe -

demo: http://mydemos.site90.net/

basically it's web protal of different sites. when user clicks 1 of links site show downsized fit in iframe on left. , user go through site site stays in iframe instead of opening in anther window. , googles translater translate ever in iframe. googles translater showing it's search bar , menu top reason after translation , of sites not beingness downsized. i'm new coding code might measy. help much needed.

<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3c.org/tr/1999/rec-html401-19991224/loose.dtd"> <!-- saved url=(0014)about:internet --><html><head><title>demo</title> <meta content="text/html; charset=iso-8859-1" http-equiv=content-type> <style type=text/css>body { background-color: #000000 } </style> <style type=text/css>a:link { color: #bdbdbd } a:visited { color: #bdbdbd } a:hover { color: #ffffff; text-decoration: none } a:active { color: #bdbdbd; text-decoration: none } </style> <script type=text/javascript"></script> <!--[if lt ie 7]> <style type="text/css"> img { behavior: url("pngfix.htc"); } </style> <![endif]--> <style type=text/css media=screen>#youtube2 { visibility: hidden } </style> <meta name=generator content="mshtml 8.00.6001.19394"></head> <body> <iframe style="z-index: 10; position: fixed; border-bottom-style: none; padding-bottom: 0px; border-right-style: none; margin: 0px; padding-left: 0px; width: 79%; padding-right: 0px; border-top-style: none; height: 100%; border-left-style: none; top: 0px; padding-top: 0px; left: 0px" id=iframe1 border=0 src="http://www.crimemapping.com/map.aspx" frameborder=0 name=iframe1 cellspacing="0"></iframe></iframe> <div style="z-index: 10; position: absolute; text-align: left; padding-bottom: 0px; margin: 0px; padding-left: 0px; width: 134px; padding-right: 0px; height: 20px; top: 9px; padding- top: 0px; left: 80%" id=bv_text2><a style="text-decoration: none" href="http://craigslist.com/"><span style="font-family: arial; color: #ffffff; font-size: 18px"><strong><i>demo<span style="color: red">d</span>demo</i></strong></span></a></div></a></b></span> <div> </div> <div style="z-index: 10; position: absolute; text-align: left; padding-bottom: 0px; margin: 0px; padding-left: 0px; width: 49px; padding-right: 0px; height: 16px; top: 50px; padding- top: 0px; left: 80%" id=bv_text15><span style="font-family: arial; color: #ffffff; font-size: 20px" face="arial" color="#ffffff"><b><a style="text-decoration: none"> <a><a href="http://free-website-translation.com/" id="ftwtranslation_button" hreflang="en" title="" style="border:0;"><img src="http://free-website- translation.com/img/fwt_button_en.gif" id="ftwtranslation_image" alt="free website translator" style="border:0;"/></a> <script type="text/javascript" src="http://free-website- translation.com/scripts/fwt.js" /></script></a></b></span></div> <div style="z-index: 10; position: absolute; text-align: left; padding-bottom: 0px; margin: 0px; padding-left: 0px; width: 49px; padding-right: 0px; height: 16px; top: 100px; padding- top: 0px; left: 80%" id=bv_text15><span style="font-family: arial; color: #ffffff; font-size: 20px" face="arial" color="#ffffff"><b><a style="text-decoration: none" href="http://www.youtube.com" <a>demo1</a></b></span></div> </body> </div>

you need provide ids iframe elements first, can set links in other iframe point first iframe providing target id in anchor a tags target="iframe1". suppose have simple 2 iframes web layout:

<html> <head> <title>link 1 iframe iframe</title> <head> <body> <iframe id="iframe1" src="http://example.com"></iframe> <iframe id="iframe2" src="some_page_with_links.html"></iframe> </body> </html>

and some_page_with_links.html document iframe2 has structure:

<html> <head> <title>this iframe2 contains links iframe1</title> <head> <body> <a href="http://www.google.com" target="iframe1">open google in iframe1</a> </body> </html>

the link in iframe2 tell browser open in iframe1, set target property of anchor a tag.

do note however, won't work external domains in case have set x-frame-options response header sameorigin in web server. other limitations might apply, depending on configuration , if plan on linking external domains.

i've noted have html tag closing errors in illustration linked to. example:

<a style="text-decoration: none" href="www.ebay.com" <a>demo2</a>

should be:

<a style="text-decoration: none" href="www.ebay.com" target="id_of_iframe1">demo2</a>

cheers!

html css css3

How to Remove Remote FTP Folders older than 3 days in PHP -



How to Remove Remote FTP Folders older than 3 days in PHP -

i need remove folders in ftp storage older 3 days. mean creation date, not modification date. should php ftp commands. here code don't work properly:

$skip = array('.', '..', '.ftpquota', '.htaccess'); $expire_date = date('y-m-d', strtotime('-3 days', time())); $ff_list = ftp_nlist($con, $db_dir); foreach($ff_list $item) { if(in_array($item, $skip)) { continue; } $mod_time = ftp_mdtm($con, $item); if(strtotime($expire_date ) >= $mod_time) { ftp_rmdir($con, $item); } }

please allow me know how create okay...

php ftp

elisp - Emacs Auto Load Color Theme by Time -



elisp - Emacs Auto Load Color Theme by Time -

can allow emacs automatically load theme ? or command @ customized time ? want m-x load-theme ret solarized-light when @ office @ 9:00am , m-x laod-theme ret solarized-dark when home , continued on emacs @ 8:00pm.

to expand on @anton kovalenko's answer, can current time using current-time-string elisp function , extracting current time of day in hours.

if want write total implementation, (warning, not debugged):

;; <color theme initialization code> (setq current-theme '(color-theme-solarized-light)) (defun synchronize-theme (setq hr (string-to-number (substring (current-time-string) 11 13))) ;;closes (setq hour... (if (member hr (number-sequence 6 17)) (setq '(color-theme-solarized-light)) (setq '(color-theme-solarized-dark))) ;; end of (if ... (if (eq current-theme) nil (setq current-theme now) (eval now) ) ) ;; end of (defun ... (run-with-timer 0 3600 synchronize-theme)

for more info on functions used, see next sections of emacs manual:

time of day strings string conversions idle timers contains number sequence

emacs elisp

ios - Convert NSDict to NSDate -



ios - Convert NSDict to NSDate -

this question has reply here:

nsdateformatter question 3 answers

i trying convert nsdict nsdate. can suggest example.

thanks in advance.

nssstring *str = [dict objectforkey:@"billdate"]; nsdateformater *f = [[nsdateformatter alloc] init]; nslocale *uslocale = [[nslocale alloc] initwithlocaleidentifier:@"en_us"]; f.locale = uslocale; f.dateformat = @"mm/dd/yyyy"; // format string uses format patterns unicode technical standard #35 nsdate *date = [f datefromstring:str];

ios date

winforms - Set groupbox invisible or make a shadow over it c# -



winforms - Set groupbox invisible or make a shadow over it c# -

i seek understand how work groupboxes in windowsforms. question now. have 2 groupboxes 2 radiobuttons each one. want when illustration radiobutton 2 groupbox1 clicked whole groupbox2 invisible or improve set white shadow on , not allow user utilize it. read here did not find http://msdn.microsoft.com/en-us/library/system.windows.forms.groupbox.aspx. tried property visible create whole window invisible. here illustration code. in advance

using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.windows.forms; namespace groupbox { public partial class form1 : form { public form1() { initializecomponent(); radiobutton1.checked = true; radiobutton3.checked = true; } private void groupbox1_enter(object sender, eventargs e) { if (radiobutton4.checked == true) { this.visible = false; } } private void groupbox2_enter(object sender, eventargs e) { if (radiobutton2.checked == true) { this.visible = false; } } } }

also read can create groupbox invisible have it's contents visible? there anyway without panels?

try this:

public partial class form1 : form { public form1() { initializecomponent(); radiobutton1.checked = true; radiobutton3.checked = true; radiobutton2.checkedchanged += radiobutton2_checkedchanged; } void radiobutton2_checkedchanged(object sender, eventargs e) { groupbox2.enabled = !radiobutton2.checked; } }

c# winforms

sql server - SQL Procedure - Begin Transaction & Commit -



sql server - SQL Procedure - Begin Transaction & Commit -

hi writing procedure "pro_reallocate_block" within that, calling procedure "pro_remove_allocation". if set begin transaction main procedure "pro_reallocate_block", in case of error occurrence in main procedure revert sub procedure "pro_remove_allocation".

create procedure pro_reallocate_block( @blockid int, @blockname nvarchar(max) ) execute caller begin set xact_abort, nocount on; begin seek set transaction isolation level serializable begin transaction declare @allocatedblockid int exec pro_remove_allocation @blockid if((select count(blockid) blocks blockid=@blockid)>0) select * blocks blockid=@blockid else select * blocks bdefault=1 commit transaction set transaction isolation level read committed end seek begin grab if xact_state() <> 0 begin rollback transaction declare @errormessage nvarchar(4000); declare @errorseverity int; declare @errorstate int; select @errormessage = error_message(), @errorseverity = error_severity(), @errorstate = error_state(); raiserror (@errormessage, @errorseverity, @errorstate); end end grab end

sql-server sql-server-2008

php - Import tumblr post to wordpress blog -



php - Import tumblr post to wordpress blog -

when add together new post in tumblr account, automatically post of tumblr sync wordpress account. not necessary @ sync time have logged in wordpress. in simple words, tumblr post automatically shown wordpress blog. donot know how work. if body have plugin or api match requirement. much thankful.

i using plugin :- http://wordpress.org/extend/plugins/tumblr-importer/

but problem have import every time post added in tumblr.hope makes sense. annoying me. tia

you have every time.

duplicating content in wp.com blog cause google assume you're spammer, propagating same material around web (which want do). drastically cut down search engine rankings of both blogs; tumblrs have virtually no googlejuice, wp blogs have great deal, , destroy that.

wordpress.com not aggregator; it's blogging platform. facebook, friendfeed, , lesser extent tumblr aggregators. can pull wp.com blog tumblr, fb, ff, etc, not other way around. staff have set things content here has original here.

php wordpress wordpress-plugin tumblr

The VMware Authorization Service is not running -



The VMware Authorization Service is not running -

windows not start vmware authorise service on local computer.

error 1075 : dependency service not exist or has been marked deletion

i have installed windows7 home basic not geeting - local user , group alternative in computer managment , login admin though not able start service manually

to prepare solution followed: this

1.click start , type run

2.type services.msc , click ok

3.scroll downwards list , locate vmware authorization service.

4.click start service, unless service showing status of started.

service vmware

sql - array of distinct values aggregated from an array column in Postgres -



sql - array of distinct values aggregated from an array column in Postgres -

suppose have (in postgresql 9.1) table identifier, column of type integer[] , other columns (at to the lowest degree one, although there might more) of type integer (or other can summed).

the goal have aggregate giving each identifier sum of "summable" column , array of distinct elements of array column.

the way can find utilize unnest function on array column in subquery , bring together subquery aggregating "summable" columns.

a simple illustration follows:

create temp table (id integer, aint integer[], summable_val integer); insert values (1, array[1,2,3], 5), (2, array[2,3,4], 6), (3, array[3,4,5], 2), (1, array[7,8,9], 19); u ( select id, unnest(aint) t grouping 1,2 ), d ( select id, array_agg(distinct t) ar u grouping 1), v ( select id, sum(summable_val) val grouping 1 ) select v.id, v.val, d.ar v bring together d on v.id = d.id;

the code above intended question can better? main drawback of solution reads , aggregate table twice might troublesome larger tables.

some other solution general problem avoid using array column , agregate "summable" column each array fellow member , utilize array_agg in aggregation - @ to the lowest degree i'd stick array way.

thanks in advance ideas.

the query may little bit faster (i suppose) cannot see remarkable optimizations:

select a.id, sum(summable_val) val, ar (select id, array_agg(distinct t) ar (select id, unnest(aint) t grouping 1,2) u grouping 1) x bring together on x.id = a.id grouping 1,3

sql arrays postgresql aggregation

webview - pyobjc webuidelegate functions not called -



webview - pyobjc webuidelegate functions not called -

i have linked webview uidelegate browserwindowcontroller in interface builder, delegate implements webuidelegate functions. in browserwindowcontroller class, do:

class browserwindowcontroller(nswindowcontroller):

webview = objc.iboutlet() def windowdidload(self): self.webview.setuidelegate_(self) def webviewdidstartload_(self, webview): print "did load start" def webview_didfailloadwitherror_(self, webview, error): print "error" def webviewdidfinishload_(self, webview): print "did finish load" def webview_shouldstartloadwithrequest_navigationtype_(self, webview, request, nav_type): print "load req"

none of lastly 4 functions, part of webuidelegate, called. tried doing (what formal protocol, though informal): class browserwindowcontroller(nswindowcontroller, webkit.protocols.webuidelegate):

but not work. have implemented webview webpolicydelegate same way , work. why doesn't webuidelegate work? have linked way have read in docs. missing informal protocol?

according apple's documentation(1) delegate protocol not have selector named webviewdidstartload:. selector is "uiwebviewdelegate" protocol, that's used on ios, not osx.

1: https://developer.apple.com/library/mac/#documentation/cocoa/reference/webkit/protocols/webuidelegate_protocol/reference/reference.html

webview pyobjc

C# Copy substring of a string then put it before the next word of the string -



C# Copy substring of a string then put it before the next word of the string -

i trying re-create lastly character of every word of string set copied character first position of next word. example, if come in string "the quick brownish fox jumps on lazy dog", output should "the equick kbrown nfox xjumps sover rthe elazy ydog";

here have far:

string s = "the quick brownish fox jumps on lazy dog"; (int = 0; < s.length; a++) { string b = s.substring(a,1); if (b == " ") { string c = s.substring(a - 1, 1); string d = s.insert (a+1, c); console.write(d); } }

the result of this : equick brownish fox jumps on lazy dogthe quick kbrown fox jumps on lazy dogthe quick brownish nfox jumps on lazy dogthe quick brownish fox xjumps o ver lazy dogthe quick brownish fox jumps sover lazy dogthe quick brownish fox jumps on rthe lazy dogthe quick brownish fox jumps on elazy dogthe quick br own fox jumps on lazy ydog

what trying accomplish output "the equick kbrown nfox xjumps sover rthe elazy ydog"

thanks answered way :)

what this?

string s = "the quick brownish fox jumps on lazy dog"; char lastchar = default(char); bool addlastchar = false; var stringbuilder = new stringbuilder(s); (int = 0; < stringbuilder.length; i++) { var ch = stringbuilder[i]; // todo: consider using char.iswhitespace(ch) method call. // please note: homecoming true different whitespace characters (tabulation, line feed, carriage return, etc). if (ch == ' ') { addlastchar = true; } else { if (addlastchar) { stringbuilder.insert(i, lastchar); addlastchar = false; } lastchar = ch; } } var result = stringbuilder.tostring();

the code works fine strings more 1 space in middle, this:

string s = "the quick brownish fox jumps on lazy dog";

c#

dojo - JavaScript: Checking to see if an array of objects doesn't have a duplicate depending on a particular property? -



dojo - JavaScript: Checking to see if an array of objects doesn't have a duplicate depending on a particular property? -

i have array of objects, objects can this:

{name: "object1", type: "event", props: {internalid: 1}} {name: "object2", type: "event", props: {internalid: 1}}

i want loop through array of these objects , want create new array of objects no duplicates (for me 2 items duplicates if have same internalid in props property)

i wondering best , efficient way "unique" objects original array , in new 1 based on internalid property?

thanks

you accomplish pretty uniq method underscore or lo-dash. optimize things bit if array sorted. both libraries have documented code, @ approach problem.

here example:

var objs = [{ name: "object1", type: "event", props: { internalid: 1 } }, { name: "object2", type: "event", props: { internalid: 1 } }, { name: "object3", type: "event", props: { internalid: 2 } }]; var result = _.uniq(objs, false, function (item) { homecoming item.props.internalid; });

javascript dojo

c - Traversing through a linked list -



c - Traversing through a linked list -

#include<stdio.h> struct node { int item; struct node *link }; main() { struct node *start,*list; int i; start = (struct node *)malloc(sizeof(struct node)); list = start; start->link = null; for(i=0;i<10;i++) { list->item = i; list->link = (struct node *)malloc(sizeof(struct node)); } list->link = null; while(start != null) { printf("%d\n",start->item); start = start->link; } }

as title suggests in trying traverse through linked list itteratively expected output 0 1 . . 9 , observed output : 9 wrong code ?

it because of 1 statement in code. forgot point next link, when tried allocate new link. because of allocating @ 1 pointer, having memory leak.

#include<stdio.h> struct node { int item; struct node *link }; main() { struct node *start,*list; int i; start = (struct node *)malloc(sizeof(struct node)); list = start; start->link = null; for(i=0;i<10;i++) { list->item = i; list->link = (struct node *)malloc(sizeof(struct node)); list = list->link; } list->link = null; while(start != null) { printf("%d\n",start->item); start = start->link; } }

c data-structures linked-list

How to Get Maven Project Version From Java Method as Like at Pom -



How to Get Maven Project Version From Java Method as Like at Pom -

i can variable's values pom file i.e.:

${project.version}

and developing custom maven plugin , can set expressions don't want it. how can in java method pom file?

ps: system.getproperty("project.version") doesn't work, should find generic solution because utilize @ other things i.e. getting bamboo build number etc.

i did in web project using maven-war-plugin inject version manifest, getting there java code. see no reason why similar can't done non-web project.

e.g.

<plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-war-plugin</artifactid> version>2.4</version> <configuration> <archive> <manifest> <adddefaultimplementationentries>true</adddefaultimplementationentries> </manifest> </archive> </configuration> </plugin>

then in java (excluding error handling):

public string getmavenversion(servletcontext ctx) { string appserverhome = ctx.getrealpath("/"); file manifestfile = new file(appserverhome, "meta-inf/manifest.mf"); manifest mf = new manifest(); mf.read(new fileinputstream(manifestfile)); attributes atts = mf.getmainattributes(); homecoming atts.getvalue("implementation-build"); }

java maven maven-plugin-development

jquery - client side display results of asynchronous tasks [django] -



jquery - client side display results of asynchronous tasks [django] -

i'd know if there improve way/pattern of doing have in mind.

i have server side process executes asyncronous tasks. planning utilize celery this. asynchronous tasks can have sub tasks. though need review history of executed tasks , kid tasks, i'm not planning utilize celery result backend, hear task_finished signals , update existing django models i'm using logs needed.

the question around way study status of these tasks user?

so in web ui, there widget/block of html somewhere tasks , status listed. need display sub tasks grouped parent tasks , individual sub task status. on page, i'd poll using jquery everytime task executed , on interval.

my thought utilize atom according spec, strict rules around content element (link spec) allowed hold. specific concern around how represent kid tasks when using atom.

the other thought utilize straight json , parse accordingly.

does know of improve way/pattern utilize this?

jquery django asynchronous atom

cmd - Can't connect to server (timed out if winsock.dll error 10060) when run blat command to send mail -



cmd - Can't connect to server (timed out if winsock.dll error 10060) when run blat command to send mail -

i using blat command line tool sending mail service command.

first run install command store mail service server create entry in registry that.........

first set smtp server smtp.mail.yahoo.com error same.

after execute

blat c:\temp.txt -to abcdef@gmail.com -superdebug

after error got.......

c:\blat310\full>blat c:\temp.txt -to abcdef@gmail.com -superdebug blat v3.1.0 (build : feb 2 2013 11:00:32) 32-bit windows, full, unicode checking alternative -to superdebug: init_winsock(), wsastartup() returned 0 (no_error) superdebug: hostname <smtp.mail.apac.gm0.yahoodns.net> resolved ip address 10 6.10.167.87 superdebug: official hostname smtp.mail.apac.gm0.yahoodns.net superdebug: attempting connect ip address 106.10.167.87 superdebug: ::connect() returned error 10060, retry count remaining 1 superdebug: ::connect() returned error 10060, retry count remaining 0 superdebug: connection returned error 10060 error: can't connect server (timed out if winsock.dll error 10060) superdebug: ::say_hello() failed connect, retry count remaining 1 superdebug: init_winsock(), wsastartup() returned 0 (no_error) superdebug: hostname <smtp.mail.apac.gm0.yahoodns.net> resolved ip address 10 6.10.167.87 superdebug: official hostname smtp.mail.apac.gm0.yahoodns.net superdebug: attempting connect ip address 106.10.167.87 superdebug: ::connect() returned error 10060, retry count remaining 1 superdebug: ::connect() returned error 10060, retry count remaining 0 superdebug: connection returned error 10060 error: can't connect server (timed out if winsock.dll error 10060)

error 10060 means connection times out, because there's nil listening on port 995 on either smtp.mail.yahoo.com or smtp.mail.apac.gm0.yahoodns.net. why seek connect port anyway? it's used pop3 on ssl (i.e. mail service retrieval), not smtp (mail submission).

try either port 25 or (more likely) port 587. latter default port message submission (see rfc 4409 details).

command cmd mail-server blat

Fill dynamic array using curly bracket notation C++ -



Fill dynamic array using curly bracket notation C++ -

this question has reply here:

how initialise dynamic array in c++? 9 answers

is there way in c++ fill array allocated this

int **a = new int[4][2];

so it's filled values in 1 line this

int [4][2] = {{2,3,4},{5,6,7}};

you can in c++11 universal initialization notation:

int(*a)[2] = new int[2][2]{{1,2},{3,4}};

c++ c arrays c++11 initialization

ios - Convert a Web service from GET to POST -



ios - Convert a Web service from GET to POST -

i have created web service create communication between ios application , joomla web site, , used method communicate between mobile application , web service , between web service , controller (php file work , homecoming data) , didn't find how convert implementation post method here actual scheme :

ws.php : it's web service (simple illustration )

<?php $id = $_get['id'] ; // info url // here create testes // redirect controller of joomla component receive // phone call of request url attribute "action" of // existing html form implement login system, added // parameter called web service help me modify controller // create difference between normal phone call , web service phone call header("location: index.php?option=com_comprofiler&task=login&ws=1&id=1"); ?>

controller.php : receiver of web service phone call , web phone call (from browser)

<?php // code added me, in existent controller of component // waiting form submitting, got convert info post here if (isset($_get['ws'])) // it's web service phone call { $_post['id'] = $_get['id'] ; // task ... if ($correctlogin) // illustration echo "1" else echo '0'; } ?>

i didn't set real implementation, , it's simple illustration of system, it's same

call mobile

nsurl *url = [[nsurl alloc]initwithstring:@"http://localhost/ws.php?id=1"]; nsdata *dataurl= [nsdata datawithcontentsofurl:url]; nsstring *str = [[nsstring alloc]initwithdata:dataurl encoding:nsutf8stringencoding]; if(![str isequaltostring:@"0"]) nslog(@"connected"); else nslog(@"not connected");

so don't want utilize method, want receive info mobile using post , send info controller using post also, best solution ?

if want app send info using post method, i'm code. hope help.

it takes info sent in dictionary object. ecodes info sent post , returns response (if want results in string format can utilize [[nsstring alloc] initwithdata:dresponse encoding: nsasciistringencoding]; when returning data)

-(nsdata*) getdata:(nsdictionary *) postdatadic{ nsdata *dresponse = [[nsdata alloc] init]; nsurl *nurl = [nsurl urlwithstring:url]; nsdictionary *postdict = [[nsdictionary alloc] initwithdictionary:postdatadic]; nsdata *postdata = [self encodedictionary:postdict]; // create request nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:nurl]; [request sethttpmethod:@"post"]; // define method type [request setvalue:[nsstring stringwithformat:@"%d", postdata.length] forhttpheaderfield:@"content-length"]; [request setvalue:@"application/x-www-form-urlencoded charset=utf-8" forhttpheaderfield:@"content-type"]; [request sethttpbody:postdata]; // peform request nsurlresponse *response; nserror *error = nil; dresponse = [nsurlconnection sendsynchronousrequest:request returningresponse:&response error:&error]; homecoming dresponse; }

this method prepares dictionary info post

- (nsdata*)encodedictionary:(nsdictionary*)dictionary { nsmutablearray *parts = [[nsmutablearray alloc] init]; (nsstring *key in dictionary) { nsstring *encodedvalue = [[dictionary objectforkey:key] stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]; nsstring *encodedkey = [key stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]; nsstring *part = [nsstring stringwithformat: @"%@=%@", encodedkey, encodedvalue]; [parts addobject:part]; } nsstring *encodeddictionary = [parts componentsjoinedbystring:@"&"]; homecoming [encodeddictionary datausingencoding:nsutf8stringencoding]; }

ios web-services post joomla get

android - Why does my app crash when my service makes an alertdialog? -



android - Why does my app crash when my service makes an alertdialog? -

hi i'm trying create service runs in background after user puts in amount of time. after amount of time alartdialog appears , ringtone user selected rings until cancel it. unfortunately error causes app crash. if need anymore info inquire :)

my service class

import java.util.timer; import java.util.timertask; import org.holoeverywhere.app.alertdialog; import org.holoeverywhere.preference.preferencemanager; import org.holoeverywhere.preference.sharedpreferences; import android.app.service; import android.content.context; import android.content.dialoginterface; import android.content.intent; import android.media.ringtone; import android.media.ringtonemanager; import android.net.uri; import android.os.ibinder; import android.os.vibrator; import android.util.log; public class countdownservice extends service { @override public void oncreate() { super.oncreate(); } int hr = 990; int min = 990; int sec = 990; context c; alertdialog alertdialog; sharedpreferences getprefs; vibrator v; ringtone r; @override public int onstartcommand(intent intent, int flags, int startid) { string input = intent.getstringextra("timeleft"); string[] strarray = input.split(","); c = this.getapplicationcontext(); getprefs = preferencemanager.getdefaultsharedpreferences(c); v = (vibrator) c.getsystemservice(context.vibrator_service); build(); (string t : strarray) { if (hour == 990) { hr = integer.parseint(t); } else { if (min == 990) { min = integer.parseint(t); }else{ if (sec == 990) { sec = integer.parseint(t); } } } } timer timer = new timer(); timertask tt = new timertask() { @override public void run() { sec--; updatetime(); } }; timer.schedule(tt, 0, 1000); homecoming start_sticky; } private void build() { alertdialog.builder alertdialogbuilder = new alertdialog.builder(c); // set title alertdialogbuilder.settitle("time's up!!!"); // set dialog message alertdialogbuilder.setmessage("press ok stop alarm") .setcancelable(true) .setneutralbutton("ok", new dialoginterface.onclicklistener() { public void onclick(dialoginterface dialog, int id) { if (r != null) { if (r.isplaying()) { r.stop(); } } alertdialog.cancel(); alertdialog.cancel(); } }); alertdialog = alertdialogbuilder.create(); } @override public ibinder onbind(intent arg0) { homecoming null; } private void updatetime() { if (hour <= 0 && min <= 0 && sec <= 0) { done(); } if (sec < 0) { min --; sec = 59; } if (min < 0) { hr --; min = 59; } } private void done() { uri uri; boolean notmuted = getprefs.getboolean("muted", true); boolean viberate = getprefs.getboolean("viberate", true); string strringtonepreference = getprefs.getstring("app_ringtone", null); log.v("alarm", "a " + strringtonepreference); if (viberate) { v.vibrate(1000); } if (notmuted) { if (strringtonepreference != null) { uri = uri.parse(strringtonepreference); log.v("alarm", "was parsed"); } else { log.v("alarm", "was not parsed"); uri = null; } playsound(this.getapplicationcontext(), uri); } } private void playsound(context context, uri alert) { r = ringtonemanager.getringtone(context, alert); if (r != null) { r.play(); log.v("alarm", "was not null"); } alertdialog.show(); } }

my log

02-10 19:13:07.875: e/androidruntime(23231): fatal exception: timer-0 02-10 19:13:07.875: e/androidruntime(23231): java.lang.runtimeexception: can't create handler within thread has not called looper.prepare() 02-10 19:13:07.875: e/androidruntime(23231): @ android.os.handler.<init>(handler.java:121) 02-10 19:13:07.875: e/androidruntime(23231): @ android.view.viewrootimpl.<init>(viewrootimpl.java:371) 02-10 19:13:07.875: e/androidruntime(23231): @ android.view.windowmanagerimpl.addview(windowmanagerimpl.java:267) 02-10 19:13:07.875: e/androidruntime(23231): @ android.view.windowmanagerimpl.addview(windowmanagerimpl.java:215) 02-10 19:13:07.875: e/androidruntime(23231): @ android.view.windowmanagerimpl$compatmodewrapper.addview(windowmanagerimpl.java:140) 02-10 19:13:07.875: e/androidruntime(23231): @ android.app.dialog.show(dialog.java:278) 02-10 19:13:07.875: e/androidruntime(23231): @ com.chair49.holotimer.countdownservice.playsound(countdownservice.java:169) 02-10 19:13:07.875: e/androidruntime(23231): @ com.chair49.holotimer.countdownservice.done(countdownservice.java:147) 02-10 19:13:07.875: e/androidruntime(23231): @ com.chair49.holotimer.countdownservice.updatetime(countdownservice.java:113) 02-10 19:13:07.875: e/androidruntime(23231): @ com.chair49.holotimer.countdownservice.access$0(countdownservice.java:111) 02-10 19:13:07.875: e/androidruntime(23231): @ com.chair49.holotimer.countdownservice$1.run(countdownservice.java:67) 02-10 19:13:07.875: e/androidruntime(23231): @ java.util.timer$timerimpl.run(timer.java:284)

you can't phone call ui stuff background thread. can utilize runonuithread().

android android-service android-alertdialog

sql - Check order of rows in mysql -



sql - Check order of rows in mysql -

need help mysql.

i have table total of bids, need check if there more 3 bids from same user 1 after another.

here code example:

$all = sql_get('select bids bids auction_id = 1 order amount asc'); $total = 0; foreach ($all $bid) { if ($bid->user_id == $user->id) { if (++$total <= 3) continue; $bid->burned = true; sql_store($bid); show_error('you cant have more 4 bids 1 after another, lastly bid burned.'); } else { $total = 0; } }

is there way in single query ?

select user_id, case when @user_id = user_id @rownum := @rownum + 1 else ((@user_id := user_id) * 0) + (@rownum := 1) end rownum ( select user_id bids, (select @rownum := 0, @user_id := null) vars auction_id = 1 order created desc) h having user_id = '{$user->id}' , rownum >= 3

simply parse user_id query , know if there 3 in row. asumes save time rows created created column.

mysql sql

jsf - ViewState custom saving method - is it possible? -



jsf - ViewState custom saving method - is it possible? -

afaik in jsf viewstate stored jvm memory when javax.faces.state_saving_method set "server".

is there way configure / setup custom saving method that, example, can utilize (eventually, disk backed) storage engine (ie. memcache / redis) store viewstate ?

something equivalent of custom session.save_handler in php.

is stored jvm memory

to more precise, it's stored in http session in turn managed container.

so, if want customize session management, @ servletcontainer level. it's unclear 1 you're using, in case of illustration tomcat, refer manager component document under chapters "persistent manager" session storage on disk.

jsf viewstate

backbone.js - Filter list of items -



backbone.js - Filter list of items -

i have list of items , query textfield. when come in query in textfield, want filter list of items based on query. how can this?

in view added event:

events: -> 'submit #query_form' : 'filterlinks'

this triggers function first empty list , want show items meet query criteria:

filterlinks: -> query = $('#query').val() @collection.reset()

how can filter list?

edit: finish view:

template: jst['links/index'] initialize: -> @collection.on('reset', @render, this) @collection.on('add', @appendlink, this) events: -> 'submit #new_link' : 'createlink' 'submit #query_form' : 'filterlinks' render: -> $(@el).html(@template()) @collection.each(@appendlink) createlink: (event) -> event.preventdefault() @collection.create title: $('#title').val() description: $('#description').val() url: $('#url').val() category: $('#category').val() votes: 0 $('#message').append('<div>link has been added succesfully!</div>').fadeout(5000) appendlink: (link) -> view = new hotlynx.views.link(model: link) $('#all_links').append(view.render().el) filterlinks: -> alert($('#query').val()) @collection.reset()

you can utilize underscore's filter method filter collection , homecoming results want. see: http://underscorejs.org/#filter

then you'd utilize result of filter re-render view displays items.

backbone.js

r - cannot handle matrix/array columns with write.dbf -



r - cannot handle matrix/array columns with write.dbf -

hope problem. first time me , it's little bit tricky describe.

i want add together attributes dbf file , save afterwards utilize in qgis. elections , info votes 11 parties in absolute , relative values. utilize shapefiles bundle this, tried foreign.

my system: rstudio 0.97.311, r 2.15.2, shapefile 0.7, foreign 0.8-52, ubuntu 12.04

try #1 => no problems

shpdistricts <- read.shapefile(filename) shpdatadistricts <- shpdistricts$dbf[[1]] shpdatadistricts <- shpdatadistricts[, -c(3, 4, 5)] # delete columns shpdistricts$dbf[[1]] <- shpdatadistricts write.shapefile(shpdistricts, filename))

try #2 => "error in get("write.dbf", "package:foreign")(dbf$dbf, out.name) : cannot handle matrix/array columns"

shpdistricts <- read.shapefile(filename) shpdatadistricts <- shpdistricts$dbf[[1]] shpdatadistricts <- shpdatadistricts[, -c(3, 4, 5)] # delete columns shpdatadistricts <- cbind(shpdatadistricts, votesdistrict[, 2]) # add together new column names(shpdatadistricts)[5] <- "spoe" shpdistricts$dbf[[1]] <- shpdatadistricts write.shapefile(shpdistricts, filename))

the write function returns "error in get("write.dbf", "package:foreign")(dbf$dbf, out.name) : cannot handle matrix/array columns"

so adding column (integer) data.frame, write.dbf function isn't able write out anymore. debugging 3 hours on simple issue. tried shapefiles bundle via opening shapefile , dbf file, time same problem.

when utilize foreign bundle straight (read.dbf).

if save dbf-file without voting info (only little adapations step 1+2), it's no problem. must have merge voting data.

i got same error message ("error in get("write.dbf"...) while working shapefiles in r using rgdal. added column shapefile, tried save output , got error. added column shapefile dataframe, when converted factor via as.factor() error went away.

shapefile$column <- as.factor(additional.column)

writepolyshape(shapefile, filename)

r gis spatial shapefile dbf

sql - MySQL query optimization: how to optimize voting calculations? -



sql - MySQL query optimization: how to optimize voting calculations? -

hope you're doing fine.

i need help bit database:

this database stores votes. users pick sound tracks like, , vote them. can vote 'up' or 'down'. easy pie. but, when comes calculating stats gets hairy.

meta

it's key-value styled table, stores commonly used stats (just sort-of caching):

mysql> select * meta; +-------------+-------+ | key | value | +-------------+-------+ | track_count | 2620 | | vote_count | 3821 | | user_count | 371 | +-------------+-------+ vote

the vote table holds vote itself. interesting field here type, value of means:

0 - app made vote, user voted track using ui 1 - imported vote (from external service) 2 - merged vote. same imported vote, makes note, user voted track using external service, , he's repeating himself using app. track

the track holds total stats itself. amount of likes, dislikes, likes external service (likesrp), dislikes external service (dislikesrp), likes/dislikes adjustments.

app

the app requires votes for:

5 up-voted tracks during lastly 7 days 5 down-voted tracks during lastly 7 days 5 up-voted tracks during lastly 7 days, votes of imported external service (vote.type = 1) 100 up-voted tracks during lastly month

to 100 most-up voted track utilize query:

class="lang-sql prettyprint-override">select t.hash, t.title, t.artist, coalesce(x.votestotal, 0) + t.likesadjust votesadjusted ( select v.trackhash, sum(v.vote) votestotal vote v v.createdat > now() - interval 1 month , v.vote = 'up' grouping v.trackhash order votestotal desc ) x right bring together track t on t.hash = x.trackhash order votesadjusted desc limit 0, 100;

this query working ok , honors adjustments (client wanted adjust track position in lists). same query used 5 up/down voted tracks. , query task #3 this:

class="lang-sql prettyprint-override">select t.hash, t.title, t.artist, coalesce(x.votestotal, 1) votestotal ( select v.trackhash, sum(v.vote) votestotal vote v v.type = '1' , v.createdat > now() - interval 1 week , v.vote = 'up' grouping v.trackhash order votestotal desc ) x right bring together track t on t.hash = x.trackhash order votestotal desc limit 0, 5;

the problem first query taking 2 seconds perform , have less 4k votes. end of year, figure 200k votes, kill database. i'm figuring out how solve puzzle.

and came downwards these questions:

did create database design wrong? mean, better? did create query wrong? anything else improve?

the first thing did caching. but, ok, solves problem drastically. i'm curious sql-related solution (always leaning towards perfection).

the sec thing had thought set calculated values meta table , alter them during voting procedure. i'm quite short on time seek out. worth way? or, how enterprise class apps solve these problems?

thanks.

edit

i can't believe forgot include indices. here are:

mysql> show indexes in vote; +-------+------------+-------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ | table | non_unique | key_name | seq_in_index | column_name | collation | cardinality | sub_part | packed | null | index_type | comment | +-------+------------+-------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ | vote | 0 | unique_userid_trackhash | 1 | userid | | 890 | null | null | | btree | | | vote | 0 | unique_userid_trackhash | 2 | trackhash | | 4450 | null | null | | btree | | | vote | 1 | index_trackhash | 1 | trackhash | | 4450 | null | null | | btree | | | vote | 1 | index_createdat | 1 | createdat | | 1483 | null | null | | btree | | | vote | 1 | userid | 1 | userid | | 1483 | null | null | | btree | | +-------+------------+-------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ mysql> show indexes in track; +-------+------------+----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ | table | non_unique | key_name | seq_in_index | column_name | collation | cardinality | sub_part | packed | null | index_type | comment | +-------+------------+----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ | track | 0 | primary | 1 | hash | | 2678 | null | null | | btree | | | track | 1 | index_likes | 1 | likes | | 66 | null | null | | btree | | | track | 1 | index_dislikes | 1 | dislikes | | 27 | null | null | | btree | | +-------+------------+----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+

this subjective question because much depends on exact requirements, , performance testing nobody here can on data. can reply questions , add together generic solutions might work you:

did create database design wrong? mean, better?

no. ideal design oltp.

did create query wrong?

no (although order by in subqeries redundant). performance of query much dependant on indexes on vote table, since main columns queried in part:

select v.trackhash, sum(v.vote) votestotal vote v v.createdat > now() - interval 1 month , v.vote = 'up' grouping v.trackhash

i suggest 2 indexes, 1 on trackhash , 1 on createdat, vote , type (this may perform improve 3 separate indexes, worth testing both ways). 200k rows not much data, right indexes shouldn't take long query info on lastly month.

anything else improve?

this much balancing act, depends on exact requirements best way proceed. there 3 main ways approach problem.

1. current approach (query vote table each time)

as mentioned before think approach should scalable application. advantage not require maintenance, , info sent application date , accurate. disadvantage performance, might take bit longer insert info (due updating indexes), , select data. preferred approach.

2. olap approach

this involve maintaining summary table such as:

create table votearchive ( trackhash char(40) not null, createddate date not null, appmadeupvotes int not null, appmadedownvotes int not null, importedupvotes int not null, importeddownvotes int not null, mergedupvotes int not null, mergeddownvotes int not null, primary key (createddate, trackhash) );

this can populated nightly running simple query

insert votearchive select trackhash, date(createdat), count(case when vote = 'up' , type = 0 1 end), count(case when vote = 'down' , type = 0 1 end), count(case when vote = 'up' , type = 1 1 end), count(case when vote = 'down' , type = 1 1 end), count(case when vote = 'up' , type = 2 1 end), count(case when vote = 'down' , type = 2 1 end) votes createdat > date(current_timestamp) grouping trackhash, date(createdat);

you can utilize table in place of live data. has advantage of date beingness part of clustered index, query beingness limited date should fast. disadvantage of if query table statistics accurate lastly time populated, much faster queries though. additional work maintain query. sec selection if nto query live data.

3. update statistics during voting

i including completeness implore not utilize method. accomplish in either application layer or via trigger , although allow querying of date info without having query "production" table open errors, , have never come accross advocates approach. every vote need insert/update logic should turn fast insert query longer process, depending on how maintenance there chance (albeit little of concurrency issues).

4. combination of above

you have 2 tables of same format vote table, , 1 table set out in solution 2, have 1 vote table storing today's votes, , 1 historic votes, , still maintain summary table, can combine today's info summary table date results without querying lot of data. again, additional maintenance, , more potential things go wrong.

mysql sql sql-optimization

javascript - Rotating a sprite on a canvas element -



javascript - Rotating a sprite on a canvas element -

i have player class sprite , want create face towards mouse pointer.

i'm using work out rotation of sprite should be:

this.rotation = -(math.atan2(this.x - mousestate.x, this.y - mousestate.y) * 180 / math.pi);

and in draw method of player class i'm doing this:

player.prototype.draw = function() { window.ctx.save(); window.ctx.translate(this.x + this.sprite.width / 2, this.y + this.sprite/height / 2); window.ctx.rotate(this.rotation); window.ctx.drawimage(this.sprite, this.x, this.y); window.ctx.restore(); }

it something, not want. sprite seems move wildly in circle around top left of canvas (x:0, y:0).

how can create sprite face towards mouse cursor, using centre point origin?

you're not translating back. note window.ctx.translate phone call added below, , notice how i've add together negative both x , y values.

player.prototype.draw = function() { window.ctx.save(); window.ctx.translate(this.x + this.sprite.width / 2, this.y + this.sprite/height / 2); window.ctx.rotate(this.rotation); window.ctx.translate(-this.x + this.sprite.width / 2, -this.y + this.sprite/height / 2); window.ctx.drawimage(this.sprite, this.x, this.y); window.ctx.restore(); }

basically, doing moving (translating) canvas context center object center, rotating (rotate), need move center point got from.

javascript html5 canvas

Custom Flip animation between fragments android support package -



Custom Flip animation between fragments android support package -

i trying find out how create flip animation between 2 fragments.

i have tried cardflip training guide, don't seem able accomplish it. using android back upwards bundle , set tween animation, not successful.

how implement flipping animations between fragment?

here first 2 xml created guide, maybe see if doing wrong. screen_flip_left_in.xml:

<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" > <!-- before rotating, set alpha 0. --> <alpha android:valuefrom="1.0" android:valueto="0.0" android:propertyname="alpha" android:duration="0" /> <!-- rotate. --> <rotate android:valuefrom="-180" android:valueto="0" android:propertyname="rotationy" android:interpolator="@android:anim/accelerate_decelerate_interpolator" android:duration="@integer/card_flip_time_full"/> <!-- half-way through rotation (see startoffset), set alpha 1. --> <alpha android:valuefrom="0.0" android:valueto="1.0" android:propertyname="alpha" android:startoffset="@integer/card_flip_time_half" android:duration="1" /> </set>

screen_flip_left_out.xml:

<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" > <!-- rotate. --> <rotate android:valuefrom="0" android:valueto="180" android:propertyname="rotationy" android:interpolator="@android:anim/accelerate_decelerate_interpolator" android:duration="@integer/card_flip_time_full" /> <!-- half-way through rotation (see startoffset), set alpha 0. --> <alpha android:valuefrom="1.0" android:valueto="0.0" android:propertyname="alpha" android:startoffset="@integer/card_flip_time_half" android:duration="1" /> </set>

android:propertyname objectanimator (honeycomb+) animations, not view animations gingerbread. card flip animation possible using honeycomb animator api's. created fork of back upwards library allow using animator apis nineoldandroids fragment transitions. utilize animator-transition branch of github project. 1 time have modified back upwards library @ http://developer.android.com/training/animation/cardflip.html create animator xml.

android

c++ - "Beautifying" macro -



c++ - "Beautifying" macro -

watching herb sutter's talk atomics @ c++ , beyond glimpsed @ thought of easy utilize lock/unlock mechanism may or may not come in future standard of language.

the mechanism looks likes:

atomic{ // code here }

not wanting wait future standard tried implementing myself, i've come this:

#define concat_impl(a, b) ## b #define concat(a, b) concat_impl(a, b) # define atomic(a) { \ static_assert(std::is_same<decltype(a), std::mutex>::value,"argument must of type std::mutex !");\ struct concat(atomic_impl_, __line__)\ {\ std::function<void()> func;\ std::mutex* impl;\ concat(atomic_impl_, __line__)(std::mutex& b)\ { \ impl = &b;\ impl->lock();\ }\ concat(~atomic_impl_, __line__)()\ { \ func();\ impl->unlock(); \ }\ } concat(atomic_impl_var_, __line__)(a);\ concat(atomic_impl_var_, __line__).func = [&]()

and usage:

std::mutex mut; atomic(mut){ // code here };}

the problem, obviously, }; i'd remove.

is possible in way?

you can trick of defining variables within if statement.

template <typename m> struct atomic_guard_ { explicit atomic_guard_(m& m) : lock(m) {} atomic_guard_(m const&) =delete; // since unfortunately have utilize uniform atomic_guard_(m&&) =delete; // initialization, create @ to the lowest degree little safe operator bool() const { homecoming false; } std::lock_guard<m> lock; }; #define atomic(m) \ if (atomic_guard_<std::decay<decltype(m)>::type> _{m}) {} else int main() { std::mutex m; atomic(m) { std::cout << "a\n"; } atomic(m) // works too, think ok std::cout << "b\n"; }

c++ c++11 macros

jquery - Drupal View - Like Google Images Search -



jquery - Drupal View - Like Google Images Search -

i'm trying create catalogue content, has similar function google image search. ie. when click icon/image, rows underneath shift downwards , expanded content image displayed.

can done css or need set specific way first

*edit: understand showing/hiding done javascript, meant can create div appear , force downwards rows underneath it, rather pushing downwards column underneath it

thanks

this can't done pure css, need javascript react click event.

jquery css drupal google-image-search

ddl - What is the best component to use, If I want to create a table from my talend job? -



ddl - What is the best component to use, If I want to create a table from my talend job? -

from job, trying create table ( if not exists ) selecting few records joining few tables ( create table xx select * t1 inner t2 etc ), talend job. using tmysqlrow component. not sure, right component utilize ddl operations ..!! please suggest right component use.

using tmysqlrow, working fine not consistent. times failing "java.sql.sqlexception: lock wait timeout exceeded; seek restarting transaction". because of query taking long time, or using tmysqlrow ddl operation wrong ? doing wrong ?

i able figure out issue. issue that, trying drop table in tmysqlrow component , connecting tmysqlrow create again. , these 2 not working out of single tmysqlconnection object. 1 waiting other 1 commit.

once, made both these tmysqlrow components work same tmysqlconnection object, issue got resolved.

the point larn here , of should work out of same connection object.

ddl sqlexception talend

run the app on iPhone 3GS os 6.1 using Xcode 4.3.2 -



run the app on iPhone 3GS os 6.1 using Xcode 4.3.2 -

i using xcode 4.3.2 , want run app on iphone 3gs when opening organizer window , showing following:

the version of ios on “iphone” not match of versions of ios supported development installation of ios sdk. please restore device version of os listed below, or update latest version of ios sdk; available here.

os installed on iphone 6.1 (10b141)

xcode supported ios versions latest 5.1 (9b176) 5.0 4.3 4.2

please suggest me .

since downgrading ios version hard , doesn’t sound alternative you, think must follow other option:

update latest version of ios sdk

the ios 6.1 sdk included in xcode 4.6.

iphone xcode ios6

asp.net web api - Error loading Ninject component ICache -



asp.net web api - Error loading Ninject component ICache -

i using ninject in asp.net web api project , have started receiving intermittent ninject error:

"error loading ninject component icache no such component has been registered in kernel's component container."

i'm using:

ninject 3.0.1.10 ninject.mvc3 3.0.0.6 ninject.web.common 3.0.0.7

they brought project nuget load modules in iocconfig.registerioc , have made no other changes or tweaks.

it may unrelated problem started occurring @ around same time started injecting ikernel 1 of constructors. didn't set binding having read "special resolver".

i have read through number of similar questions on here:

ninject + "error loading ninject component icache"

ninject , childkernel in mvc3 project: "error loading ninject component icache"

randomly-occurring ninject exception: "error loading ninject component icache"

although in each of these cases op has same error me solution not appropriate - not creating kid kernels , i'm not using bugged version of ninject.

found solution , thought share.

the problem was using ninject.mvc3 seems wrong bundle web-api.

instead need utilize ninject.web.webapi-rc bundle described post:

http://www.eyecatch.no/blog/2012/06/using-ninject-with-webapi-rc/

steps followed prepare are

uninstalled ninject.mvc3 , ninject.web.common delete of ninject files app_start folder. install ninject.web.common , ninject.web.webapi-rc nuget load modules in ninjectwebcommon.registerservices()

asp.net-web-api ninject

ruby on rails - How do migrations affect the schema.rb file? -



ruby on rails - How do migrations affect the schema.rb file? -

i little confused how migrations impact schema.rb file?

for illustration if write migration rename table column , run migratin , schema:load rake task too, when open schema.rb file should automatically changed have new column name? or should manually alter in there too?

also create_table*.rb files create original tables. automatically have t.timestamp field defined in them creates 2 created_at , updated_at fields in schema, if want remove plenty alter create_table*.rb file , take out t.timestamp them? , run migration? or 1 time again should manually alter shcema.rb file too?

so if can explain little bit how there work great.

the schema file automatically altered when run migrations. should never have manually edit it.

see this rails guide moer information.

ruby-on-rails ruby-on-rails-3.2

python - Non-greedy operator on re.sub -



python - Non-greedy operator on re.sub -

given next string:

>>> s = 'claude binyon [director / screenwriter] walter benjamin hare [play author]'

i want accomplish following:

'claude binyon,walter benjamin hare,'

i have next regex, greedy, replacing after [. how create next non-greedy work needed?

>>> re.sub('\[.+]',',',s) 'claude binyon ,'

try doing :

>>> re.sub('\[.+?]',',',s)

python regex

mysql - In PHP, how to achieve the same purpose like StringTokenizer in Java? -



mysql - In PHP, how to achieve the same purpose like StringTokenizer in Java? -

say have string 030512 jack 25 male\n030513 david 23 male\n030514 ..., how extract info string 2 dimensional table in php?

in java, can utilize stringtokenizer, like:

stringtokenizer linetokenizer = new stringtokenizer("030512 jack ...", "\n"); list<student> students = new arraylist<student>(); while(linetokenizer.hasmoretokens()) { string line = linetokenizer.nexttoken(); stringtokenizer itemtokenizer = new stringtokenizer(line, " "); string id = itemtokenizer.nexttoken(); string name = itemtokenizer.nexttoken(); string age = itemtokenizer.nexttoken(); string sext = itemtokenizer.nexttoken(); students.add(new student(id, name, age, sex)); }

actually, final goal extracting "table-like" info , store them mysql database.

i not familiar php, show me how in php, or practice implement two-dimensional info insertion mysql database?

not fancy easier understand in sentiment (requires string doesn't end newline though, , info correctly formatted):

$students = array(); //no newline @ end, or you'll have add together check in loop. $str = "030512 jack 25 male\n030513 david 23 male"; foreach(explode("\n", $str) $student_str) { list($id, $name, $age, $sex) = explode(" ", $student_str); array_push($students, array(":id"=>$id,":name"=>$name, ":age"=>$age, ":sex"=>$sex)); } //for db part has been quite absent. $conn = new pdo("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass); $query = "insert students (id, name, age, sex) values (:id, :name, :age, :sex)"; $prepared_query = $conn->prepare($query); foreach($students $student) { $prepared_query->execute($student); }

you of course of study execute queries in first loop instead if thats want.

php mysql stringtokenizer

scheme - How to (re)load files in Racket (X)REPL? -



scheme - How to (re)load files in Racket (X)REPL? -

suppose have file like

#lang racket/base (define (hello) (print "hello")) ... more definitions ...

and load definitions in file interactively work them in (x)repl. how do that?

if start (x)repl , (load "/tmp/hello.rkt"), hello function not made available me:

-> (hello) ; hello: undefined;

if (require (file "/tmp/hello.rkt")), result same. can (enter! (file "/tmp/hello.rkt")) , (hello) works, seems rather ... unintuitive , beginner-unfriendly.

is indeed way should done , should read on modules , namespaces browse , experiment code or there simpler way i'm overlooking?

n.b. found how load file racket via command line?, explains how run file. not how load in repl, can test/debug specific definitions, edit, reload, etc.

since files start #lang modules, nil if load them. (actually something, not help you.) best avoid using load completely, pretend it's not there.

now, using require right thing, instantiate module , give access names provides. in case, didn't provide means can't utilize hello. that, can add together (provide hello) file. that's not want, since seems want debug code. (ie, won't want provide module work on things.)

so right thing utilize enter!, or if you're using xrepl, there's more convenient ,en command. instantiate module , create repl utilize namespace of module, can access everything. (and don't need load or require it.) can utilize multiple times reload code if alter it. note there issues it, might need install nightly build work it.

finally, know that, working drracket create things much easier in general.

load scheme racket read-eval-print-loop

iphone - Posting http JSON request using NSJSONSerializer iOS -



iphone - Posting http JSON request using NSJSONSerializer iOS -

here code:

in .m

nsarray *keys = [nsarray arraywithobjects:@"training_code", @"training_duration",@"training_startdate",@"training_enddate",@"trainer_id",@"training_location",@"comments",@"keyword",@"numberofdays", nil]; nsarray *objects = [nsarray arraywithobjects:@"training_code", @"training_duration",@"training_startdate",@"training_enddate",@"trainer_id",@"training_location",@"comments",@"keyword",@"numberofdays", nil]; nsdata *jsondata; nsstring *jsonstring; nsdictionary *jsondictionary = [nsdictionary dictionarywithobjects:objects forkeys:keys]; if([nsjsonserialization isvalidjsonobject:jsondictionary]) { jsondata = [nsjsonserialization datawithjsonobject:jsondictionary options:0 error:nil]; jsonstring = [[nsstring alloc]initwithdata:jsondata encoding:nsutf8stringencoding]; } // sure escape url string. nsurl *url1 = [nsurl urlwithstring:@"http://xx.xx.xx.xxx/deployioscalender/service1.asmx"]; nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:url1]; [request sethttpmethod:@"post"]; [request sethttpbody: jsondata]; [request setvalue:@"application/json" forhttpheaderfield:@"content-type"]; [request setvalue:[nsstring stringwithformat:@"%d", [jsondata length]] forhttpheaderfield:@"content-length"]; nserror *errorreturned = nil; nsurlresponse *theresponse =[[nsurlresponse alloc]init]; nsdata *data = [nsurlconnection sendsynchronousrequest:request returningresponse:&theresponse error:&errorreturned]; if (errorreturned) { // handle error. } else { nserror *jsonparsingerror = nil; nsarray *jsonarray = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers|nsjsonreadingallowfragments error:&jsonparsingerror]; }

this returning me info as:

{ d = "[{\"training_code\":\"1234 \",\"training_duration\":\"2hrs \",\"training_startdate\":\"14/02/2013 15:00:00\",\"training_enddate\":\"14/02/2013 17:00:00\",\"trainer_id\":1,\"training_location\":\"b-wing training room-4\",\"comments\":\"c# training\",\"keyword\":\"c#1234\",\"numberofdays\":1},{\"training_code\":\"4321 \",\"training_duration\":\"16 \",\"training_startdate\":\"17/02/2013 10:30:00\",\"training_enddate\":\"17/02/2013 17:30:00\",\"trainer_id\":2,\"training_location\":\"a-wing training room-6\",\"comments\":\"objective-c\",\"keyword\":\"obj-c4321\",\"numberofdays\":2}]"; }

this not in right format. want create this:

[{"training_code":"1234 ","training_duration":"2hrs ","training_startdate":"14/02/2013 15:00:00","training_enddate":"14/02/2013 17:00:00","trainer_id":1,"training_location":"b-wing training room-4","comments":"c# training","keyword":"c#1234","numberofdays":1},{"training_code":"4321 ","training_duration":"16 ","training_startdate":"17/02/2013 10:30:00","training_enddate":"17/02/2013 17:30:00","trainer_id":2,"training_location":"a-wing training room-6","comments":"objective-c","keyword":"obj-c4321","numberofdays":2}

note: web service returning proper json format.

what additional things need accomplish this.please suggest.

you web service returning proper json, but it's not. should talk web services developer , find out why they're returning malformed json. put, getting web service cannot parsed json--unless string extraction (ugh).

consider response data, improve formatted:

{ d = " [ { \"training_code\":\"1234 \", \"training_duration\":\"2hrs \", \"training_startdate\":\"14/02/2013 15:00:00\", \"training_enddate\":\"14/02/2013 17:00:00\", \"trainer_id\":1, \"training_location\":\"b-wing training room-4\", \"comments\":\"c# training\", \"keyword\":\"c#1234\", \"numberofdays\":1 }, { \"training_code\":\"4321 \", \"training_duration\":\"16 \", \"training_startdate\":\"17/02/2013 10:30:00\", \"training_enddate\":\"17/02/2013 17:30:00\", \"trainer_id\":2, \"training_location\":\"a-wing training room-6\", \"comments\":\"objective-c\", \"keyword\":\"obj-c4321\", \"numberofdays\":2 } ] "; }

first, convert info response string:

nsstring *json = [[nsstring alloc] initwithdata:data encoding:nsutf8stringencoding];

then need strip off top:

{ d = "

and bottom

"; }

then can replace of escaped quotes using code:

json = [json stringbyreplacingoccurrencesofstring:@"\\\"" withstring:@"\""];

at point, string should parsable json this:

[ { "training_code":"1234 ", "training_duration":"2hrs ", "training_startdate":"14/02/2013 15:00:00", "training_enddate":"14/02/2013 17:00:00", "trainer_id":1, "training_location":"b-wing training room-4", "comments":"c# training", "keyword":"c#1234", "numberofdays":1 }, { "training_code":"4321 ", "training_duration":"16 ", "training_startdate":"17/02/2013 10:30:00", "training_enddate":"17/02/2013 17:30:00", "trainer_id":2, "training_location":"a-wing training room-6", "comments":"objective-c", "keyword":"obj-c4321", "numberofdays":2 } ]

so can this:

id object = [nsjsonserialization jsonobjectwithdata:[json datausingencoding:nsutf8stringencoding] options:0 error:&error];

now object should hold array containing 2 records dictionaries.

if me, though, go web services developer , demand prepare response they're sending you. shouldn't have deal of string extraction nonsense.

iphone ios objective-c json nsjsonserialization

Is there any hibernate dialect to support Mysql UTF-8 National Character Type? -



Is there any hibernate dialect to support Mysql UTF-8 National Character Type? -

i using nchar, nvarchar , national varchar.

http://dev.mysql.com/doc/refman/5.0/en/charset-national.html

i didn't find back upwards in mysqldialect, mysql5innodbdialect above info type.

public mysqldialect() { super(); registercolumntype( types.bit, "bit" ); registercolumntype( types.bigint, "bigint" ); registercolumntype( types.smallint, "smallint" ); registercolumntype( types.tinyint, "tinyint" ); registercolumntype( types.integer, "integer" ); registercolumntype( types.char, "char(1)" ); registercolumntype( types.float, "float" ); registercolumntype( types.double, "double precision" ); registercolumntype( types.date, "date" ); registercolumntype( types.time, "time" ); registercolumntype( types.timestamp, "datetime" ); registercolumntype( types.varbinary, "longblob" ); registercolumntype( types.varbinary, 16777215, "mediumblob" ); registercolumntype( types.varbinary, 65535, "blob" ); registercolumntype( types.varbinary, 255, "tinyblob" ); registercolumntype( types.longvarbinary, "longblob" ); registercolumntype( types.longvarbinary, 16777215, "mediumblob" ); registercolumntype( types.numeric, "decimal($p,$s)" ); registercolumntype( types.blob, "longblob" ); // registercolumntype( types.blob, 16777215, "mediumblob" ); // registercolumntype( types.blob, 65535, "blob" ); registercolumntype( types.clob, "longtext" ); // registercolumntype( types.clob, 16777215, "mediumtext" ); // registercolumntype( types.clob, 65535, "text" ); ........ }

is there hibernate dialect back upwards mysql utf-8 national character type?

there no such type in mysql, short-hand applying character set 'utf8'.

for illustration writing nchar(10) same writing char(10) character set 'utf8', it's not real type.

you can configure connection , tables utilize utf8 begin , doesn't create difference.

mysql hibernate utf-8 hibernate3 dialect

When building a Maven site, why does my annotation processor run twice and break the build? -



When building a Maven site, why does my annotation processor run twice and break the build? -

i have build uses annotation processor plugin generate jpa criteria classes hibernate jpa 2 metamodel generator.

this works when doing normal mvn clean package, when build site, fails:

[info] --- maven-processor-plugin:2.1.0:process (generate-jpa-metamodel) @ phtool-api --- [info] source directory: c:\jp\esv-projects\phtool\phtool-api\target\generated-sources\jpa added [info] javac option: -cp [info] javac option: ... [info] javac option: -proc:only [info] javac option: -processor [info] javac option: org.hibernate.jpamodelgen.jpametamodelentityprocessor [info] javac option: -d [info] javac option: c:\jp\esv-projects\phtool\phtool-api\target\classes [info] javac option: -s [info] javac option: c:\jp\esv-projects\phtool\phtool-api\target\generated-sources\jpa [info] diagnostic note: hibernate jpa 2 static-metamodel generator 1.2.0.final [info] diagnostic c:\jp\projects\phtool\phtool-api\target\generated-sources\jpa\phtool\impl\resource\imageimpl_.java:10: error: duplicate c lass: phtool.impl.resource.imageimpl_

i noticed plugin runs twice during site generation, don't know why. perhaps it's known javadoc plugin bug?

the problem solved now, through changes in parent pom. can't tell alter solved problem, here relevant versions within pom:

<groupid>org.bsc.maven</groupid> <artifactid>maven-processor-plugin</artifactid> <version>2.2.4</version> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-compiler-plugin</artifactid> <version>3.1</version> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-site-plugin</artifactid> <version>3.3</version> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-javadoc-plugin</artifactid> <version>2.9</version>

note version of javadoc plugin hasn't changed!

maven maven-site-plugin

php - substr doesn't work fine with utf8 -



php - substr doesn't work fine with utf8 -

i using substr method access first 20 characters of string. works fine in normal situation, while working on rtl languages (utf8) gives me wrong results (about 10 characters shown). have searched web found nth useful solve issue. line of code:

substr($article['cbody'],0,20);

thanks in advance.

if you’re working strings encoded utf-8 may lose characters when seek part of them using php substr function. happens because in utf-8 characters not restricted 1 byte, have variable length match unicode characters, between 1 , 4 bytes.

you can utilize mb_substr(), works same way substr difference can add together new parameter specify encoding type, whether utf-8 or different encoding.

try this:

$str = mb_substr($article['cbody'], 0, 20, 'utf-8'); echo utf8_decode($str);

hope helps.

php mysql utf-8 right-to-left substr

c# - Can Silverlight access USB port -



c# - Can Silverlight access USB port -

this question has reply here:

asp.net/silverlight command usb device 4 answers

i'm developing web application using mvc3 , requirement access usb port. if not possible there other way or workaround accessing port using web browser. please send me sample link.

thanks

you might find more answers if provided detail on why app required access usb port. if intranet, talking corporate , have more command on client side. if internet, it's hopeless (or should be).

c# asp.net-mvc silverlight google-chrome usb

javascript - Chrome Extension Code Sharing -



javascript - Chrome Extension Code Sharing -

i building chrome extension part of allow users write plugins , other users can download them - e.g user writes javascript function , extension downloads code whomever interested in plugin. extension 'evals' whole bunch of code malicious. little project - don't plan reach millions of users or create income , it's school project , still want provide reasonable solution problem (it doesn't have perfect).

i thinking of few possibilities create security drawback more user-friendly:

have myself or whoever runs project go on each submitted plugin , create sure not contain malicious code(drawback approach clear, don't want go on plugins rest of life). give users ability comment on , rate plugins or inform website admin , in malicious code not downloaded much. try write automated script detects malicious code(not feasibly right?) detect vulnerable parts in extension , invest time in protecting them (for illustration cookies , localstorage). make user understand he's downloading plugin @ own risk.

i hear thoughts developers , users , how approach problem keeping in mind have minimal resources project?

javascript plugins google-chrome-extension

redirect - JSF commandbutton ajax: how to capture the success/fail event -



redirect - JSF commandbutton ajax: how to capture the success/fail event -

my current code.

<h:form> <h:panelgroup id="messagepanel" layout="block"> <h:messages errorstyle="color: red" infostyle="color: green" layout="table"/> </h:panelgroup> <h:panelgrid columns="2"> // form input stuff here.. </h:panelgrid> <h:commandbutton class="register-btn" action="#{accountcontroller.create}" value="#{bundle.register}"> <f:ajax event="action" execute="@form" render="messagepanel"/> </h:commandbutton> </h:form>

messagepanel validation errors displays.

i want know how capture success event.

[done] if user input wrong values, ajax validation , displays wrong values

[problem] if success should redirect page.

**updated

create method

public string create() { seek { getfacadeuser().create(currentuser); jsfutil.addsuccessmessage(resourcebundle.getbundle("/bundle").getstring("accountcreated")); homecoming preparecreate(); } grab (exception e) { jsfutil.adderrormessage(e, resourcebundle.getbundle("/bundle").getstring("persistenceerroroccured")); homecoming null; } } public string preparecreate() { current = new account(); selecteditemindex = -1; homecoming "index"; }

i'm using jsf 2.1

this not right way redirection ajax request. should utilize externalcontext.redirect() instead:

facescontext.getcurrentinstance().getexternalcontext().redirect("yoururl");

in way receive partial response server to, redirection:

<partial-response> <redirect url="yoururl"> </redirect> </partial-response>

string returned in method irrelevant, can homecoming null.

ajax redirect jsf-2

ios - DrawRect gets called but screen remains in old state -



ios - DrawRect gets called but screen remains in old state -

i have created uiview subclass, added existing view gesture recognizers (pinch, tap, pan, etc).

once phone call setneedsdisplay, drawrect function gets called, far good. amazing part screen not updated newly created content.

i used nslog messages track sourcode functioning properly, function implemented.

can give me hint. due gesture recognizers? if yes, how overcome this?

ios uiview uigesturerecognizer

android - How can I create a trigger between normal table and fts3 table? -



android - How can I create a trigger between normal table and fts3 table? -

i have been having issues switching between fts3 tables , normal database tables. application simple , allows user add together contacts database , can search contacts match search query (why used fts table) , result displayed on list onitemclicklistener. when click item, error. have traced error database (if utilize normal database works, if utilize fts doesn't). have decided utilize both types of databases , wondering if show me how trigger created sync databases.

my first database contact (database name) , table called contacts. sec database table contacts_fts. searching col_name, need in contacts_fts table? wondering if check see if trigger valid?

public static final string database_name = "contact"; public static final string database_table = "contacts"; private static final string database_table_fts = "contacts_fts"; private static final int database_version = 20; private context ourcontext; private dbhelper dbhelper; private static sqlitedatabase db; private static final string database_create = "create table " + database_table + " (" + col_id + " integer primary key autoincrement, " + col_name + " text not null, " + col_email + " text not null, " + col_cell + " text not null, " + col_arrival + " text not null, " + col_departure + " text not null, " + col_flight_number + " text not null, " + col_hotel_room_number + " text not null, " + col_event1 + " text not null, " + col_event2 + " text not null, " + col_event1_room + " text not null, " + col_event2_room + " text not null);"; private static final string database_create_fts = "create virtual table " + database_table_fts + " using fts3(" + "content=" + "\"contacts\", " + col_name + ");"; private static final string trigger = "create trigger contacts_trigger " + "after insert "+ "on " + database_table + " begin " + "insert " + database_table_fts + " set " + col_name + " = new.col_name " + col_id + " = old.col_id;" + " end;";

i think alternative "external content" table available fts4 , not fts3.

external content fts4 tables

try using fts4 table instead of fts3.

android database triggers fts3