Sunday, 15 February 2015

Not able to group similar records in XSLT -



Not able to group similar records in XSLT -

i trying grouping similar records based on language. not able grouping in xslt. using xsl key function grouping record in xslt. trying loop , add together each grouping records 1 group.

i have next input xml.

<root> <element name="david" language="german"></element> <element name="sarah" language="german"></element> <element name="isaac" language="english"></element> <element name="abraham" language="german"></element> <element name="jackson" language="english"></element> <element name="deweher" language="english"></element> <element name="jonathan" language="hindi"></element> <element name="mike" language="hindi"></element> </root>

xslt:

<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/xsl/transform" xmlns:xs="http://www.w3.org/2001/xmlschema" exclude-result-prefixes="xs" version="1.0"> <xsl:key name="lang" match="element" use="@language"></xsl:key> <xsl:template match="/"> <root> <xsl:for-each select="key('lang',//element/@language)"> <group> <xsl:attribute name="name" select=".//@language"></xsl:attribute> <member><xsl:value-of select=".//@name"/></member> </group> </xsl:for-each> </root> </xsl:template> </xsl:stylesheet>

expected output :

<root> <group name="german"> <member>david</member> <member>sarah</member> <member>abraham</member> </group> <group name="english"> <member>isaac</member> <member>jackson</member> <member>deweher</member> </group> <group name="hindi"> <member>jonathan</member> <member>mike</member> </group> </root>

actual output :

<root> <group name="german"> <member>david</member> </group> <group name="german"> <member>sarah</member> </group> <group name="english"> <member>isaac</member> </group> <group name="german"> <member>abraham</member> </group> <group name="english"> <member>jackson</member> </group> <group name="english"> <member>deweher</member> </group> <group name="hindi"> <member>jonathan</member> </group> <group name="hindi"> <member>mike</member> </group> </root>

i getting each records separately. can please allow me know went wrong in xsl. :)

i made changes in stylesheet. should accomplish result expect:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/xsl/transform" version="1.0"> <xsl:output indent="yes"/> <xsl:key name="lang" match="element" use="@language"></xsl:key> <xsl:template match="root"> <xsl:copy> <xsl:for-each select="element[count(. | key('lang', @language)[1]) = 1]"> <group name="{@language}"> <xsl:for-each select="key('lang', @language)"> <member><xsl:value-of select="@name"/></member> </xsl:for-each> </group> </xsl:for-each> </xsl:copy> </xsl:template> </xsl:stylesheet>

the first loop selects each unique language (a node-set of size 3), , creates context inner loop. inner loop iterates through each element , selects ones have same language.

muenchian grouping may seem hard grasp, can apply template shown in this tutorial , not have think much. applied template example.

update: here solution without using for-each loops:

<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/xsl/transform" version="1.0"> <xsl:output indent="yes"/> <xsl:key name="lang" match="element" use="@language"></xsl:key> <xsl:template match="root"> <xsl:copy> <xsl:apply-templates select="element[generate-id(.) = generate-id(key('lang', @language)[1])]"/> </xsl:copy> </xsl:template> <xsl:template match="element"> <group name="{@language}"> <xsl:apply-templates select="key('lang', @language)" mode="member"/> </group> </xsl:template> <xsl:template match="element" mode="member"> <member><xsl:value-of select="@name"/></member> </xsl:template> </xsl:stylesheet>

xslt xslt-1.0 xslt-grouping

How to delete xml element using qt -



How to delete xml element using qt -

i have xml file this

<plan> <car id="1">491,142;492,138;</car> <car id="10073">498,141;489,145;</car> <car id="1">483,143;477,145;</car> <car id="10075">487,142;490,137;</car> <car id="10076">483,137;488,136;</car> <car id="10077">484,146;480,144;</car> <car id="1">480,147;498,142;</car> <car id="10079">488,143;487,147;</car> <car id="1">498,141;487,142;</car> <car id="10081">487,143;481,144;</car> <car id="1">495,137;485,137;</car> <car id="10083">486,142;484,140;</car> <car id="10084">478,147;479,142;</car> <car id="1">493,139;489,139;</car> <car id="10087">498,140;490,136;</car> <car id="10088">479,145;484,142;</car> </plan>

how can delete auto element of id "1" using qt library?

it's pretty straightforward:

qdomdocument doc; qfile file("/tmp/1.xml"); file.open(qfile::readonly); doc.setcontent(&file); qdomelement plan = doc.documentelement(); qdomnodelist cars = plan.childnodes(); for(int = 0; < cars.count(); i++) { qdomnode node = cars.at(i); if (node.iselement() && node.toelement().attribute("id") == "1") { plan.removechild(node); } } qdebug() << doc.tostring();

qt

sql - Automated Heroku PostgreSQL Updates without Client Request -



sql - Automated Heroku PostgreSQL Updates without Client Request -

i new web development. building simple text based web game. using heroku , postgresql. have sql table users , coin amount(their earnings).

i can receive/transmit info database using requests made players. want accomplish automate coin add-on each users account.

so let's @ origin of each hour, want add together 15 coins each user. how can possible accomplish kind of automation heroku , postgresql ?

i tried searching hour, wasn't able find name of process :(

while schedule (as sonnyhe notes), it's improve not to.

instead, update value when you're updating balance other reason, adding difference between time lastly added coins , current time, extracting hours, , multiplying 15.

if user asks view balance, need display lastly stored value plus hours since * 15.

that way you're not doing lots of unnecessary updates , causing unnecessary load.

sql ruby-on-rails postgresql heroku

javascript - My code works in xampp but not on the 000webhost.com -



javascript - My code works in xampp but not on the 000webhost.com -

when test on localhost works fine when utilize on website "000webhost.com" console writes "bad!" (as in code). have no thought why working on localhost , why not on 000webhost.com

there ajax:

var xmlhttp = (window.xmlhttprequest)?new xmlhttprequest():new activexobject("microsoft.xmlhttp"); xmlhttp.onreadystatechange=function(){ if(xmlhttp.readystate==4 && xmlhttp.status==200){ var resptext = xmlhttp.responsetext; try{ var json = json.parse(resptext); console.log("good!"); } catch(e){ console.log("bad!"); } } } xmlhttp.open(method,url + "?" + parameters,true); xmlhttp.send();

there php:

//$content html code ex: <span>i'm here</span> $resp = array( 'r' => true, 'response' => $content, ); echo json_encode($resp);

when delete try makes error unexpected token <

sorry english language , give thanks helping.

have checked json? sounds of error, sounds json invalid.

javascript php json

sonarqube - PHP 2.1 plugin with Sonar 3.7.4 -



sonarqube - PHP 2.1 plugin with Sonar 3.7.4 -

i using sonarqube 3.7.4 version , php plugin 2.1 . when analyse php project . won't analyse php mess detector, , php codesniffer, result shows rules compliance 100% , issue 0 always. worked in sonar 3.5.1 version. whati missing. can help me

thanks

saravanan.n

i'm pretty sure using version 1.x of php plugin , after migration version 2.x php quality profiles empty. misleading behavior due fact in version 2.x past rules based on code sniffer phpmd, ... have been rewritten based on sonarqube php parser. it's update manually php quality profiles activate new rules.

php sonarqube phpmd

Git-Repository inside Git-Repository (no submodule) -



Git-Repository inside Git-Repository (no submodule) -

i want utilize gitrepository within gitrepository. know there submodules read aren't great. right created git repository, added .gitignore , accepted files via whitelist. created directory within , created git init new git repository within root repository. right works without problems...

i seek visualize situation:

root-repository - .git - script.bat - readme.md - .gitignore (which ignores * , whitelists !script.bat !readme.md !.gitignore) - directory - - .git - - .gitignore - - other files...

what want achieve? root-repository should first repository every developer pulls. runs script (which git clones projects, adds environment variables, build dependencies , on..).

is okay or there downsides?

i haven't worked git submodules yet, can't compare 2 solutions. have done similar thing, similar reasons, difference root project not git repository. situation this:

root_directory - git_repo_1 - git_repo_2 - ... (more repos) - project_build_repository.

the project build repository contains scripts cloning entire project , building (the entire project built various subprojects, each of can built or used independantly).

there few downsides doing this, , there additional downside approach have taken not nowadays in variant have done.

the general downside whenever have apply operation all/multiple repositories, have manage manually, or manage script. leads variety of derivative problems -- forget something, have maintain scripts, deviate idiomatic way of doing things git -- depending on how work around root problem.

the disadvantage approach has on mine 1 of ambiguity. naive user might git command (status, force etc) , expect submodules be handled correctly not be. compound issues discussed in previous paragraph.

i don't recommend approach (i evaluating utilize of git submodule , comparing tradeoffs in near future), in approach user following:

create project dir. in project dir, clone project_build_repo. run initial clone script, checks out submodules in right paths.

in case readme etc info goes in project_build_repo.

good luck.

git

javascript - Refresh takes the webpage to homepage instead of showing present search result again -



javascript - Refresh takes the webpage to homepage instead of showing present search result again -

i making webpage fetches query results database. problem whenever reload page in chorme, redirects page home page instead of loading same page 1 time again albeit redirecting correctly in firefox , safari.

for example: if search url : http://bug.xyz.com/#/?bug_package=demo&ndays=0 when reload/refresh page in chrome takes me http://bug.xyz.com/ want reload nowadays url only.

language used: javascript

p.s. link illustration purpose , not work website on intranet only.

my thought is, /#/ bit for. may what's causing problem.

otherwise you'll need post code.

javascript google-chrome firefox website

mysql - get json object from apache solr using java for autocomplete -



mysql - get json object from apache solr using java for autocomplete -

i did apache solr indexing (mysql) data, searching select , suggest, how json object dynamically apache solr while keyup characters, here given apache solr url , corresponding results

url localhost:8983/solr/collection1/select?q=hotelname%3a%22royal+orchid%22&wt=json&indent=true output { "responseheader": { "status": 0, "qtime": 0, "params": { "indent": "true", "q": "hotelname:\"royal orchid\"", "_": "1403088370128", "wt": "json" } }, "response": { "numfound": 20, "start": 0, "docs": [ { "hotelname": [ "royal orchid metropole mysore" ], "cityname": "mysore", "id": "224433", "_version_": 1471227815192952800 }, { "hotelname": [ "royal orchid central bangalore" ], "cityname": "bengaluru (and vicinity)", "id": "240388", "_version_": 1471227815235944400 }, { "hotelname": [ "royal orchid central jaipur" ], "cityname": "jaipur", "id": "258200", "_version_": 1471227815290470400 }, { "hotelname": [ "royal orchid brindavan gardens" ], "cityname": "mysore", "id": "258917", "_version_": 1471227815293616000 }, { "hotelname": [ "royal orchid central pune" ], "cityname": "pune", "id": "267814", "_version_": 1471227815330316300 }, { "hotelname": [ "royal orchid suites" ], "cityname": "bengaluru (and vicinity)", "id": "309427", "_version_": 1471227815379599400 }, { "hotelname": [ "royal orchid central ahmedabad" ], "cityname": "ahmedabad", "id": "326301", "_version_": 1471227815444611000 }, { "hotelname": [ "royal orchid fort resort" ], "cityname": "mussoorie", "id": "327797", "_version_": 1471227815467679700 }, { "hotelname": [ "royal orchid resort pattaya" ], "cityname": "pattaya", "id": "344270", "_version_": 1471227815546323000 }, { "hotelname": [ "royal orchid central grazia" ], "cityname": "navi mumbai", "id": "350799", "_version_": 1471227815558905900 } ] } }

is possible phone call apache solr url jquery autocomplete or shall write restful client json data, pls help me out.

yes, if javascript running in localhost:8983. if not, phone call violate cross-domain policy of browser.

if not, need create simple backend bouncer on same domain website. so, if solr running @ localhost:8983 , website running @ localhost:80, need backend helper javascript.

the js in question quite simple, can utilize $.get or $.getjson. recommend getjson this, see documentation , examples @ http://api.jquery.com/jquery.getjson/.

i have no clue how backend built, c# mvc ajax controller action bouncing this. note wrote without testing, not work straight can utilize guideline.

public jsonresult search(string searchterm) { // if searchterm value "q". might have encode it. var url = "localhost:8983/solr/collection1/select?q=" + searchterm + "&wt=json&indent=true"; doxlog.info("contacting sovelia api url: " + url); var request = (httpwebrequest)webrequest.create(url); request.useragent = "dox"; // fire request using (var response = request.getresponse()) { var datastream = response.getresponsestream(); using (var reader = new streamreader(datastream)) { var responseasstring = reader.readtoend(); homecoming json(responseasstring, jsonrequestbehavior.allowget); } } }

java mysql json apache solr

php - issue with mysqli query when I use the function to run the query -



php - issue with mysqli query when I use the function to run the query -

why error when run query using mysqli within function? works fine outside of function. when running function, error states "$db" variable undefined.

<?php $username = 'username'; $password = 'password'; $db = new mysqli('localhost', 'root', 'root', 'rocketforce_blog'); $result = $db->query("select * users user_name = '$username' , password = '$password'"); $row = $result->num_rows; $cnt = count($row); echo $cnt; //======================================================================================= function user_exists($username, $password) { $result = $db->query("select * users user_name = '$username' , password = '$password'"); $row = $result->num_rows; $cnt = count($row); homecoming $cnt; } echo user_exists($username, $password); ?>

the variable $db not known in scope of function. if want known in function, either have pass $db parameter function. eg

function user_exists($db, $username, $password) { $result = $db->query("select * users user_name = '$username' , password = '$password'"); $row = $result->num_rows; $cnt = count($row); homecoming $cnt; } echo user_exists($db, $username, $password);

or import global $db variable scope of function. that:

function user_exists($username, $password) { global $db; $result = $db->query("select * users user_name = '$username' , password = '$password'"); $row = $result->num_rows; $cnt = count($row); homecoming $cnt; } echo user_exists($username, $password);

the first 1 improve one, utilize type hints, pass different connections , on...

php mysqli

c# - List with Associated Detail Box GUI -



c# - List with Associated Detail Box GUI -

i'm working in c# / wpf , i'm trying develop window has next layout:

the thought click each item in datagrid , see associated details of item in command below datagrid. i'm not sure kind of command house expanded details. question around options how accomplish kind of ui, i'm novice @ wpf.

a neat , easy solution have 2 separate views. 1 embedded in other. grid listed items main view. details panel sec view embedded in first one.

to communicate item selected , details should displayed using binding. on panel displaying details using datacontext , bind item selected on grid. and, on grid, communicate item has been selected using selectedvalue.

below sample should give thought what's relation between views.

<window ... xmlns:view="clr-namespace:sampleproject.view" ... /> <grid> <grid.rowdefinitions> <rowdefinition height="*"/> <rowdefinition height="*"/> </grid.rowdefinitions> ... <!-- let's assume sec view defined in view folder --> <view:detailsview datacontext="{binding selecteditem, updatesourcetrigger=propertychanged, mode=twoway}"/> <datagrid itemssource="{binding items, updatesourcetrigger=propertychanged, notifyonsourceupdated=true}" selectedvalue="{binding selecteditem, updatesourcetrigger=propertychanged}" > ...

the items collection of products want display in datagrid. should implemented in viewmodel of main view. selecteditem property on viewmodel.

note sample give thought what's construction of solution might it's far finish solution. still, hope help understand how go on project.

main point communication between panels done utilize of binding datacontext (on detailsview) , selectedvalue (on grid).

c# wpf datagrid

java - How to add css-keyframes to vaadin components? -



java - How to add css-keyframes to vaadin components? -

i'd add together keyframe-animation vaadin label component: background should create colored transition red yellow.

but bg color not alter in way. missing anything?

private label label = new label("background reddish fading"); lable.setcss("red");

css:

.v-label-red { @include red; }

keyframe:

@-webkit-keyframes reddish { {background: red;} {background: yellow;} } @keyframes reddish { {background: red;} {background: yellow;} }

be sure have @keyframes out of main @mixin of theme. next .v-label-red needs background set (most same to in keyframes , needs time handle (now goes white -> reddish -> yellowish -> white in no time. here example, should bring on right track:

css

@import "../reindeer/reindeer.scss"; @keyframes keyframe1 { {background: red;} {background: yellow;} } @keyframes keyframe2 { {background: yellow;} {background: red;} } @mixin app { @include reindeer; .keyframe1 { background: yellow; -webkit-animation: keyframe1 1s linear; -moz-animation: keyframe1 1s linear; -ms-animation: keyframe1 1s linear; animation: keyframe1 1s linear; } .keyframe2 { background: red; -webkit-animation: keyframe2 1s linear; -moz-animation: keyframe2 1s linear; -ms-animation: keyframe2 1s linear; animation: keyframe2 1s linear; } }

vaadin ui code (groovy)

@vaadinui @theme('app') @compilestatic class appui extends ui { final static string k1 = 'keyframe1' final static string k2 = 'keyframe2' @override protected void init(vaadinrequest vaadinrequest) { final layout = new verticallayout() layout.setspacing(true) layout.setmargin(true) final headline = new label('hello world') headline.addstylename(k1) final button = new button("toggle", { if (headline.stylename.contains(k1)) { headline.addstylename(k2) headline.removestylename(k1) } else { headline.addstylename(k1) headline.removestylename(k2) } } button.clicklistener) layout.addcomponents(headline, button) setcontent(layout) } }

this code fade label on loading , fade between 2 states on button clicks.

java css vaadin css-animations

xamarin - Android Setting New default home in code -



xamarin - Android Setting New default home in code -

i have app want set default home screen, i'm running unusual problem.

i have setting allows user select default home screen.

i utilize next code allow them select default activity:

intent selector = new intent(intent.actionmain); selector.addcategory(intent.categoryhome); selector.addcategory(intent.categorydefault); selector.setcomponent(new componentname("android", "com.android.internal.app.resolveractivity")); startactivity(selector);

with no default set, run code , select app default , tell utilize that.

now, run code again, , tell utilize different activity (not mine) , utilize it.

the problem is, never switches different if default set.

i've seen other applications allow this, i'm missing something, don't know what.

i'm testing on samsung galaxy s4 api level set 14.

ok, found reply question.

the reply here: http://www.trustydroid.com/2014/05/19/force-show-default-app-chooser-dialog/

the 1 thing should maintain in mind component name must correct. apparently under api14, ignores component (and acts works) if class name not correct. goes through motions of enabling component, launching chooser, disabling component. however, never saves new default.

after tried compiling under api19, os threw exception lead me prepare issue having working (which wrong class name).

once had straightened out, did wanted.

for completeness sake, here code:

create fakeactivity this:

[activity(label = "fakelauncher", enabled = false)] [intentfilter(new[] { intent.actionmain }, categories = new[] { intent.categoryhome, intent.categorydefault })] public class fakelauncher : activity { protected override void oncreate(bundle bundle) { base.oncreate(bundle); // create application here } }

then ever want alter default home run code:

componentname componentname = new componentname(application.packagename, "<fake activity class name>"); packagemanager.setcomponentenabledsetting(componentname, android.content.pm.componentenabledstate.enabled, android.content.pm.componentenableoption.dontkillapp); intent tempintent = new intent(intent.actionmain); tempintent.addcategory(intent.categoryhome); startactivity(tempintent); packagemanager.setcomponentenabledsetting(componentname, android.content.pm.componentenabledstate.disabled, android.content.pm.componentenableoption.dontkillapp);

android xamarin

php - Mongo Update Speed -



php - Mongo Update Speed -

i have script when run on local scheme runs when running on production scheme runs much slower. have confirmed php profiler slow-down happening in update method on mongocollection object. have copied php software (binary , modules) production scheme local scheme create sure isn't due difference in machine/network. running production php software on local scheme runs slow. problem not machine or network. since same script not script. points 1 of 3 possibilities:

difference in php version difference in mongo driver version difference in configuration

the script in question iterates through records in collection , makes update each one. update has write concern set 0 speed more of import knowing executed successfully. php profiler stopped providing info 1 time called update (since update implemented in c). turned next strace see if scheme calls help explain difference in speed. loop updates beingness issued has next strace output on fast system:

sendto(3, "\202\0\0\0\206\0\0\0\0\0\0\0\321\7\0\0\0\0\0\0properties_2"..., 130, msg_dontwait, null, 0) = 130 write(1, ".", 1) = 1 sendto(3, "\202\0\0\0\207\0\0\0\0\0\0\0\321\7\0\0\0\0\0\0properties_2"..., 130, msg_dontwait, null, 0) = 130 write(1, ".", 1) = 1 sendto(3, "\202\0\0\0\210\0\0\0\0\0\0\0\321\7\0\0\0\0\0\0properties_2"..., 130, msg_dontwait, null, 0) = 130 write(1, ".", 1) = 1

i outputting "." between each update have feedback indicate how fast updates going. when running same script on slower php see following:

sendto(3, "\357\0\0\0v\0\0\0\0\0\0\0\324\7\0\0\0\0\0\0properties_2"..., 239, msg_dontwait, null, 0) = 239 poll([{fd=3, events=pollin|pollerr|pollhup}], 1, 30000) = 1 ([{fd=3, revents=pollin}]) recvfrom(3, "1\0\0\0009\0.\nv\0\0\0\1\0\0\0\10\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 8192, msg_dontwait, null, null) = 49 write(1, ".", 1) = 1 sendto(3, "\357\0\0\0w\0\0\0\0\0\0\0\324\7\0\0\0\0\0\0properties_2"..., 239, msg_dontwait, null, 0) = 239 poll([{fd=3, events=pollin|pollerr|pollhup}], 1, 30000) = 1 ([{fd=3, revents=pollin}]) recvfrom(3, "1\0\0\0\201\0.\nw\0\0\0\1\0\0\0\10\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 8192, msg_dontwait, null, null) = 49 write(1, ".", 1) = 1 sendto(3, "\357\0\0\0x\0\0\0\0\0\0\0\324\7\0\0\0\0\0\0properties_2"..., 239, msg_dontwait, null, 0) = 239 poll([{fd=3, events=pollin|pollerr|pollhup}], 1, 30000) = 1 ([{fd=3, revents=pollin}]) recvfrom(3, "1\0\0\0\320\0.\nx\0\0\0\1\0\0\0\10\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 8192, msg_dontwait, null, null) = 49 write(1, ".", 1) = 1 sendto(3, "\357\0\0\0y\0\0\0\0\0\0\0\324\7\0\0\0\0\0\0properties_2"..., 239, msg_dontwait, null, 0) = 239 poll([{fd=3, events=pollin|pollerr|pollhup}], 1, 30000) = 1 ([{fd=3, revents=pollin}]) recvfrom(3, "1\0\0\0\365\0.\ny\0\0\0\1\0\0\0\10\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 8192, msg_dontwait, null, null) = 49 write(1, ".", 1) = 1

notice have added scheme calls. looks checking reply me indicates it's not using write concern 0. major difference between 2 php installations fast 1 using driver 1.4.5 while slow 1 using 1.5.3.

i compared update code both versions. in 1.4.5 it seems send message , return. on other hand looking @ 1.5.3 it sends message gets reply. don't see skipping checking reply if write status 0. if follow code extracts reply can see calls these 2 additional scheme calls.

can understand improve help me figure out how code running fast in production. on fast php install (mongo driver 1.4.5) script executes in 2-3 minutes. on slow scheme (mongo driver 1.5.3) killed after 30 minutes because tired of waiting. knows how long have taken done.

(note: updated original reply after research)

the new write operation commands came in 2.6 , hence in utilize between supported driver (php 1.5+) , mongodb server (2.6+) mean new semantics of w=0 writes in play. means server waits operation finish before sending response (that is, difference between w=0 , w=1 w=0 omits error details). driver still waits response before returning phone call (i.e. no longer fire , forget).

you can see in mongodb shell also, , official way around utilize new bulk api. although know 1.5 driver fall legacy write operations when connecting 2.4 , below server, there no way forcefulness behavior in php driver.

php performance mongodb

vba - Data Type Mismatch in criteria expression Access 2010 with SQL Insert Statement -



vba - Data Type Mismatch in criteria expression Access 2010 with SQL Insert Statement -

i trying update linked table in access , getting error of info mismatch type in criteria expression. database fields float ones start hours.

i tried making hours field integer value, got different type mismatch message.

i new vb , access, dumb. appreciate help. here code.

private sub command30_click() dim monthformat string dim yearformat string dim fullyear string dim dateperformed string dim currdate string dim timeentered string dim empnum string dim acct string dim cat string dim cmnt string dim firstname string dim lastname string dim shift string dim addvacation string dim hours string if isnumeric(me.text12.value) hours = cint(me.text12.value) else: hours = me.text12.value monthformat = format(me.text10.value, "mm") yearformat = format(me.text10.value, "yy") fullyear = format(me.text10.value, "yyyy") dateperformed = format(me.text10.value, "yyyymmdd") currdate = format(datetime.date, "yyyymmdd") timeentered = format(datetime.time, "hhmmss") empnum = " & me.combo20.column(0) & " acct = " & me.combo20.column(1) & " cat = " & me.combo20.column(3) & " cmnt = " & me.combo20.column(4) & " firstname = " & me.combo20.column(5) & " lastname = " & me.combo20.column(6) & " shift = " & me.combo20.column(7) & " hours = " & me.text12.value & " addvacation = "insert dbo_r_pphrtrx" & _ "(date_performed, employee_number " & _ ", job_number " & _ ", release " & _ ", account, account_cr, batch_item, batch_number, burden_dollars, category, date_time_begun, date_time_complt, eff_var_dollars, employee_id, eo_flag, first_name " & _ ", hours_earned, hours_worked, hours_worked_set, labor_dollars, last_name, location_code, period_yyyymm, product_line, qty_complete, rate_var_dollars " & _ ", release_wo " & _ ", shift, [status], [time], work_center, date_entered, divisionid, comment " & _ ", late_charge, operation, overtime, project_task, reference, task_number, type_transaction, datacapserialnumber, cost_account, cs_period, work_order) " & _ " " & _ " values('" & dateperformed & "' , '" & empnum & "' " & _ ", switch(('" & monthformat & "' >= 1 , '" & monthformat & "' <= 3), ('01vh' + '" & yearformat & "'), ('" & monthformat & "' >= 4 , '" & monthformat & "' <= 6), ('02vh' + '" & yearformat & "'), ('" & monthformat & "' >= 7 , '" & monthformat & "' <= 9), ('03vh' + '" & yearformat & "'), ('" & monthformat & "' >= 10 , '" & monthformat & "' <= 12), ('04vh' + '" & yearformat & "'))" & _ ", switch(('" & monthformat & "' >= 1 , '" & monthformat & "' <= 3), ('01vh' + '" & yearformat & "'), ('" & monthformat & "' >= 4 , '" & monthformat & "' <= 6), ('02vh' + '" & yearformat & "'), ('" & monthformat & "' >= 7 , '" & monthformat & "' <= 9), ('03vh' + '" & yearformat & "'), ('" & monthformat & "' >= 10 , '" & monthformat & "' <= 12), ('04vh' + '" & yearformat & "'))" & _ ", '" & acct & "', '2500-x', '0', '0', '0', 'labor hrs', '" & dateperformed & "' + '0600', '" & dateperformed & "' + '0600', '0', 'accss', '', '" & firstname & "' " & _ ", '" & hours & "', '" & hours & "', '0', '0', '" & lastname & "', '01', '" & fullyear & "' + '" & monthformat & "', '01', '0', '0' " & _ ", switch(('" & monthformat & "' >= 1 , '" & monthformat & "' <= 3), ('01vh' + '" & yearformat & "'), ('" & monthformat & "' >= 4 , '" & monthformat & "' <= 6), ('02vh' + '" & yearformat & "'), ('" & monthformat & "' >= 7 , '" & monthformat & "' <= 9), ('03vh' + '" & yearformat & "'), ('" & monthformat & "' >= 10 , '" & monthformat & "' <= 12), ('04vh' + '" & yearformat & "'))" & _ ", '" & shift & "', '', '" & timeentered & "', '92', '" & currdate & "', 'jobscope', 'v' " & _ ", '', '', '', '', '', '', '', '', '', '', '')" docmd.runsql (addvacation) end sub

instead of "gluing together" long, ugly, , potentially troublesome insert statement might consider using recordset object insert new row:

class="lang-vbs prettyprint-override">dim cdb dao.database, rst dao.recordset set cdb = currentdb set rst = cdb.openrecordset("select * dbo_r_pphrtrx false", dbopendynaset) rst.addnew rst!date_performed = dateperformed rst!employee_number = empnum ' ... , on rest of fields rst.update rst.close set rst = nil set cdb = nil

sql vba ms-access access-vba

javascript - ReceiveMessage event showing data as undefined -



javascript - ReceiveMessage event showing data as undefined -

i have iframe in there javascript function:

function callparent(){ parent.postmessage('closemodal','*'); homecoming true; }

and other javascript function in main page:

$(window).on('message',function(e){ console.log(e); });

it's printing e in e.data it's giving undefined. expecting info string 'closemodal'.

how message string iframe?

the info you're passing in

e.originalevent.data

so on main page:

$(window).on('message',function(e){ console.log(e.originalevent.data); });

as pointy commented jquery creates own event object.

if not using jquery have had

window.onmessage = function(e){ console.log(e.data); };

javascript jquery iframe

jquery - How to get properties of Kendo element in javascript -



jquery - How to get properties of Kendo element in javascript -

i've got several kendo numerictextboxes on razor view page , event handlers them:

@html.kendo().numerictextboxfor(model => model.signednumerictextbox1).step(0.25f).events(e => e.change("changesignednumerictextbox1")) @html.kendo().numerictextboxfor(model => model.signednumerictextbox2).step(0.25f).events(e => e.change("changesignednumerictextbox2")) @html.kendo().numerictextboxfor(model => model.signednumerictextbox3).step(0.25f).events(e => e.change("changesignednumerictextbox3")) <script> function changesignednumerictextbox1() { var val = this.value() alert(this.name); if (val > 0) { $("#signednumerictextbox1").kendonumerictextbox({ format: "+##.##", decimals: 2 }); } else { $("#signednumerictextbox1").kendonumerictextbox({ format: "##.##", decimals: 2 }); } } function changesignednumerictextbox2() { var val = this.value() alert(this.name); if (val > 0) { $("#signednumerictextbox2").kendonumerictextbox({ format: "+##.##", decimals: 2 }); } else { $("#signednumerictextbox2").kendonumerictextbox({ format: "##.##", decimals: 2 }); } } function changesignednumerictextbox3() { var val = this.value() alert(this.name); if (val > 0) { $("#signednumerictextbox3").kendonumerictextbox({ format: "+##.##", decimals: 2 }); } else { $("#signednumerictextbox3").kendonumerictextbox({ format: "##.##", decimals: 2 }); } } </script>

is there way reference numeric text box in javascript need have 1 changesignednumerictextbox function?

this should help:

<script> function changeme() { var myid = '#' + this._form.context.id; var val = $(myid).val(); if (val > 0) { $(myid).kendonumerictextbox({ format: "+##.##", decimals: 2 }); } else { $(myid).kendonumerictextbox({ format: "##.##", decimals: 2 }); } } </script>

javascript jquery razor kendo-ui

javascript - Google maps map not loading -



javascript - Google maps map not loading -

i've read ton of solutions problem, non of them worked me. map not loading

here html

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script> <script> var map; function initialize() { var mapoptions = { zoom: 8, center: new google.maps.latlng(41.7429109,24.391538699999955) }; map = new google.maps.map(document.getelementbyid('map-canvas'), mapoptions); } google.maps.event.adddomlistener(window, 'load', initialize); </script> </head> <body onload="initialize()"> <div id="map_canvas"></div> </body>

the css think problem somewhere here

body { height:100%; width:100%; margin: 0; padding: 0; line-height: 1.5em; font-family: georgia, "times new roman", times, serif; font-size: 12px; color: #666; background:#302f2f ; } #map_canvas { width:300px; height:300px; }

so please help me

your html element has id 'map_canvas', javascript has 'map-canvas'.

it cannot find element cos you're spelling id wrong! :o)

javascript html google-maps maps

regex - IIS URLRewrite Regular Expression -



regex - IIS URLRewrite Regular Expression -

i horrible regular expressions , new url rewrite module in iis please bear me...

i have scenario have 1-2 pages need redirected specific location , protocol (https).

desired url

https://www.domain.com/specific/location/mypage.aspx

i need create sure users hitting specific url when trying access page. of below should redirect user "desired" url:

http://www.domain.com/specific/location/mypage.aspx http://domain.com/specific/location/mypage.aspx https://domain.com/specific/location/mypage.aspx http://www.anotherdomain.com/specific/location/mypage.aspx http://anotherdomain.com.com/specific/location/mypage.aspx https://anotherdomain.com.com/specific/location/mypage.aspx

i need happen page , 1 other page , need create sure these pages beingness redirected ssl, rest of site should redirected http version if user types in https. how can accomplish this, need more 1 rule, etc?

any help appreciated.

thankfully, isn't complicated looks. when creating rules using iis url rewrite module, "url" in match tag looking @ after host name. doesn't see domain.com.

so, in web.config, within system.webserver section, in rewrite section:

<rule name="redirect specific location" enabled="true" stopprocessing="true"> <match url="specific\/location\/mypage\.aspx"/> <action type="redirect" url="https://www.domain.com/specific/location/mypage.aspx"/> </rule>

that way url coming in ends specific/location/mypage.aspx redirected, no matter hostname is.

regex iis redirect url-rewriting

c# - CRUD operations in MVC 3 without using db context -



c# - CRUD operations in MVC 3 without using db context -

i need help .actually using ado net 4.0 .net framework , create own database using app_data in solution explorer .mdf extension.

using system; using system.collections.generic; using system.linq; using system.web; using system.web.mvc; using crudoperations.models; using system.data.entity; namespace crudoperations.controllers { public class employeecontroller : controller { // // get: /employee/ employentities employcontext; public actionresult index() { using (var details= new employentities()) { homecoming view(details.employs.tolist()); } } // // get: /employee/details/5 public actionresult details(int id) { employcontext = new employentities(); employ _tempemploy = new employ(); _tempemploy.id = id; homecoming view(_tempemploy); } // // get: /employee/create public actionresult create() { homecoming view(); } // // post: /employee/create [httppost] public actionresult create(employ objemploy) { seek { employcontext = new employentities(); employcontext.addtoemploys(objemploy); employcontext.savechanges(); homecoming redirecttoaction("index"); } grab { homecoming view(); } } public actionresult edit(int id) { employcontext = new employentities(); employ _employ = new employ(); //_employ = ( employ // id = id) homecoming view(); } [httppost] public actionresult edit(int id, employ objemploy) { seek { homecoming redirecttoaction("index"); } grab { homecoming view(); } } // // get: /employee/delete/5 public actionresult delete(int id) { employ _tempemploy = new employ(); homecoming view(_tempemploy); } // // post: /employee/delete/5 [httppost] public actionresult delete(int id, employ objemploy) { seek { //employcontext = new employentities(); //employ _tempemploy = new employ(); //_tempemploy.id = id; //employ _employ = employcontext.find(_tempemploy); employcontext.deleteobject(objemploy); employcontext.savechanges(); homecoming redirecttoaction("index"); } grab { homecoming redirecttoaction("delete", new { id = id, savechangeserror = true }); } } public iview detailsmodel { get; set; } }

}

actually i'm getting problem in accessing info using id i.e in db context there method "find(id)" there no such type of method in object context.what have accessing info edit ,details , delete info database

you can utilize firstordefault() fetching id, fetch first matching object.

db.users.firstordefault(x => x.userid== id);

hope, may help you. have anice day.

c# asp.net-mvc

How to draw different shapes on an image in openCV? -



How to draw different shapes on an image in openCV? -

i beginner in opencv. know c++ , android programming. have decided shift on opencv. in project, using opencv detecting reddish color ball through photographic camera , getting coordinates. using these coordinates, want draw same line or shape on separate white image. example, if utilize user moves ball write alphabet w in air, , have received coordinates of ball position, want draw w on separate image. not asking code, little help , guidance.

thanks in advance.

if have coordinates easy. first create cv::mat , set white.

cv::mat image; image.setto(cv::scalar(255,255,255));

then if have begin , end coordinates can draw line using opencv line function.

cv::line(image, cv::point(initial_coords.x, initial_coords.y), cv::point(end_coords.x, end_coords.y), cv::scalar(0,0,255));

finally w utilize puttext function

cv::puttext(image, "text", cv::point(coords.x, coords.y), cv::font_hershey_script_simplex, 2, scalar::all(255), 3,8);

if need erase window before adding new things utilize 1 time again

image.setto(cv::scalar(255,255,255));

opencv image-processing computer-vision

c# - How to decrease GPU useage in XAML + Direct3D app? -



c# - How to decrease GPU useage in XAML + Direct3D app? -

i'm developing app uses direct3d draw routes on map. have noticed phone hot when shows direct3d. have tried cut down draw calls decrease gpu loading set contentdirty @ prepareresource false. draw method not called more, unfortunately phone still hot one.

there way cut down gpu usage?

hresult direct3dinterop::prepareresources(_in_ const large_integer* presenttargettime, _out_ bool* contentdirty) { unreferenced_parameter(presenttargettime); if (m_renderer != nullptr && m_renderer->isdirty) { *contentdirty = true; } homecoming s_ok; } hresult direct3dinterop::gettexture(_in_ const drawingsurfacesizef* size, _inout_ idrawingsurfacesynchronizedtexturenative** synchronizedtexture, _inout_ drawingsurfacerectf* texturesubrectangle) { unreferenced_parameter(size); unreferenced_parameter(synchronizedtexture); unreferenced_parameter(texturesubrectangle); m_renderer->render(); homecoming s_ok; }

c# windows-phone-8 directx direct3d

sql server - Substring select string between two caracters -



sql server - Substring select string between two caracters -

the next code

declare @text varchar(max) set @text='[dim company].[company].[23]' select substring(@text, charindex('[dim company].[company].[', @text) , charindex(']',@text) - charindex('[dim company].[company].[', @text) + len(']'))

returns [dim company]. expecting homecoming integer between lastly [] -- in case 23. how can desired field?

if know it's last, why not reverse string, find value between first pair of brackets, reverse result?

much easier nesting charindex calls.

sql-server

angularjs - How can I avoid to trigger the applyDrilldown Function in Highcharts -



angularjs - How can I avoid to trigger the applyDrilldown Function in Highcharts -

i have build own drilldown behaviour javascript error in chart.prototype.applydrilldown function when press on text under stacked chart instead of column. how possible avoid behaviour?

here plunkr: http://plnkr.co/edit/dfvn9jnvqu2dv4s7jn7q?p=info

regards

ps.: in real project event triggered series.length times. can not reproduce in plunkr. ideas should look?

angularjs highcharts

ruby on rails - Building SQL3 db error -



ruby on rails - Building SQL3 db error -

i building database of skills , in origin thinking need title param them added required param. rid of title param can create new skills , description. right there error because looking :title. here controller:

class skillscontroller < applicationcontroller def index @skills = skill.all end def show @skills = skill.all end def new @skills = skill.all end def create @skills = skill.new(skill_params) if @skills.save redirect_to :action => 'index' else @skills = skill.find(:all) render :action => 'new' end end def edit @skills = skill.find(params[:id]) @skills = skill.find(:all) end def update @skills = skill.find(params[:id]) if @skills.update_attributes(params[:skill]) redirect_to :action => 'show', :id => @skills else @skills = skill.find(:all) render :action => 'edit' end end def delete skill.find(params[:id]).destroy redirect_to :action => 'index' end def show_skills @skills = skill.find(params[:id]) end end private def skill_params params.require(:skill).permit(:attribute_1, :attribute_2, :attribute_3) end

and here error when seek , submit new skill:

activerecord::statementinvalid in skillscontroller#create sqlite3::constraintexception: skills.title may not null: insert "skills" ("created_at") values (?)

i think easiest way bypass issue create skill.title not required not sure how prepare it. post /new form if helps:

<h1>add new skill</h1> <%= form_tag ({action: "create"}) %> <p><label for="skill">skill</label>: <%= text_field 'skill', 'title' %></p> <p><label for="skill_description">description</label><br/> <%= text_area 'skill', 'description' %></p> <%= submit_tag "create" %> <% end %> <%= link_to 'back', {:action => 'index'} %>

i tried getting rid of 'title' line , made more problems. maintain messing code , researching , give thanks knows issue. cheers , 1 time again stackers!!!

looks created title column not null constraint, database won't allow record created without title.

if don't need it, should drop column database.

create migration:

bundle exec rails generate migration remove_title_from_skills

edit migration file created , add:

def alter remove_column :skills, :title end

run migration:

bundle exec rake db:migrate

remove other references :title in application.

ruby-on-rails database sqlite3 sqlite3-ruby

CSS text overflow fade -



CSS text overflow fade -

how can emulate -webkit-mask-image css property on firefox , other browsers?

i need create text fade effect on text overflow. chrome i've done this:

-webkit-mask-image: -webkit-linear-gradient(left, rgba(0, 0, 0, 1) 90%, rgba(0, 0, 0, 0) 98%);

how can effect other browsers?

except webkit browser no browser supported mask image. need go alternative.

css

How to convert PHP array to a JSON array? -



How to convert PHP array to a JSON array? -

for example, have next code in json:

{ "tag": "img", "attr": [ { "alt": "text", "src": "url", "void": "true", "all": "true" } ] }

what php code should utilize echo/print code above? tried this:

$arr = array ( "tag" => "img", $attr = array ( "alt" => "text", "src" => "url", "void" => "true", "all" => "true" ) );

and then:

echo $arr = json_encode($arr);

but error. ideas?

your array declaration wrong. should be:

$arr = array ( "tag" => "img", "attr" => array ( "alt" => "text", "src" => "url", "void" => "true", "all" => "true" ) );

php arrays json

javascript - Magento email success message after form submission returns blank page -



javascript - Magento email success message after form submission returns blank page -

i used a tutorial create contact form module in magento:

however, way describes how output success message doesn't work. or i'm doing wrong. figured just:

mage::getsingleton('core/session')->addsuccess('success!');

but results in blank page.

does know way display success message within code outlined in site above?

thanks!

try customer/session instead of core/session. create sure append redirect code:

mage::getsingleton('customer/session')->addsuccess('success!'); $this->_redirect('your-url/');

javascript php jquery ajax magento

c# - Fill DataGridView on condition from database -



c# - Fill DataGridView on condition from database -

i have mysql database , datagridview in c# , fill datagridview following:

schooldataset schl = new schooldataset(); schooldatasettableadapters.studentinfotableadapter adptr = new schooldatasettableadapters.studentinfotableadapter(); adptr.fill(schl.studentinfo); datagridview1.datasource = schl.studentinfo.defaultview;

and undesired columns create them visible = false datagridview properties came problem if want specify info (rows) fill in datagridview such applying status like: fill info in datagridview isactive = 1 can still utilize above code modifications or have write sql query , fill datagridview manually ?

after searching , trying tons of codes got next in simplest code: in code above comment out lastly line datagridview1.datasource = schl.studentinfo.defaultview; or replace following

dataview dv = new dataview(schooldataset.studentinfo, "isactive = 'false'", "id", dataviewrowstate.currentrows);

which creates new dataview , filters according isactive column false value, 3rd parameter id sort based-on, , can write line datagridview1.datasource = dv; tell datagridview load info dataview. hope save someone's time. big goes @karthik ganesan

c# mysql datagridview

android - Bluetooth Low Energy - java.lang.NullPointerException -



android - Bluetooth Low Energy - java.lang.NullPointerException -

so i've been struggling past few hours , searching before don't think can find way sovle problem. i'm trying utilize context within of fragment extension , it's giving me errors i've pasted total code here in gist

enter link description here

from found on sounds happens when there null context, don't understand how prepare it.

logcat:

> 06-18 10:20:08.972 5718-5718/com.aparosecurity.kblock w/dalvikvm﹕ > threadid=1: thread exiting uncaught exception (group=0x41625898) > 06-18 10:20:08.992 5718-5718/com.aparosecurity.kblock > e/androidruntime﹕ fatal exception: main > java.lang.nullpointerexception > @ com.aparosecurity.kblock.imagefragment.oncreate(imagefragment.java:77) > @ android.support.v4.app.fragment.performcreate(fragment.java:1477) > @ android.support.v4.app.fragmentmanagerimpl.movetostate(fragmentmanager.java:904) > @ android.support.v4.app.fragmentmanagerimpl.performpendingdeferredstart(fragmentmanager.java:834) > @ android.support.v4.app.fragment.setuservisiblehint(fragment.java:841) > @ android.support.v4.app.fragmentpageradapter.setprimaryitem(fragmentpageradapter.java:130) > @ android.support.v4.view.viewpager.populate(viewpager.java:1066) > @ android.support.v4.view.viewpager.populate(viewpager.java:914) > @ android.support.v4.view.viewpager.onmeasure(viewpager.java:1436) > @ android.view.view.measure(view.java:15848) > @ android.widget.linearlayout.measurevertical(linearlayout.java:847) > @ android.widget.linearlayout.onmeasure(linearlayout.java:588) > @ android.view.view.measure(view.java:15848) > @ android.view.viewgroup.measurechildwithmargins(viewgroup.java:5012) > @ android.widget.framelayout.onmeasure(framelayout.java:310) > @ android.view.view.measure(view.java:15848) > @ android.view.viewgroup.measurechildwithmargins(viewgroup.java:5012) > @ android.widget.linearlayout.measurechildbeforelayout(linearlayout.java:1404) > @ android.widget.linearlayout.measurevertical(linearlayout.java:695) > @ android.widget.linearlayout.onmeasure(linearlayout.java:588) > @ android.view.view.measure(view.java:15848) > @ android.view.viewgroup.measurechildwithmargins(viewgroup.java:5012) > @ android.widget.framelayout.onmeasure(framelayout.java:310) > @ com.android.internal.policy.impl.phonewindow$decorview.onmeasure(phonewindow.java:2189) > @ android.view.view.measure(view.java:15848) > @ android.view.viewrootimpl.performmeasure(viewrootimpl.java:1905) > @ android.view.viewrootimpl.measurehierarchy(viewrootimpl.java:1104) > @ android.view.viewrootimpl.performtraversals(viewrootimpl.java:1284) > @ android.view.viewrootimpl.dotraversal(viewrootimpl.java:1004) > @ android.view.viewrootimpl$traversalrunnable.run(viewrootimpl.java:5481) > @ android.view.choreographer$callbackrecord.run(choreographer.java:749) > @ android.view.choreographer.docallbacks(choreographer.java:562) > @ android.view.choreographer.doframe(choreographer.java:532) > @ android.view.choreographer$framedisplayeventreceiver.run(choreographer.java:735) > @ android.os.handler.handlecallback(handler.java:730) > @ android.os.handler.dispatchmessage(handler.java:92) > @ android.os.looper.loop(looper.java:137) > @ android.app.activitythread.main(activitythread.java:5136) > @ java.lang.reflect.method.invokenative(native method) > @ java.lang.reflect.method.invoke(method.java:525) > @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:737) > @ com.android.internal.os.zygoteinit.main(zygoteinit.java:553) > @ dalvik.system.nativestart.main(native method)

any help appreciated.

the specific lines failing, error occurs when mcontext used.

@override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); fragval = getarguments() != null ? getarguments().getint("val") : 1; mhandler = new handler(); // initializes bluetooth adapter. api level 18 , above, reference // bluetoothadapter through bluetoothmanager. final bluetoothmanager bluetoothmanager = (bluetoothmanager) mcontext.getsystemservice(context.bluetooth_service); mbluetoothadapter = bluetoothmanager.getadapter(); }

you have not initialized mcontext , null. invoking method on null reference causes npe.

in fragment, utilize getactivity() reference hosting activity can used context. (caveat: when attached activity. works in oncreate() comes after onattach().)

so, replace

mcontext.getsystemservice()

with

getactivity().getsystemservice()

java android android-fragments android-studio bluetooth-lowenergy

random - Split an array into chaotic sub-arrays? -



random - Split an array into chaotic sub-arrays? -

there need split info array consisting of n rows , m columns s non-intersecting parts of (approximately) equal size.

realistically n*m not divisible s have work blocks of size floor(n*m) , ceil(n*m). @ moment to the lowest degree of concerns.

the essential required property every block structurally disconnected wholeness of info in sense neither big chunks of globally adjacent elements belong same block nor checker-board style splitting.

what suggest? should turn randomness or there neat structures suitable in situation?

i've found myself idly mulling on during snatched periods of downtime, , seems there should few ways it; depends on want achieve. here's i've been dreaming up, in case it's useful.

as understand this, you'd split n x m array i equal chunks, n , m unknown, , without adjacent elements sharing set.

firstly, four colour theorem tells can 4 sets; might worth seeing if there's existing algoritm working these out array. on other end of scale, can trivially n x m groups, assigning each element it's own singleton set.

how approach rather depends on you'd minimise - whether want smallest number of groups i, example. if wasn't issue, seek following:

looking @ n alone, if n even, split array sets of size n/2, create n/2 sets - 1 containing 1st element of each group, 1 containing 2nd etc. these contain non-consecutive elements. if n odd, create singleton set consisting of nth element, , proceed above remainder.

in 1 - dimensional case, give n/2 sets of size 2, potential set of size 1. work 2 dimensions well, dividing both n , m above.

as said, isn't reply looking for, hope might help promote farther investigation - replace odd / check 1 highest mutual factor or prime decomposition, example. might worth asking on math overflow.

i can write pseudocode (or python) how above might possible, if useful.

random arrays

javascript - Making a table dynamic -



javascript - Making a table dynamic -

made table product listings page has row of 3 images, row of text below each image, repeat. rather have page scroll downwards indefinitely, figure improve utilize js/jquery alter values in each < td > (img & matching text) create new page every 6 products. however, kindergarten-level js failing me miserably.

while think question i'm asking above pretty obvious, i'm wondering if never should have been set table in first place. seemed easiest way maintain organized, few examples i've seen seem < div >'s rather tables.

here's jsfiddle messing around with: http://jsfiddle.net/jshweky/fgvy2/

html:

<table id="saladgrid"> <tr class="saladpics"> <td class="s1"></td> <td class="s2"></td> <td class="s3"></td> </tr> <tr class="saladtxt"> <td class="txt"> <p>acorn squash, golden beets, pistachios</p> </td> <td class="txt"> <p>roasted eggplant, herbed ricotta, sumac</p> </td> <td class="txt"> <p>arugula, fennel, blackberries, quinoa, pickled shallots</p> </td> </tr> <tr class="saladpics"> <td class="s4"></td> <td class="s5"></td> <td class="s6"></td> </tr> <tr class="saladtext"> <td class="text"> <p>arugula, orange, golden beets, golden tomatoes, pistachios</p> </td> <td class="text"> <p>caesar</p> </td> <td class="text"> <p>butternut squash, lime, feta, chili</p> </td> </tr> </table> <button id="prev">prev</button> <button id="next">next</button>

css (paraphrased):

table { width: 100%; height: 100%; margin-top: 0; padding: 0; border: 0; border-spacing: 0; } td { margin: 0; padding: 0; border: 0; text-align: center; vertical-align: middle; } #saladgrid table { margin: 0 auto; border-spacing: 30px; } .saladpics td { height: 350px; width: 350px; background-position: center; background-size: 415px 400px; background-repeat: no-repeat; border-radius: 250px; border: 1px black solid; } .saladtext { position: relative; margin-bottom: -20px; } .saladpics td.s1 { background-image: url("http://i1281.photobucket.com/albums/a514/jshweky/gourmade%20to%20order/img_1989_zps38d802a7.jpg"); }

i figure it's matter of creating new var's , writing function add together 6 existing img class (e.g. s1 becomes s7, etc.) that's guess , said, if that's right i'm still in embryonic stages of js coding.

your javascript swap image works fine, issue first part of script. commented out in fiddle , worked fine. there improve ways (sliding divs within container, build elements in javascript , append them frames on page - give pinterest style effect of loading new elements @ bottom) - depends on how want handle suggestion using jquery add together or remove elements dom.

//var s7= new image(); //img.src=url('https://encrypted-tbn0.gstatic.com/images?q=tbn:and9gcrhc9vk1u5yc5rwmhuk9ai2rgidcsh-wxpt-aleqm9onxi9xbn9da'); $(document).ready(function () { $('#prev').click(function () { $('.s1').css('background-image', 'url("http://i1281.photobucket.com/albums/a514/jshweky/gourmade%20to%20order/img_1483_zpsc4ca87cf.jpg")'); }); });

also, here alternate syntax .css() allow alter more 1 property of elements @ time (you need utilize .html() function alter text in next element too):

$('.s1').css({backgroundimage : 'url("http://i1281.photobucket.com/albums/a514/jshweky/gourmade%20to%20order/img_1483_zpsc4ca87cf.jpg")', backgroundsize : "cover"}); });

javascript jquery html css

php - posts order by title second word -



php - posts order by title second word -

this mutual question, haven't been able find straightforward reply to. want generate list of custom post type titles. im using 'orderby' => 'title' have them display alphabetically. titles names , lastly names , want sort lastly name. know create meta fields seperated first , lastly names , order lastly name field. i'd see if there no method explode 'title' , pass sec word in `orderby'.

this basic code:

<?php // 'actors' post type $args = array( 'post_type' => 'actors', 'orderby' => 'title', 'order' => 'asc', 'nopaging' => true, 'cache_results' => false, 'update_post_meta_cache' => false ); $loop = new wp_query($args); while($loop->have_posts()): $loop->the_post(); echo '<li><img src="' . get_post_meta(get_the_id(),'_dtm_small_image', [0]) . '"><span>' . get_the_title() . '</span></li>'; endwhile; wp_reset_query(); ?>

iv'e tried to:

$gettitle = get_the_title(); $lastname = explode(" ", $gettitle);

and alter 'orderby' => $lastname[1], . doesnt work. there no way utilize sec word in title sort posts?

you can't loop, wordpress doesn't have option.

what can do, it's split title , create array.

$people = array(); while($loop->have_posts()): $loop->the_post(); list($firstname, $lastname) = explode(" ", get_the_title() ); // can utilize list, since said that's first , lastly name on title. $people[] = $lastname; endwhile; wp_reset_query(); sort($people); // sort array asc. note: can create function sort sort or rsort, on input foreach ($people $last) { echo $last, "<br />"; // echo lastly name }

this not efficient, works. should consider adding 2 fields wordpress.

php wordpress

osgi - when using gogo gosh scripts, how do I get print outs from all commands -



osgi - when using gogo gosh scripts, how do I get print outs from all commands -

i'm trying automate provisioning , searching of service speed testing of changes osgi system. utilize maven pax:provision set environment various repositories.

i have commands load info xml files , commands search services. search commands homecoming string describing results.

i've provision.tsl file commands load osgi environment , search.tsl file runs search commands. in search.tsl have list of search command, each various tables i've loaded. e.g.

echo doing searching searchcell sometable somevalue searchcolumnname echo search someothertable searchcell someothertable someothervalue searchcolumnname echo search yetanothertable searchcell yetanothertable yetsomeothervalue searchcolumnname

however, when run search command e.g.

osgi> gosh search.tsl

i result lastly command in file. echo works normal though , looks like.

doing searching search someothertable search yetanothertable homecoming results searchcell yetanothertable

is expected behaviour gosh?

the gosh console automatically prints value of each interactive command.

this makes appear searchcell command printing result, when in fact returning string, gogo prints.

this doesn't work in scripts, either need recode searchcell command print stdout, or explicitly print each result in script:

echo doing searching echo (searchcell sometable somevalue searchcolumnname) echo search someothertable echo (searchcell someothertable someothervalue searchcolumnname)

osgi pax gogo-shell

time - How to convert Milliseconds to "X mins, x seconds" in Java? -



time - How to convert Milliseconds to "X mins, x seconds" in Java? -

i want record time using system.currenttimemillis() when user begins in program. when finishes, subtract current system.currenttimemillis() start variable, , want show them time elapsed using human readable format such "xx hours, xx mins, xx seconds" or "xx mins, xx seconds" because not take hour.

what's best way this?

since 1.5 there java.util.concurrent.timeunit class, utilize this:

string.format("%d min, %d sec", timeunit.milliseconds.tominutes(millis), timeunit.milliseconds.toseconds(millis) - timeunit.minutes.toseconds(timeunit.milliseconds.tominutes(millis)) );

(thanks @damian comments) if want add together leading 0 values 0-9, do:

string.format("%02d min, %02d sec", timeunit.milliseconds.tominutes(millis), timeunit.milliseconds.toseconds(millis) - timeunit.minutes.toseconds(timeunit.milliseconds.tominutes(millis)) );

for java versions below 1.5 or systems not back upwards timeunit class (such android before api version 9), next equations can used:

int seconds = (int) (milliseconds / 1000) % 60 ; int minutes = (int) ((milliseconds / (1000*60)) % 60); int hours = (int) ((milliseconds / (1000*60*60)) % 24); //etc...

java time

qt - QT5.3 installer for windows throws error ' is not a valid win32 application' -



qt - QT5.3 installer for windows throws error ' is not a valid win32 application' -

i trying install qt5.3 on windows machine mingw. when seek install, throws error saying

"qt-opensource-windows-x86-mingw482_opengl-5.3.0.exe not valid win32 application."

i tried online installer, network not fast, installation doesn't go beyond 20% , takes huge time.

any solution appreciated.

thanks,

vrushali

the downloaded file corrupted. have download again. suppose can inquire download , set on dvd you.

windows qt

php - "Could not connect. Too many connections" Error in MySQLi -



php - "Could not connect. Too many connections" Error in MySQLi -

i have next code

function opendbconn($params){ $conn_mode = $params['conn_mode']; $db_conn = $params['db_conn']; //create connections if(empty($db_conn->info)) { $db_conn = new mysqli("localhost", $user, $password, "database"); $db_conn->set_charset('utf8'); $mysqli_error = $db_conn->connect_error; } if($mysqli_error !== null){ die('could not connect <br/>'. $mysqli_error); }else{ homecoming $db_conn; } } //close db connection function closedbconn( $params ){ $db_conn = $params['db_conn']; $db_conn->close; } //used below $db_conn = opendbconn(); save_new_post( $post_txt, $db_conn ); closedbconn( array('db_conn'=>$db_conn));

from time time, "could not connect. many connections" error. tends happen when have google bot scanning website.

this problem seems have started ever since upgrading mysqli mysql. there advice on how ensure connections closed?

thanks

you need increment number of connections mysql server (the default 100 , typically each page load consumes 1 connection)

edit /etc/my.cnf

max_connections = 250

then restart mysql

service mysqld restart

http://major.io/2007/01/24/increase-mysql-connection-limit/

php mysqli runtime-error

ios - UITableview create alphabetic indexing from data array -



ios - UITableview create alphabetic indexing from data array -

i have nsmutablearray populated sqlite query returns want display in uitableview in alphabetical order.

i know want display letter indexs see in contacts application etc.

however not sure how set indexs , create sections array each sections next letter in alphabet.

how go taking array , getting sections , indexs needed?

let's array (nsmutablearray myarray) letters looks this:

( { headertitle = v; rowvalues = ( { id = 60; name = "valley of giants (2)"; "real_name" = "valley of giants"; "wine_count" = " (2)"; } ); }, { headertitle = r; rowvalues = ( { id = 47; name = "rothbury estate (6)"; "real_name" = "rothbury estate"; "wine_count" = " (6)"; }, { id = 48; name = "rouge homme (4)"; "real_name" = "rouge homme"; }, { id = 45; name = "rawson\u2019s retreat (7)"; "real_name" = "rawson\u2019s retreat"; }, { id = 46; name = "rosemount estate (36)"; "real_name" = "rosemount estate"; } ); },

in table view, set number of sections

- (nsinteger)numberofsectionsintableview:(uitableview *)tableview { homecoming [myarray count]; }

number of rows in section:

- (nsinteger)tableview:(uitableview *)tableview numberofrowsinsection:(nsinteger)section{ homecoming [[[myarray objectatindex:section] objectforkey:@"rowvalues"] count]; }

section title

-(nsstring *)tableview:(uitableview *)tableview titleforheaderinsection:(nsinteger)section{ homecoming [[myarray objectatindex:section] valueforkey:@"headertitle"]; }

then within cellforrowatindexpath can access info this

- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath{ nsstring *name= [[[[myarray objectatindex:indexpath.section] objectforkey:@"rowvalues"] objectatindex:indexpath.row] valueforkey:@"name"]; // , create cell do... }

if need sort array in alphabetical order can like:

nssortdescriptor *descriptor = [[nssortdescriptor alloc] initwithkey:@"headertitle" ascending:yes]; [myarray sortusingdescriptors:[nsarray arraywithobject:descriptor]];

ios objective-c arrays uitableview

c# 4.0 - C# explicit cast - from collection of KeyValuerPair to Dictionary -



c# 4.0 - C# explicit cast - from collection of KeyValuerPair to Dictionary -

i have list of keyvaluepairs. utilize todictionary.

however noted error message (shown below) has explicit cast, implies can cast list dictionary<...>. how can this?

cannot implicitly convert type 'system.linq.iorderedenumerable<system.collections.generic.keyvaluepair<int,string>>' 'system.collections.generic.dictionary<int, string>'. explicit conversion exists (are missing cast?)

sample code:

dictionary<int, string> d = new dictionary<int, string>() { {3, "c"}, {2, "b"}, {1, "a"}, }; var s = d.orderby(i => i.value); d = s;

implies can cast list dictionary

well, implies cast valid @ compile-time. doesn't mean work @ execution time.

it's possible code work:

iorderedenumerable<keyvaluepair<string, string>> pairs = getpairs(); dictionary<string, string> dictionary = (dictionary<string, string>) pairs;

... if value returned getpairs() class derived dictionary<,> implemented iorderedenumerable<keyvaluepair<string, string>>. it's unlikely that's actually case in normal code. compiler can't stop trying, won't end well. (in particular, if code in question , standard linq objects, fail @ execution time.)

you should stick todictionary... although should aware you'll lose ordering, there's no point in ordering start with.

to show code in question:

dictionary<int, string> d = new dictionary<int, string>() { {3, "c"}, {2, "b"}, {1, "a"}, }; var s = d.orderby(i => i.value); d = (dictionary<int, string>) s;

that compiles, fails @ execution time predicted:

unhandled exception: system.invalidcastexception: unable cast object of type 'system.linq.orderedenumerable`2[system.collections.generic.keyvaluepair`2[system.int32,system.string],system.string]' type 'system.collections.generic.dictionary`2[system.int32,system.string]'. @ test.main()

as bit of background, can always cast interface type non-sealed class ("target"), if type doesn't implement interface, because it's possible class derived "target" implement interface.

from section 6.2.4 of c# 5 specification:

the explicit reference conversions are:

... from class-type s interface-type t, provided s not sealed , provided s not implement t. ...

(the case s does implement t covered implicit reference conversions.)

if seek implicitly convert value , there's no implicit conversion available, there's explicit conversion available, compiler give warning in question. means can prepare compiler-error cast, need aware of possibility of failing @ execution time.

here's example:

using system; class test { static void main() { iformattable x = getobject(); } static object getobject() { homecoming datetime.now.second >= 30 ? new object() : 100; } }

error message:

test.cs(7,26): error cs0266: cannot implicitly convert type 'object' 'system.iformattable'. explicit conversion exists (are missing cast?)

so can add together cast:

iformattable x = (iformattable) getobject();

at point, code work half time - other half, it'll throw exception.

c#-4.0 .net-4.5

prolog - Reading from user_input causes ":|" to appear in output -



prolog - Reading from user_input causes ":|" to appear in output -

my code using read_line_to_codes/2 , read_stream_to_codes/2 in order read user_input. how these reads organized:

main :- read_line_to_codes(user_input, [a]), read_line_to_codes(user_input, b), /* parsing happens here */ read_stream_to_codes(user_input, c), /* more parsing happens here , code goes on */

i compiling programme using next command:

swipl -q -t main -o programme -c program.pl

the programme runs fine, due reads in main, output |:|: characters (the swipl console shows |: whenever user has input something). when remove i/o code program, runs without outputting characters.

is there way rid of behavior?

you have utilize prompt1/1 predicate set prompt next line or prompt/2 alter prompt message globally.

e.g. using prompt1/1:

?- read_line_to_codes(user_input, l). |: test l = [116, 101, 115, 116]. ?- prompt1(''), read_line_to_codes(user_input, l). test l = [116, 101, 115, 116].

or, using prompt/2:

?- prompt(old, 'give me: '). old = '|: '. ?- read_line_to_codes(user_input, l). give me: abc l = [97, 98, 99].

prolog swi-prolog

java - Hibernate JPA @Inheritance TABLE_PER_CLASS JpaRepository on Child entity union select all tables -



java - Hibernate JPA @Inheritance TABLE_PER_CLASS JpaRepository on Child entity union select all tables -

i have problem have base of operations abstract entity station inheritance table_per_class , 3 kid tables stationcompany stationanalysis stationvariant

@mappedsuperclass @inheritance(strategy = inheritancetype.table_per_class ) public abstract class station { @entity public class stationcompany extends station { @manytoone(optional = false, fetch = fetchtype.eager) @fetch(fetchmode.select) private company company; @entity public class stationanalysis extends stationcompany { @manytoone(optional = false, fetch = fetchtype.eager) @fetch(fetchmode.select) private analysis analysis; @entity public class stationvariant extends stationanalysis { @manytoone(optional = false, fetch = fetchtype.eager) @fetch(fetchmode.select) private variant variant; public interface istationcompanyrepository extends jparepository<stationcompany, long> { @service public class stationservice implements istationservice<stationcompany> { @autowired istationcompanyrepository stationcompanyrepository;

then search findall on stationcompany, hibernate create query union select. search stationcompany entrys.

select x ( select stationcompany union select b stationvariant union select c stationanalysis )

the problem hibernate mapping. think had problem construction station stationcompany station... solve problem aditional abstract @mappedsuperclass classes. after hibernate select right table , no more union selects.

@mappedsuperclass @inheritance(strategy = inheritancetype.table_per_class) public abstract class station { @mappedsuperclass public abstract class abstractstationcompany extends station { @manytoone(optional = false, fetch = fetchtype.eager) @fetch(fetchmode.select) private company company; @entity public class stationcompany extends abstractstationcompany { @mappedsuperclass public class abstractstationanalysis extends abstractstationcompany { @manytoone(optional = false, fetch = fetchtype.eager) @fetch(fetchmode.select) private analysis analysis; @entity public class stationanalysis extends abstractstationanalysis { @entity public class stationvariant extends abstractstationanalysis {

java hibernate jpa table-per-class

mysql - Adjacency table to nested set conversion -



mysql - Adjacency table to nested set conversion -

i need convert adjacency list nested set in mysql. have found 1 resource on net convert adjacency list nested set using mysql(http://data.bangtech.com/sql/nested_set_treeview.htm). code on same webpage.

create table test.tree (emp char(10) not null, boss char(10)); create table test.personnel( emp char(20) primary key, boss char(20) references personnel(emp), salary decimal(6,2) not null ); insert test.personnel values ('jerry', 'null',1000.00); insert test.personnel values ('bert', 'jerry',900.00); insert test.personnel values ('chuck', 'jerry',900.00); insert test.personnel values ('donna', 'chuck',800.00); insert test.personnel values ('eddie', 'chuck',700.00); insert test.personnel values ('fred', 'chuck',600.00); insert test.tree select emp, boss test.personnel;

i create tree table personnel table. tree table has boss-employee hierarchy. adjacency list. convert nest set, applied code.

begin atomic declare counter integer; declare max_counter integer; declare current_top integer; set counter = 2; set max_counter = 2 * (select count(*) test.tree); set current_top = 1; insert test.stack select 1, emp, 1, null test.tree boss null; delete test.tree boss null; while counter <=(max_counter - 2) loop if exists (select * test.stack s1, test.tree t1 s1.emp = t1.boss , s1.stack_top = current_top) begin -- force when top has subordinates, set lft value insert test.stack select (current_top + 1), min(t1.emp), counter, null test.stack s1, test.tree t1 s1.emp = t1.boss , s1.stack_top = current_top; delete test.tree emp = (select emp test.stack stack_top = current_top + 1); set counter = counter + 1; set current_top = current_top + 1; end else begin -- pop stack , set rgt value update test.stack set rgt = counter, stack_top = -stack_top -- pops stack stack_top = current_top set counter = counter + 1; set current_top = current_top - 1; end if; end loop; end;

mysql workbench shows several syntax errors not remove.

i familiar basic operations of mysql not debug code on own. how remove these errors? plz help. sec source found above operation http://www.sqlservercentral.com/articles/hierarchy/94040/ code in t sql , don't have plenty skills translate mysql.

you should set null , not 'null' in line

insert test.personnel values ('jerry', 'null',1000.00);

correct version:

insert test.personnel values ('jerry', null, 1000.00);

mysql nested-sets adjacency-list

sql - How to reverse engineer MySQL database tables one-by-one onto an ERD using WorkBench -



sql - How to reverse engineer MySQL database tables one-by-one onto an ERD using WorkBench -

i have database containing hundreds of tables, , want create erd out of using mysql workbench's reverse engineer feature.

but reverse engineering science such amount of objects @ 1 time beyond workbench's capabilities, i'm planning one-by-one, have these 5 tables know related each other , reversed engineered successfully, , have erd of them. want add together more tables see fit same database onto generated erd reverse engineering science 5 tables before.

i know can generating new erd each time want add together table 5 tables. there work-around don't have reverse engineer each time want add together new table thinks related 5 tables.

thanks.

try reverse engineering science new model , save that. open main model , take file -> include model include other model.

btw: there limits content in model (and more: on single diagram), @ to the lowest degree should able reverse engineer @ to the lowest degree 200 objects @ once.

mysql sql database mysql-workbench erd

algorithm - Efficiently filling empty cells in 3D matrix -



algorithm - Efficiently filling empty cells in 3D matrix -

i have 3d "cubical" matrix, cells filled , others empty. closed part enclosed filled cells represents hollow shape. example, matrix have cells filled in such way form surface of hollow sphere. now, want efficient way fill interior of sphere: if cell c0 surrounded in directions filled cells (filled cell in direction need not immediate neighbour of c0), fill c0.

a naive way next :-

for each cell, scan in +x, -x, +y, -y, +z, -z direction, , see if encounter filled cell in each , every direction.

if filled cell encountered in each , every direction, fill cell (as part of interior of shape).

if reach end of grid in 1 direction without encountering filled cell, cell under consideration not interior shape, , should remain unfilled.

the complexity of above approach o(n^4), dimension of 3d grid n*n*n.

an optimization follows :-

if unfilled cell c[x][y][z], encountered 1 filled cell each in 6 directions, not c[x][y][z] needs filled, guaranteed cells scanned (i.e. {in +x direction, cells c[x][y][z], c[x+1][y][z], c[x+2][y][z], ..., till first filled cell}, -x, +y, -y, +z, -z direction) must part of interior of shape, , hence must filled.

another follows :-

if unfilled cell c[x][y][z], not encounter filled cell in, say, +x direction, not c[x][y][z] remain unfilled, guaranteed cells scanned (i.e. in +x direction, cells c[x][y][z], c[x+1][y][z], c[x+2][y][z], ..., till end of grid) must part of exterior , hence, must remain unfilled.

can suggest more efficient approach problem? simple optimizations above, might not cut down order of time complexity, welcome.

you dealing 3d flood fill. see detailed wikipedia article http://en.m.wikipedia.org/wiki/flood_fill

algorithm data-structures matrix

wpf - TaskFactory New UI Creation -



wpf - TaskFactory New UI Creation -

how create new ui element using taskfactory? when seek next error :

the calling thread must sta, because many ui components require this.

example code

dim txtboxlist new list(of textbox) sub startthread() dim ts taskscheduler = taskscheduler.fromcurrentsynchronizationcontext() task.factory.startnew(sub() createcontrol(), ts) end sub sub createcontrol() dim txtbox new textbox dispatcher.begininvoke(sub() txtboxlist.add(txtbox)) end sub

if you're working wpf, need leave behind , notions might have learned ancient technologies , understand , encompass the wpf mentality.

basically, never need create or manipulate ui elements in procedural code in wpf. instead, wpf lends heavily utilize databinding.

the wpf threading model not allow create or manipulate instances of ui elements in background threads, , add together them visual tree created "main" ui thread.

anyways, there 0 need such thing, because creating ui elements in cases trivial task can (and must) performed ui thread.

rather worrying visual tree, should concentrate on having data loaded in background threads, , passed datacontext ui can display info accordingly.

this little illustration uses itemscontrol display list of users, loaded asynchronously in background thread , dispatched ui thread display:

<window x:class="wpfapplication7.asyncitemscontrol" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <itemscontrol itemssource="{binding}"> <itemscontrol.itemtemplate> <datatemplate> <border background="lightgray" borderbrush="black" borderthickness="1" margin="2"> <stackpanel> <textblock text="{binding lastname}" margin="2"/> <textblock text="{binding firstname}" margin="2"/> </stackpanel> </border> </datatemplate> </itemscontrol.itemtemplate> </itemscontrol> </window>

code behind:

public partial class asyncitemscontrol : window { public asyncitemscontrol() { initializecomponent(); var dispatcher = taskscheduler.fromcurrentsynchronizationcontext(); task.factory.startnew(() => getusers()) .continuewith(x => datacontext = x.result,dispatcher); } public list<user> getusers() { // pretend method calls web service or database retrieve data, , takes 5 seconds response: thread.sleep(5000); homecoming new list<user> { new user() {firstname = "marty", lastname = "mcfly"}, new user() {firstname = "emmett", lastname = "brown"}, new user() {firstname = "bufford", lastname = "tannen"} }; } }

data item:

public class user { public string lastname { get; set; } public string firstname { get; set; } }

result:

notice illustration uses databinding , not create or manipulate ui elements in procedural code, rather operates simple user class simple string properties.

also notice during 5 seconds "load" time, ui responsive because actual work beingness performed background thread.

this approach allows greater separation between ui , info allows much greater scalability , customizability of ui without having alter underlying business / application logic.

notice how itemscontrol takes care of creating , rendering appropiate ui elements needed display 3 info items. actual definition of "how each item looks" datatemplate.

i recommend reading material linked thoughout reply more in-depth understanding of how wpf works in general.

side note: if you're targetting c# 5.0 can leverage async / await , create code cleaner removing task based stuff. i'm on c# 4.0 feature not available me.

wpf rocks. re-create , paste code in file -> new project -> wpf application , see results yourself.

let me know if need farther help.

wpf vb.net taskfactory

Removing "/jekyll/update" from the jekyll URLs -



Removing "/jekyll/update" from the jekyll URLs -

i trying build site using jekyll. here config:

# dependencies markdown: redcarpet pygments: true # permalinks permalink: /blog/:categories/:year/:month/:day/:title/ # setup title: jekyll metro tagline: 'a metro theme jekyell' description: 'a sample blog using jekyllmetro' url: http://blog-olakara.rhcloud.com # author details author: 'abdel raoof olakara' # google analytics gahandler: 'ua-52149651-1' # blog configurations paginate: 5 # posts per page on blog index paginate_path: "/blog/page:num" destination: ./_site navigation: - text: blog url: /blog/ - text: archive url: /archive/ - text: url: /about/ # custom vars version: 0.1.0

and here blog : http://blog-olakara.rhcloud.com/blog/ if go post.. "/jekyll/update/"..

what need avoid display of jekyll/update in path. configuration error doing?

the illustration post has 2 categories "jekyll" , "update" appended url. seek remove them.

you can alter "permalink" pattern :

permalink: /blog/:categories/:year/:month/:day/:title/

to :

permalink: /blog/:year/:month/:day/:title/

url jekyll

Trying to parse json source with javascript -



Trying to parse json source with javascript -

this question has reply here:

parse json in javascript? [duplicate] 16 answers

i trying parse json source javascript.

i have json source:

var exam = '{ status : 'connected', authresponse: { accesstoken: 'it accesstoken', expiresin:'2014-06-19', signedrequest:'it signedrequest', userid:'mp172' } }';

to parse, utilize json.parse(exam);

after source, not working. want parse source javascript.

actually, json source not valid. according json.org, fellow member should quote "

change exam {"status":"connected","authresponse":{"accesstoken":"it accesstoken","expiresin":"2014-06-19","signedrequest":"it signedrequest","userid":"mp172"}}

javascript json parsing

python - Conduit.simpleHttp - perform a request supplied with headers and data -



python - Conduit.simpleHttp - perform a request supplied with headers and data -

i have simple application sends http(s) request , print info returned:

import network.http.conduit (simplehttp) simplehttp "http://example.com" >>= b.putstr

how supply request headers? or more concrete, how create request below (written in python) in haskell?

requests.post('https://some-url.com',data=json.dumps({"aaa":"bbbcccddd"}), headers={"content-type":"application/json"})

the documentation doesn't http://hackage.haskell.org/package/http-conduit-1.2.1/docs/network-http-conduit.html

note docs request:

the constructor info type not exposed. instead, should utilize either def method retrieve default instance, or parseurl build url, , use records below create modifications.

so can configure request using number of record names. in case need requestheaders , requestbody. here example:

{-# language overloadedstrings #-} import data.text (text) import qualified data.aeson aeson import qualified data.map map import network.http.conduit main :: io () main = request <- parseurl "http://example.com" res <- withmanager $ httplbs $ configurerequest request print res configurerequest r = r { method = methodpost, requestheaders = ("content-type", "application/json") : requestheaders r, requestbody = requestbodylbs (aeson.encode $ map.fromlist [("aaa" :: text, "bbbccsddd" :: text)]) }

python haskell networking

How to change String Array to ArrayList in java -



How to change String Array to ArrayList in java -

here original code has defined string-array (25). working perfectly. don't need define 25. instead, used arraylist. please check code.

using string of array:

public string[] getemailaddr(string straccountnbr) throws exception { string strquery2 = null; resultset rs = null; preparedstatement ps = null; string[] emailaddress = new string[25]; int i=0; strquery2 = "select c.emailaddress emailaddress" + " customeremailid c " + "where c.accountnbr = ? " ; logmsg("strquery2: "+strquery2); ps = getdbconn().preparestatement(strquery2); ps.setstring(1, straccountnbr); rs = ps.executequery(); while(rs.next()) { emailaddress[i]=(rs.getstring("emailaddress")); logmsg("emailaddress[i]"+" "+i+": "+emailaddress[i]); i=i+1; } homecoming emailaddress; }

here, need alter string-array arraylist. tried this,

public string[] getemailaddr(string straccountnbr) throws exception { string strquery2 = null; resultset rs = null; preparedstatement ps = null; //newly tried // arraylist<string> strarremailids = new arraylist<string>(); string[] emailaddress= new string[strarremailids.size()]; strarremailids.toarray(emailaddress); //newly tried // int i=0; strquery2 = "select c.emailaddress emailaddress" + " customeremailid c " + "where c.accountnbr = ? " ; logmsg("strquery2: "+strquery2); ps = getdbconn().preparestatement(strquery2); ps.setstring(1, straccountnbr); rs = ps.executequery(); while(rs.next()) { emailaddress[i]=(rs.getstring("emailaddress")); logmsg("emailaddress[i]"+" "+i+": "+emailaddress[i]); i=i+1; } homecoming emailaddress; }

email ids database instead of example.com.

but getting java.lang.arrayindexoutofboundsexception: 0 error in line. emailaddress[i]=(rs.getstring("emailaddress"));

please help!

this not how utilize arraylist.

first, need write:

list<string> strarremailids = new arraylist<>();

so, programme interface , utilize java 7 diamond operator.

next, remove index i. don't need this.

finally, do:

emailaddress.add(rs.getstring("emailaddress"));

to convert string[] can do:

string[] arr = emailaddress.toarray(new string[emailaddress.size()]);

here suggestion final code:

public string[] getemailaddr(string straccountnbr) throws exception { final list<string> emailaddress = new arraylist<>(); final string strquery2 = "select c.emailaddress emailaddress" + " customeremailid c " + "where c.accountnbr = ? "; seek (final preparedstatement ps = getdbconn().preparestatement(strquery2)) { ps.setstring(1, straccountnbr); seek (final resultset rs = ps.executequery()) { while (rs.next()) { emailaddress.add(rs.getstring("emailaddress")); } } } homecoming emailaddress.toarray(new string[emailaddress.size()]); }

i have removed pointless assignments null. have added try-with-resources blocks close external resources, code 1 massive memory leak.

java arrays string arraylist