Wednesday, 15 May 2013

How to use aysnc module in node.js to loop over two arrays -



How to use aysnc module in node.js to loop over two arrays -

i want loop on array , write info database. code below shows how in non-async way loop. know not preferred way of doing it.

for(var x = 0;x < tt.matches.length;x++) //match each player match , playerid tournament tree { if(tt.matches[x].p[0] !== -1) { var tmid = json.stringify(tt.matches[x].id); player.update({ _id : grupd.players[y] },{ tournamentmatchid : tmid, treeid : tt.matches[x].p[0], opponent : tt.matches[x].p[1] },{ safe : true }, function (err) { if(err) { console.log(err); } }); y++; } if(tt.matches[x].p[0] === -1) { byes++; } if(tt.matches[x].p[1] !== -1) { var tmid = json.stringify(tt.matches[x].id); player.update({ _id : grupd.players[y] },{ tournamentmatchid : tmid, treeid : tt.matches[x].p[1], opponent : tt.matches[x].p[0] },{ safe : true }, function (err) { if(err) { console.log(err); } }); y++; } if(tt.matches[x].p[1] === -1) { byes++; } }

i need perform following, 1 time again shown in 'traditional way'.

for(var x = 0;x < plyrs.length;x++) { var nextmatch = json.stringify(tt.upcoming(plyrs[x].treeid)) ; player.update({ _id : plyrs[x]._id },{ tournamentmatchid : nextmatch },{ safe : true }, function (err) { if(err) { console.log(err); } }); }

you keeping counter of open db calls, calling next phase of programme when of calls have returned. see below.

there's theoretical hole in approach though, if of player.update() calls homecoming before process.nexttick completion status may triggered early.

var activecalls = 0; for(var x = 0;x < tt.matches.length;x++) //match each player match , playerid tournament tree { if(tt.matches[x].p[0] !== -1) { var tmid = json.stringify(tt.matches[x].id); activecalls++; player.update({ _id : grupd.players[y] },{ tournamentmatchid : tmid, treeid : tt.matches[x].p[0], opponent : tt.matches[x].p[1] },{ safe : true }, function (err) { activecalls--; if(err) { console.log(err); } if ( activecalls == 0 ) donextthing() }); y++; } if(tt.matches[x].p[0] === -1) { byes++; } if(tt.matches[x].p[1] !== -1) { var tmid = json.stringify(tt.matches[x].id); activecalls++; player.update({ _id : grupd.players[y] },{ tournamentmatchid : tmid, treeid : tt.matches[x].p[1], opponent : tt.matches[x].p[0] },{ safe : true }, function (err) { activecalls--; if(err) { console.log(err); } if ( activecalls == 0 ) donextthing() }); y++; } if(tt.matches[x].p[1] === -1) { byes++; } }

arrays node.js asynchronous

php - substr not working correctly? -



php - substr not working correctly? -

i creating forum, , working on bbcode section. bbcode works, implementing emoticon system. syntax looks this: [e]:)[/e]

i made string testing purposes:

[b]hello world[/b] [i]i having fun[/i] [e]:)[/e] how doing today?! <3[color=blue]:d[/color]

and returning not want. here returning:

:)[/e] how doing today?! <3[color=bl

this code:

function bbcode($str) { if (strpos($str, '[e]')!==false && strpos($str, '[/e]')!==false) { $f = strpos($str, '[e]') + 3; $s = strpos($str, '[/e]'); $emote = substr($str, $f, $s); } homecoming $emote; }

note $f , $s returning right positions, 45 , 47, substr not cutting string correctly. why , how can prepare it?

"string substr ( string $string , int $start [, int $length ] )

returns portion of string specified start and length parameters."

$emote = substr($str, $f, $s - $f);

php

c system calls being ran before the if statement -



c system calls being ran before the if statement -

so here problem, given code, added before please input name ignored, , automatically first instruction run(without first checking if x 5, input name, instructions prior run. if first line of programme printf, ignored , inquire input print printf statement though first. please help

int main(int argc, char** argv) { char val[70]; int x=3; if(x>5) { if(write(1, "please input name", 22)!=22) { homecoming -1; } if(read(0, val, 36) < 0) {} if(write(1, val, 36)!=36) {} } }

printf works on stdout file*. read() , write() calls work straight on file descriptors.

a file* buffered, meaning stuff printf resides in buffer in programme until flushed. while write() sends info straight operating system, without buffering in application.

so flush file* buffer create output appear:

int main(int argc, char** argv) { char val[70]; int x=3; printf("hello"); fflush(stdout);

and if stdout terminal, auto flushed when write newline, e.g. printf("hello\n");

c

android - Audiotrack Can't stop playback immediately -



android - Audiotrack Can't stop playback immediately -

developer docs says must phone call pause() flush()(for discard playback data).

but doesn't work.

i've found out if add together little delay between audiotrack.pause() , audiotrack.flush() calls. sound playback stops immediately, doesn't work.

so how stop audiotrack immediately?

android

HTML/CSS Div Extending Beyond Its Closing Tag -



HTML/CSS Div Extending Beyond Its Closing Tag -

on web page i'm creating, page dynamically generated php-based cms. cms fetches info page database, echoes right html tags etc onto page.

the problem have reason browser extending div beyond it's closing tag.

ie: though can see tag closes, browser doesn't appear to, styling applied within div beingness applied whole page.

below html output. (this extract of page, , header div 1 that's persisting).

<div id="header"> <table> <tr> <td style="width: 10%;"> <img style="height: 120px; width: 101px;" src="img" alt="some alt"> </td> <td> <h2>heading</h2> <h3>subhead</h3> </td> </tr> <table> </div> <div id="menubar">

i've included opening of next div.

if seek , style h2 , h3 within of div, of h2 , h3 tags on page affected. here's css:

#header h2 { font-size: 24pt; font-weight: 900; color: #776f65; letter-spacing: 0; line-height: 0; } #header h3 { font-weight: 900; color: #776f65; letter-spacing: 0; padding-left: 35px; }

and finally, here's php code utilize generate html output:

echo('<div id="header">'); // header element begins here while($row = mysql_fetch_array($getheaderelements)) { echo($row['content']); } echo('</div>'); // end header element.

the browser i'm using google chrome.

does know why unusual behavior occurring?

regards, ben.

the "end" tag <table> start tag table.

this error cause of problem.

validate markup, it's inexpensive way pick sort of error.

css html styling

combinatorics - Find vector elements that sum up to specific number in MATLAB -



combinatorics - Find vector elements that sum up to specific number in MATLAB -

let consider have vector vec.

is ther way find vector elements can grouped sum given number num in matlab?

for illustration if vec = [2 5 7 10] , num = 17

the requested algorithm should provide reply subvectors [2 5 10] , [7 10] sum given num.

here way solve using conbntns, function mapping toolbox retrieves possible combinations of set of values (if don't have toolbox, can utilize combinator fex). so, vector a, example, we'll find possible combination of given length (1 length of a) sum them , see equal num=17:

num=17; a=[2 5 7 10]; ii=1:numel(a) b=combntns(a,ii); c=sum(b,2); d=find(c==num); if ~isempty(d) b(d,:) end end ans = 7 10 ans = 2 5 10

of course of study can store b(d,:) output cell array or whatever future use...

matlab combinatorics

sql - Efficient time series querying in Postgres -



sql - Efficient time series querying in Postgres -

i have table in pg db looks this:

id | widget_id | for_date | score |

each referenced widget has lot of these items. it's 1 per day per widget, there gaps.

what want result contains widgets each date since x. dates brought in via generate series:

select date.date::date generate_series('2012-01-01'::timestamp time zone,'now'::text::date::timestamp time zone, '1 day') date(date) order date.date desc;

if there no entry date given widget_id, want utilize previous one. widget 1337 doesn't have entry on 2012-05-10, on 2012-05-08, want resultset show 2012-05-08 entry on 2012-05-10 well:

actual data: widget_id | for_date | score 1312 | 2012-05-07 | 20 1337 | 2012-05-07 | 12 1337 | 2012-05-08 | 41 1337 | 2012-05-11 | 500 desired output based on generate series: widget_id | for_date | score 1336 | 2012-05-07 | 20 1337 | 2012-05-07 | 12 1336 | 2012-05-08 | 20 1337 | 2012-05-08 | 41 1336 | 2012-05-09 | 20 1337 | 2012-05-09 | 41 1336 | 2012-05-10 | 20 1337 | 2012-05-10 | 41 1336 | 2012-05-11 | 20 1337 | 2012-05-11 | 500

eventually want boil downwards view have consistent info sets per day can query easily.

edit: made sample info , expected resultset clearer

sql fiddle

select widget_id, for_date, case when score not null score else first_value(score) on (partition widget_id, c order for_date) end score ( select a.widget_id, a.for_date, s.score, count(score) over(partition a.widget_id order a.for_date) c ( select widget_id, g.d::date for_date ( select distinct widget_id score ) s cross bring together generate_series( (select min(for_date) score), (select max(for_date) score), '1 day' ) g(d) ) left bring together score s on a.widget_id = s.widget_id , a.for_date = s.for_date ) s order widget_id, for_date

sql postgresql

delphi - Attaching an object to an already existing ListItem? -



delphi - Attaching an object to an already existing ListItem? -

in listview, how can attach object @ time existing listitem? (i know can attach object listitem additem, need attach object after listitem has been created).

you can access through tlistitem.data property. example:

var listitem: tlistitem; begin listview1.additem('item 1', nil); ... listitem := listview1.items[0]; listitem.data := edit1; tedit(listitem.data).text := 'updated text...'; end;

delphi listview object delphi-xe2 listitem

sql - CF10 concatenated mysql string as binary data -



sql - CF10 concatenated mysql string as binary data -

i'm working on moving site cf8 cf10 , came across wasn't expecting. mysql query has simple concatenate combine company id company name such:

select concat(co_coid, ' - ',co_company) idconame

on cf8, returns string can display value on cfselect.

998 - company 999 - company b

etc.

however, on cf10 when dump query it's showing binary info , have utilize tostring() on output.

i knew there gotchas required using tostring() when returning encrypted info weren't there before, i'm not sure why it's doing on simple string concatenation.

[update] can changed through connect string or other server wide setting? know can utilize tostring() on output, or cast() in query, server wide ideal. mysql server same server, there's no version alter there.

convert number string,

select concat(cast(co_coid char(15)), ' - ',co_company) idconame

mysql sql coldfusion coldfusion-10

wcf - Must use exact identifier for APP object with verb SET -



wcf - Must use exact identifier for APP object with verb SET -

i'm next this article on allowing wcf read info msmq getting error command

appcmd set app "msmq/msmqservice" /enabledprotocols:net.msmq

msmq name of iis hosted website , msmqservice name of .svc file.

the error

error ( message:must utilize exact identifer app object verb set. )

here site looks in iis

@sachin, trying perform running command set net.msmq in enabled protocols of virtual directory. in specific command msmqservice name of vdir under web site msmq. if create vdir name msmqservice , execute command command succeed (not svc file name). , svc files should have .svc extension iis able invoke appropriate handlers when request arrives.

alternatively can same thing in iis ui next these instructions:

inetmgr run prompt go web site msmq navigate vdir msmqservice. right click -> manage application -> "advanced settings..." notice setting named "enabled protocols". type in net.msmq there. nail ok.

wcf msmq

jquery - Browser local storage get and set json objects issue -



jquery - Browser local storage get and set json objects issue -

im receiving webservice string has json format. using jquery.parsejson im creating json object on client side (and can access without issues).

after utilize localstorage.setitem add together json object browser local storage. issue comes when localstorage.getitem , [object object] , dont know how access object json object anymore.

do know whats cause , solution this?

thanks

jose.

you can stringify object before storing it, , later parse when retrieve it:

var testobject = { 'one': 1, 'two': 2, 'three': 3 }; // set object storage localstorage.setitem('testobject', json.stringify(testobject)); //retrieve object , parse 1 time again var retrievedobject = json.parse(localstorage.getitem('testobject'));

jquery json

Android LinearLayout set layout_gravity in java code -



Android LinearLayout set layout_gravity in java code -

i have problem on layout :(

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/cuerpo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:orientation="vertical" > ...

in java code

linearlayout cuerpo = (linearlayout) findviewbyid(r.id.cuerpo); if(align){ cuerpo.setgravity(gravity.center_vertical); }else{ cuerpo.setgravity(gravity.no_gravity); }

i need layout_gravity no gravity.

the layout gravity talking within layoutparams of of linearlayout object. so, logically, have follow next steps:

get layoutparams of linearlayout.

if know layoutparams supposed be, can cast them (beware, based on your choice, must create sure correct!).

set gravity of layoutparams desire.

so in code be:

viewgroup.layoutparams layoutparams = cuerpo.getlayoutparams(); // step 1. linearlayout.layoutparams castlayoutparams = (linearlayout.layoutparams) layoutparams; // step 2. castlayoutparams.gravity = gravity.center_vertical; // step 3.

or simple 1 liner steps in one:

((linearlayout.layoutparams) cuerpo.getlayoutparams()).gravity = gravity.center_vertical;

please beware:

i cannot see trying do, not seem correct. type of layoutparams not type of view, type of layout view reside in.

(i.e. in @gincsait's reference, if have button in linearlayout, layoutparams of button of type linearlayout.layoutparams. same cannot said layoutparams of linearlayout.)

java android layout layout-gravity

javascript - Is it possible to have event-based communication between browser windows? -



javascript - Is it possible to have event-based communication between browser windows? -

is possible have event-based communication between browser tabs/windows?

i known (at to the lowest degree theoretically) possible using local storage. please provide little illustration of code doing that? send event in 1 tab, , receive in another.

are there libraries/jquery-plugins that?

(i know can communicate between windows/tabs of same browser using cookies; not need; prefer event-based approach, don't want recheck state of cookies every millisecond).

localstorage has events can subscribe syncronize other pages.

note: if update key's value in window a, event not triggered in window a. triggered in windows b & c.

here demo: http://html5demos.com/storage-events

open page in several tabs. alter value on input , see reflected in divs.

here code javascript:

var datainput = document.getelementbyid('data'), output = document.getelementbyid('fromevent'); // handle updates storage-event-test key in other windows addevent(window, 'storage', function (event) { if (event.key == 'storage-event-test') { output.innerhtml = event.newvalue; } }); // update storage-event-test key when value on input changed addevent(datainput, 'keyup', function () { localstorage.setitem('storage-event-test', this.value); });

markup:

<div> <p>your test data: <input type="text" name="data" value="" placeholder="change me" id="data" /> <small>(this echoed on <em>other</em> windows)</small></p> <p id="fromevent">waiting info via <code>storage</code> event...</p> </div>

the html 5 spec discusses info passed in event:

[constructor(domstring type, optional storageeventinit eventinitdict)] interface storageevent : event { readonly attribute domstring key; readonly attribute domstring? oldvalue; readonly attribute domstring? newvalue; readonly attribute domstring url; readonly attribute storage? storagearea; }; dictionary storageeventinit : eventinit { domstring key; domstring? oldvalue; domstring? newvalue; domstring url; storage? storagearea; };

from: http://www.w3.org/tr/webstorage/#the-storage-event

using event, can create other pages react when specific key in local storage updated.

javascript jquery local-storage

deployment - Python fabric with EC2 instance -



deployment - Python fabric with EC2 instance -

i working on setting auto deployment script using python fabric on ec2 instance. having code repositories cloned on ec2 instance https (without user name,https://bitbucket.org/) instead of ssh.

if clone repositories using ssh, solve problem now. but, wanted know if next possible:-

after connecting remote ec2 instance using fabric, if next command hg clone, asks user name , password. have type 2 things manually on command prompt. there way can pass these values run time automatically?

thanks!

you can utilize ssh keys , connect using ssh+hg protocol. it'll auth w/o password if set up.

deployment amazon-ec2 fabric

logging - Stratergies to collect analytics and error in windows 8 metro app -



logging - Stratergies to collect analytics and error in windows 8 metro app -

i have build metro app using javascript, have written around 6000 lines of codes.

i ooking ways collect 2 things

what users doing, user action analytics error users may facing, collecting log file or other strategy.

what available options , available strategies that.

i using cloud connection easy see usage in centralized location. create collection of log messages, analytic points, errors, etc. in users local storage , fire off asynchronous service @ application launch (and perhaps every few min thereafter) made sure user connected internet, , force records local storage azure mobile service. if haven't set azure mobile services before, they're super easy, cheap, , handy. can create table store info points , add together property user's receipt id (that uniquely identifies them , machine). you've got 1 table usage info of users. that's $0.02.

logging error-handling microsoft-metro analytics winjs

Preventing of maven update in Spring Roo replaces all the file in AspectJ files ? -



Preventing of maven update in Spring Roo replaces all the file in AspectJ files ? -

when maven update in spring roo replace file in aspectj files. how prevent it?

i want write code in controller file , not want replace code after maven update.

are modifying xyzcontroller.java oder xyzcontroller_roo_controller.aj? updating .aj files cause grief roo. normally, you'd re-create methods want update xyzcontroller.java , alter them there. after next refresh, roo won't create method in .aj file more changes won't disappear.

maven spring-roo

c# - How do I write a method that can take either a DataGridView or a ListView as input? -



c# - How do I write a method that can take either a DataGridView or a ListView as input? -

i using next 2 methods persist column info datagridview , listview.

i notice methods similar , in fact utilize same info construction store column settings in. properties storing each column things like, visible, width, displayindex

how can re-write have single function can handle datagridview or listview?

i have thought investigating whether both datagridview , listview inherit mutual class or implement mutual interface - not sure how find out.

also have thought extending each class implement mutual interface... not sure how proceed.

public void savedatagridview ( datagridview view) { foreach (datagridviewcolumn col in view.columns) { // save properties } } public void savedatalistview(listview view) { foreach (columnheader col in view.columns) { // save properties } }

no way until utilize dynamic keyword not increment performance.

datagridview.columns , listview.columns have no mutual base of operations type (except ilist, seek uncertainty luck). neither columnheader , datagridviewcolumn have too.

c# .net winforms listview datagridview

indexing - COBOL expression as index in table array -



indexing - COBOL expression as index in table array -

just short quick question. how index look cobol array? example, if index k=1, next find element of k=2

element(k+1)

unfortunately not acceptable in cobol , know if there alternative?

i'm not sure why think won't work, long set in cobol statement.

id division. program-id. submod. info division. working-storage section. 01 a-nicely-named-table. 05 filler occurs 2 times. 10 a-nicely-named-entry pic x. 01 another-piece-of-data pic x value space. 01 a-nicely-named-subscript binary pic 9(4). linkage section. 01 l-input pic x(4). 01 l-to-hex pic bxbxbxbx. procedure partition using l-input l-to-hex. move "a" a-nicely-named-entry ( 1 ) move "b" a-nicely-named-entry ( 2 ) move 1 a-nicely-named-subscript if a-nicely-named-entry ( a-nicely-named-subscript + 1 ) equal "b" move a-nicely-named-entry ( a-nicely-named-subscript + 1 ) another-piece-of-data end-if display ">" another-piece-of-data "<" goback .

output is:

>b<

with reference comment, not "strictness" thing means. "+ 1" 1 thing, "relative subscript", , "+1" else, sec subscript.

depending on compiler, may able code:

move element(k++1) ...

you may have set moaning compiler, , suppose in may not work. would, however, horrible way write cobol.

i'd suggest not using names element. @ point in future appear "reserved word" cobol. don't shorthand. utilize names, utilize effective spacings. it'll help understand programme little later, , help else has @ it.

arrays indexing cobol

php - Codeigniter: getting a user name with id -



php - Codeigniter: getting a user name with id -

i've got project i'm working on in, user can register , assigned id. user has ability post blogs or comment, these blogs or comments assigned authorid same users userid.

i need way name posted below these blogs or messages instead of id-which does.

my blog controller handles blog posting (commenting similar) exception of add together blog function:

function blogtoevoegen() { $this->form_validation->set_rules('blogtitel', 'blogtitel', 'min_length[3]|required|xss_clean|callback_username_check'); $this->form_validation->set_rules('blogtekst', 'blogtekst', 'min_length[2]|required|xss_clean'); if ($this->form_validation->run() == false) { $this->load->view('view_page', $this->view_data); } else { $data = array( 'id' => $this->input->post('id'), 'blogtitel' => $this->input->post('blogtitel'), 'blogtekst' => $this->input->post('blogtekst'), 'auteur_id' => $this->session->userdata('gebruiker_id'), ); $this->db->set('datum', 'now()', false); $this->db->insert('blogs', $data); redirect('blog/eigenblogs'); } }

a function handles displaying of blog post (it gets comments linked blog)

function comments() { $this->db->where('id', $this->uri->segment(3)); $this->db->select('blogtitel, blogtekst, auteur_id, datum'); $data['query2'] = $this->db->get('blogs'); $this->db->where('boodschap_id', $this->uri->segment(3)); $data['query'] = $this->db->get('comments'); $data ["titel"] = "pxl - comment"; $data ["pagina"] = "content_comment"; $this->load->view("view_page", $data); }

the view code displays these blogs (left code comments out)

<?php foreach ($query2->result() $rij): ?> <div class="post"> <h2><?= $rij->blogtitel ?></h2> <p><?= $rij->blogtekst ?></p> <p class="meta">posted <a href="#"><?= $rij->auteur_id ?></a> on <?= $rij->datum ?> </p> </div> <?php endforeach; ?> <hr>

i need way alter auteur_id name (made out of combination first + lastly name).

what need here called sql join. find more in ci manual:

here illustration of need:

$this->db->select('*'); $this->db->from('blogs'); $this->db->join('users', 'users.id = blogs.author_id'); $query = $this->db->get();

this blog posts , query user in users table based on author_id.

php database codeigniter

entity framework - WPF MVVM Light DataGrid and separate Add Item View -



entity framework - WPF MVVM Light DataGrid and separate Add Item View -

i learning wpf , mvvm , trying create programme has datagrid , button opens form using command can add together item datagrid.

the problem not sure how should implement viewmodels. have 1 viewmodel datagrid form works correctly , using repository retrieve info entity framework.

is possible add together object add together form , have appear in datagrid in other form automatically when press add together button or need refresh action on datagrid? using observable collections in viewmodel , have implemented onpropertychange functionality in collection parameter in view model.

as far can understand when set in repository, every view model gets info should refreshed... though not sure if should write message code work.

i pretty confused , hope can shed lite here... in advance. tell me if have missed mention , add together it:)

edit: how register models:

simpleioc.default.register<parentslistviewmodel>(); simpleioc.default.register<editparentviewmodel>();

and how register repository:

simpleioc.default.register<iparentsrepository, parentsrepository>();

and how retrieve instances of viewmodels:

parentslistviewmodel parentslistviewmodelinstance = servicelocator.current.getinstance<parentslistviewmodel>(); editparentviewmodel editparentviewmodelinstance = servicelocator.current.getinstance<editparentviewmodel>();

the parentslistviewmodel datagrid viewmodel , editparentviewmodel 1 utilize adding/editing records in repository. service locator passes instances of repositories automaticaly have no thought how passes instance of repository viewmodels. pass same instance?

the view models wont automatically refresh when add together repository.

all observable collection inform ui when new item added / removed observable collection (roughly speaking). inotifypropertychange inform ui specific property has changed.

you have few options getting want work (if understand correctly):

you refresh entire observable collection when item added you repository inform datagrid view model event when new item added - datagrid view model can update observable collection you add together form view model talk info grid view model , tell when new item added - in situation you'll need mechanism marshaling info 1 view model another.

does help?

edit 12/02/2013 17:30 gmt:

here's quick , dirty illustration of alternative 2 like. requires same instance of repository shared between 2 view models - in case have injected on constructors.

public interface iparentsrepository{ event eventhandler<myitemaddedeventargs> itemadded; //your normal interface implementation here } public class parentsrepository : iparentsrepository { public event eventhandler<myitemaddedeventargs> itemadded; public list<myitem> getallitems() { //logic returns items here homecoming new list<myitem>(); } public void additem(myitem item) { //logic adds item here //fire item added event onitemadded(item); } private void onitemadded(myitem item) { if(itemadded != null) itemadded(this, new myitemaddedeventargs(item)); } } public class myitemaddedeventargs : eventargs { public myitemaddedeventargs(myitem itemadded) { } public myitem itemadded { get; set; } } public class myitem { public string someproperty { get; set; } } public class mydatagridviewmodel { private readonly iparentsrepository _parentsrepository; public mydatagridviewmodel(iparentsrepository parentsrepository) { _parentsrepository = parentsrepository; _parentsrepository.itemadded += _parentsrepository_itemadded; var myitems = _parentsrepository.getallitems(); myitems = new observablecollection<myitem>(myitems); } void _parentsrepository_itemadded(object sender, myitemaddedeventargs e) { if(!myitems.contains(e.itemadded)) myitems.add(e.itemadded); } public observablecollection<myitem> myitems { get; set; } } public class myadditemviewmodel { private readonly iparentsrepository _parentsrepository; public myadditemviewmodel(iparentsrepository parentsrepository) { _parentsrepository = parentsrepository; } //your logic add together item here }

this method adjusted method 1, when _parentsrepository_itemadded event fires, rather adding new item, fetch whole dataset again.

wpf entity-framework mvvm datagrid mvvm-light

grails - gsp mail plugin autosending -



grails - gsp mail plugin autosending -

when navigate page, why send() function beingness called automatically?

i want able view gsp page, fill in few text fields, , phone call submit action of "send"

this gsp file

<%@ page contenttype="text/html;charset=utf-8" %> <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"/> <meta name="layout" content="main"/> <title>contact form</title> </head> <body> <g:form name="contactform" action = "send"> <g:render template = "contactformfields"/> <g:actionsubmit value = "submit" action = "send"/> </g:form> </body> </html>

this contactformfields template

<g:select name = 'subject' = '${emailservice.options}' noselection='topic'/> contact name: <g:textfield name = "contact"/> contact number: <g:textfield name = "phone"/> contact email: <g:textfield name = "email"/> aditional information: <g:textarea name = "information" rows="5" cols="40"/>

emailservicecontroller

class emailservicecontroller { def defaultaction = "contactservice" def send() { sendmail(){ "mygroovytest@gmail.com" params.email subject params.subject body params.information } } }

domain class

class emailservice { static constraints = { def options = new arraylist() options.push("qestions service") options.push("feedback on performed service") options.push("other") options.push("why doing this") } }

gsp calls service

<div class="banner"> <h1>my hvac company</h1> <a href = "javascript: contactpop()"> contact me today!</a> <a href = "services">services</a> <a href = "emailservice">have me contact you!</a> </div>

you don't have contactservice action in emailservicecontroller it's treating send() default action when link controller no action name. seek adding empty contactservice action

def contactservice() { }

grails controller grails-plugin gsp

android - ImageButton with different states images size -



android - ImageButton with different states images size -

how can prevent imagebutton having fixed size? drawables used in selector have different size, , want imagebutton resize match image size.

i've tried adjustviewbounds without success.

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp" > <imagebutton android:id="@+id/picture_imagebutton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:adjustviewbounds="true" android:src="@drawable/tab_background_selector" /> </relativelayout>

instead of using imagebutton, utilize imageview because imagebutton cannot resized based on imagesize. imageview best alternative way can suggest problem. acheive next way:

layout.xml:

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <imageview android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/image_selection"/> </relativelayout>

image_selection.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/default_image"/> //default_image.png displayed when activity loads. <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/default_image_hover" /> //default_image_hover.png image displaed during onclick of imageview <item android:state_focused="true" android:drawable="@drawable/default_image_hover" /> <item android:state_focused="false" android:drawable="@drawable/default_image"/> </selector>

sampleactivity.java:

imageview myimage= (imageview)findviewbyid(r.id.image); myimage.setonclicklistener(this);

android android-layout imagebutton

Qt Window with transparent background image -



Qt Window with transparent background image -

i placed background image this:

setwindowflags(qt::framelesswindowhint); qpixmap slika("some_image.png"); qpalette paleta; paleta.setbrush(this->backgroundrole(), qbrush(slika)); this->setpalette(paleta);

if create image transparent, when application loads, blink , disappear. if create image no transparency, ok. why qt refuses utilize transparent image?

i don't know utilize case this, can seek using setstylesheet method create background transparent.

setstylesheet("background:transparent;"); setattribute(qt::wa_translucentbackground); setwindowflags(qt::framelesswindowhint);

hope helps.

qt

ember.js - Blocked in displaying logins via connectOutlet in trek tutorial -



ember.js - Blocked in displaying logins via connectOutlet in trek tutorial -

i'm next tutorial here http://trek.github.com/ , i'm @ blocked point.

ember code in index.html:

<script type="text/x-handlebars" data-template-name="application"> <h2>ember committers:</h2> {{outlet}} </script> <script type="text/x-handlebars" data-template-name="contributors"> {{#each person in controller}} {{person.login}} {{/each}} </script>

ember code in app.js:

app = ember.application.create(); // application default controller , view app. applicationcontroller = ember.controller.extend(); app.applicationview= ember.view.extend( { templatename: 'application' }); // contributors controller , view... app. allcontributorscontroller = ember.arraycontroller.extend(); app.allcontributorsview= ember.view.extend( { templatename: 'contributors' }); app.router = ember.router.extend({ root: ember.route.extend({ index: ember.route.extend({ route: '/', connectoutlets: function(router) { // here connect allcontributers info & template outlet in application template. router.get('applicationcontroller').connectoutlet('allcontributors', [{login:'wycats'},{login: 'tomdale'}]); } }) }) });

at point when run it, expect see text "ember committers:" along 2 login names specified via connectoutlet().

i see header text , not logins , don't errors.

any ideas?

i've had success when i've done routes way on emberjs.com guide page http://emberjs.com/guides/routing/defining-your-routes/

you'd define routes via

app.router.map(function(){ this.route('contributors'); });

at point, default if go #/contributors set contributors template {{outlet}} (no view declaration necessary).

if need alter outlet, within route (not router! confusion cost me day) creating 1 contributors:

app.contributorsroute = ember.route.extend({ connectoutlets: ... });

ember.js

how to programmatically add colspan in ZK/Zul? -



how to programmatically add colspan in ZK/Zul? -

how set property of colspan in zul framework?

e.g.

tr tr = new tr(); td td = new td(); tr.appendchild(td); td = new td(); tr.appendchild(td);

now, in next row, have set single td within table row through composer cover space of 2 td . how can accomplish this?

<table> <tr> <td> </td/> <td> </td> </tr> <tr> <td colspan="2"> </td> </tr> </table>

in zul not done <table>, <tr>, , <td> tags <grid>, <row>, , <cell> tags. so..

<grid> <columns> <column label="a" /> <column label="b" /> </columns> <rows> <row> <cell> <label value="item 1" /> </cell> <cell> <label value="item 2" /> </cell> </row> <row> <cell colspan="2"> <label value="item 3" /> </cell> </row> </rows> </grid>

from java side, then, becomes easy..

grid grid = new grid(); rows rows = new rows(); rows.setparent(grid); row row1 = new row(); row1.setparent(rows); cell cell1 = new cell(); cell1.setparent(row1); cell1.appendchild(new label("item1")); cell cell2 = new cell(); cell2.setparent(row1); cell2.appendchild(new label("item2")); row row2 = new row(); row2.setparent(rows); cell cell3 = new cell(); cell3.setparent(row2); cell3.appendchild(new label("item3")); cell3.setcolspan(2); // you're looking

please refer (great) zk docs more information.

zk zul

c# - How can I determine if a console app was executed from within a batch file? -



c# - How can I determine if a console app was executed from within a batch file? -

i have console application in need observe whether or not executed command line, opposed within batch file. want protect

console.write ( "press key exit" ); console.readkey ( true ); console.writeline ( );

from executing when app executing within batch file.

you can crazy things (like parent process, see arguments got etc), if command app add together command line argument, phone call "batch mode" or whatever , when programme invoked create non-interactive.

c# batch-file

c# - Image magnification lagging -



c# - Image magnification lagging -

i created application allows user magnify part of background picture. main problem is, magnification field lagging can see on picture. , single threaded application. have suggestion can solve problem?

my code:

public void magnifier(point e) { magnifiedpicture.size = new size(magnifiersize, magnifiersize); magnifiedpicture.visible = true; magnifiedpicture.location = new point(e.x-magnifiersize/2, e.y-magnifiersize/2); magnifiedpicture.backgroundimage = cutthepicture(canvasimage, new rectangle(_ptoncanvas.x - 18, _ptoncanvas.y - 18, 16, 16)); magnifiedpicture.refresh(); // <-- probe, without effect }

i utilize invokepaint on mouse move event , problem solved.

invokepaint( this, new painteventargs( this.creategraphics(), this.displayrectangle ) );

c# lag magnification

knockout.js - javascript - knockout - how it works? -



knockout.js - javascript - knockout - how it works? -

i trying utilize knockout , wonder myself how works network point of view : can see "calls" browser client server retrieve data? mean : used utilize ajax calls populate forms, tables... => can see ajax calls server. same thing when need submit form : can see ajax calls. means can debug firefbug , see parameters sent/ response received, inluding headers (request/response). knocknout, info in form "binding" automatically framework ko. so, know how works really? how calls done? there way "see" info flow?

from network point of view, nil changes when using knockout. you'll still need create ajax calls populate view models, they're outside framework, not part of it. means can still set breakpoint on ajax calls , observe stuff beingness sent , received.

a major code departure network calls exist within knockout viewmodel.

var somevm = function(data) { var self = this; self.id = ko.observable(data.id); // ... self.getitems = function() { // ajax phone call here, method on vm } }

however, tj crowder points out - key mechanic of knockout binding client side view model user interface, either info population or visibility command in single page application. networking you'll have handle, it's not part of knockout. likely, you'll create little changes in placement of ajax calls.

javascript knockout.js

java - How to get a localized date format for EditText hint in android -



java - How to get a localized date format for EditText hint in android -

how localized date format edittext hint in android?

yyyy-mm-dd(en) aaaa-mm-dd(sp) aaaa-mm-jj(fr)

you can utilize dateformat.getdateformat(context), following:

returns dateformat object can format date in short form (such 12/31/1999) according current locale , user's date-order preference.

  -- dateformat documentation

then, pass object of type activity or context:

java.text.dateformat formatter = android.text.format.dateformat.getdateformat(context);

java android localization date-format

objective c - Zooming UIImage in a UIScrollView -



objective c - Zooming UIImage in a UIScrollView -

i have custom class implements uiscrollview.

i created 1 uiimageview , add together subview of uiscrollview. scrolls vertically , horizontally perfectly, seems ignoring zooming stuff. here code:

- (void) setupboard { // add together board uiimageview *imageholder = [[uiimageview alloc] initwithimage:[uiimage imagenamed:@"grid.jpg"]]; [self addsubview:imageholder]; self.contentsize = cgsizemake(imageholder.frame.size.width, imageholder.frame.size.height); self.indicatorstyle = uiscrollviewindicatorstylewhite; self.maximumzoomscale = 5.0; self.minimumzoomscale = 0.2; self.zoomscale = 0.7; self.clipstobounds = yes; }

how zoom using standard pinch gestures? help appreciated. thanks!

from uiscrollview class reference overview:

the uiscrollview class can have delegate must adopt uiscrollviewdelegate protocol. zooming , panning work, delegate must implement both viewforzoominginscrollview: , scrollviewdidendzooming:withview:atscale:; in addition, maximum (maximumzoomscale) , minimum (minimumzoomscale) zoom scale must different.

i suspect either haven't assigned delegate scroll view, or delegate doesn't implement both of methods.

objective-c uiscrollview

facebook graph api - iOS: Passing data between View Controllers -



facebook graph api - iOS: Passing data between View Controllers -

i'm using facebook api, , when user select place (checkin), want open view , pass place (fbgraphplace), in "secondviewcontroller" variable null when method "viewdidload" executed. when user select place:

if (secondviewcontroller == nil) { secondviewcontroller *secondviewcontroller = [[secondviewcontroller alloc] initwithnibname:nsstringfromclass([secondviewcontroller class]) bundle:[nsbundle mainbundle]]; self.secondviewcontroller = secondviewcontroller; } // how reference navigation controller // little different uibarbuttonitem *newbackbutton = [[uibarbuttonitem alloc] initwithtitle: @"back" style: uibarbuttonitemstylebordered target: nil action: nil]; [[self navigationitem] setbackbarbuttonitem: newbackbutton]; secondviewcontroller.place = self.selectedplace; [self.navigationcontroller pushviewcontroller:self.secondviewcontroller animated:yes];

you should pushviewcontroller first, assign place variable

ios facebook-graph-api uiviewcontroller

jquery - Make an async ajax request when clicking on a link -



jquery - Make an async ajax request when clicking on a link -

i'm using php/jquery , have next scenario:

i have site (site1.php) link, points site (site2.php), added link ajax-onclick-event jquery requests site (ajaxcall.php). other site has "a lot of work" do, it's not short request.

my goal is: set request ajaxcall.php in background (asynchron) , go site2.php. (i not need reply of ajaxcall.php)

my first implementation this:

<!doctype html> <html> <head> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#link").on("click",function(){ $.get('./ajaxcall.php'); </script> </head> <body> <a href="./file2.php" id="link">link</a> </body> </html>

obviously won't work. because ajax-request (which async), aborted page changed.

so far can see have 2 possiblities here:

make request synchron & show loading indicator ($.ajax({url: './ajaxcall.php',async:false});) --> disadvantage: file2.php not open before ajaxcall.php done.

open popup (window.open('ajaxcall.php')) , create synchron-ajax-request / or similar there , auto-close after --> advantage: file2.php should open --> (big)disadvantage: popup

??? improve way ???

i hope understood i'm trying accomplish , can help me :)

try code...

$(document).ready(function() { $("#link").on("click",function(e){ e.preventdefault(); var href = this.href; $.get('./ajaxcall.php', function() { window.location.href = href; }); }); });

it stops execution of link (with e.preventdefault()), gets target url , redirects page location when request complete.

jquery ajax asynchronous

Wireless exchange between Arduino and Raspberry Pi: choice of protocol -



Wireless exchange between Arduino and Raspberry Pi: choice of protocol -

hello oh mighty stackoverflow.com community.

this question i've been fiddling while now. have (will have) arduino 2560 talking rpi using pair of 388 rf transmitter/receiver - serial communication. create matters worse, there many transmitters (arduinos) , single reciever (rpi). 2 questions cannot quite figure reply for:

protocol extremely primitive - if want error correction, have take myself. thought utilize extremely simple parity bit start , see how goes. thoughts?

speaking of protocol - how going encode data? there single number going transmit - transmitter id - accompanied boolean flag (sensor active/inactive). best way encode info serial rf transmission? text? can transmit stream of bytes, much be, create farther porting hard (big/little endian, word size, etc). tried consider exotics such nanopb no matter how protocol buffers great overkill task. understand position wobbly here, i'd appreciate ideas.

finally, know sounds lame i'm pretty sure has done before , there might sort of cross-platform library can utilize exchange. if indeed so, great - can want instead of re-inventing wheel.

anyway, here's stand. appreciate answers.

this transmitter i'm using , receiver.

thanks lot everyone!

have looked @ arduino virtual wire library – http://www.pjrc.com/teensy/td_libs_virtualwire.html. works fine transmitters , receivers on arduino , should not hard port raspberry pi. there forum give-and-take @ http://www.raspberrypi.org/phpbb3/viewtopic.php?t=24215&p=239410.

arduino protocols wireless raspberry-pi error-correction

OpenCV in python. Getting webcam stream works, but error message is printed -



OpenCV in python. Getting webcam stream works, but error message is printed -

i writing in need webcam stream , face detection on it. works fine, error message printed in terminal, despite of me using cv.capturefromcam(-1) detects photographic camera connected machine. tried using cv2 instead of cv, , same error:

vidioc_querymenu: invalid argument vidioc_querymenu: invalid argument vidioc_querymenu: invalid argument vidioc_querymenu: invalid argument vidioc_querymenu: invalid argument vidioc_querymenu: invalid argument vidioc_querymenu: invalid argument

note code running cv.capturefromcam(-1).oh , using python 2.7.

import cv cv.capturefromcam(-1)

can tell me how prepare this? thanks.

i ran same error messages. in case not fatal indication python using v4l2 probe parameters happen invalid photographic camera / os combination.

in case

>>> cap = cv2.videocapture(0) vidioc_querymenu: invalid argument vidioc_querymenu: invalid argument vidioc_querymenu: invalid argument ...

but

ret, frame = cap.read()

gives ret=true , numby image frame.

in case video photographic camera logitech, inc. hd webcam c910. , running angstrom on beagleboneblack.

python opencv webcam

php - Normalize merchant weights based on long term performance (mysql data) -



php - Normalize merchant weights based on long term performance (mysql data) -

i have database of retail merchants. each record has following:

id | merchant | clicks | sales | conversion rate | epc

the problem have in situations new merchant has 2 clicks , 1 sale gives new retailer 50% conversion rate , high epc, "better" merchant has 200,000 clicks , 40,000 sales. looking way come number between 0 , 2 or 1 , 2 can computed based on above info , used give more weight retailers improve long term performance (higher number of clicks , sales). sql query based on info given ideal, can in php.

let me provide actual numbers. next info sorted number of sales , accurately shows our top merchants. there still few problems ordering since can see click nordstrom worth twice of click zappos.

merchant |clicks |sales|conversion|epc 6pm |982903 |21846|2.22 |0.10 zappos.com |1594711|13741|0.86 |0.09 nordstrom.com|564169 |12028|2.13 |0.18 shopbop.com |249714 |3910 |1.57 |0.16

php mysql statistics

java - What's the most effective way to execute a task some distant time in the future on App Engine? -



java - What's the most effective way to execute a task some distant time in the future on App Engine? -

i have application on app engine consuming data. after parsing data, know needs execute in period of time - perchance not number of hours or weeks.

what best way execute piece of code after arbitrary amount of time on app engine?

i figured using countdown millis or etamillis taskqueue work, haven't seen evidence of doing same thing, such long time frames.

is best approach, or there improve way?

if able persist object in datastore of relevant info future processing (including when processing object's info should begin), have cron job periodically query datastore date/time range filter , trigger processing of above objects @ appropriate time.

java google-app-engine scheduled-tasks scheduling

html - Which way to load a huge image (canvas vs img vs background-image)? -



html - Which way to load a huge image (canvas vs img vs background-image)? -

what want

currently have png image of 4000x4000. after using tinypng.org became 288kb file.

now want fastes way load image, place in dom , able draw lot of canvas' on it.

i tested , results stunned me.

what tested

i made 3 tests , check load speed.

(423ms) <canvas> (138ms) <img> (501ms) css background-image

the <img> tag fastest.

question

so, bad-practice utilize <img> tag display huge (background) image , utilize dirty css able draw canvas on it?

or improve utilize canvas in case , don't worry longer load time?

great question! related: when utilize img vs. css background-image?

from article, if people intended print page wouldn't utilize <img> - appear on print. same apply <canvas>, making background-image logical solution.

how background image added through css? inline or through own stylesheet? if it's using own stylesheet, have tried compressing css before testing speed?

this related, suppose: do images load faster in html or css?

html css html5 canvas image

c# - How to extract the filename from a request url using Regex in ASP.NET -



c# - How to extract the filename from a request url using Regex in ASP.NET -

i need extract filename + extension request having .aspx extension within request url. ex. if requested url - http://www.abcd.com/index.aspx?a=1&b=2 should homecoming index.aspx. if requested url http://abcd.com/products/pages/page1 should homecoming empty.if requested url http://abcd.com/images/img1.gif should homecoming empty.

edit: if there aspx anywhere else in url might pose actual problem. escaping . , looking . within url, , getting first match might solve problem hostname's dont have .aspx in them.

try this:

match filenamematch = regex.match("url", @"\w+\.aspx"); string filename = filenamematch.value;

c# asp.net regex

html - Not working- incremental in input text's value in javascript on pageload -



html - Not working- incremental in input text's value in javascript on pageload -

i want increment input text's value on page load in javascript code-

<input id="myid" type="text" name="itemquantity[]" value="1"/> <script> localstorage['myid'] = document.getelementbyid('myid').value = parseint(localstorage['myid'] || '0', 10) + 1; </script>

code working fine have error when set code in javascript actual page

$('#left_bar .cart-info').append('<div class="shopp" id="each-'+thisid+'"> <div class="label">'+itemname+'<input type="hidden" name="itemname[]" value="'+itemname+'"/><input type="hidden" name="itemprice[]" value="'+itemprice+'"/>'+(localstorage["myid"] =document.getelementbyid("myid").value =parseint(localstorage["myid"] || "0", 10) + 1;)+'<input id="myid" type="text" name="itemquantity[]" value="1"/></div><div class="shopp-price">$<em>'+itemprice+'</em></div> <span class="shopp-quantity">1</span><img src="images/remove.png" class="remove" /><br class="all" /></div>');

suggest solutions.

thankyou

javascript html

android - Conversion to Dalvik format Failed facebook/AccessToken$SerializationProxyV1; -



android - Conversion to Dalvik format Failed facebook/AccessToken$SerializationProxyV1; -

[2013-02-09 19:48:50 - dex loader] unable execute dex: multiple dex files define lcom/facebook/accesstoken$serializationproxyv1; [2013-02-09 19:48:50 - mainactivity] conversion dalvik format failed: unable execute dex: multiple dex files define lcom/facebook/accesstoken$serializationproxyv1;

i tried

clean project delete libs folder restart eclipse remove android-support-v4.jar

but none of them resolve problem.

any help appreciated!!

well, depends if build facebook sdk only, or you've included library own android project (i suppose that's case). if have jar's within project folder (added jars project), remove them , re-create them somewhere outside project root, add together them 1 time again external jars. question might possible duplicate.

android android-library

Base_Controller: Access current controller name in Laravel -



Base_Controller: Access current controller name in Laravel -

i trying current controller name in base of operations controller in laravel 3.2 returns null. within home controller there's no problem.

how can value within base_controller?

<?php class base_controller extends controller { public $page_data = array(); public function __call($method, $parameters) { homecoming response::error('404'); } public function __construct() { $this->page_data['body_id'] = request::$route->controller; parent::__construct(); } }

why don't utilize get_called_class() if have php 5.3 available can controllers class name? workaround though , not looking for...

controller laravel laravel-3

r - How the change line width in ggplot? -



r - How the change line width in ggplot? -

datalink: the info used

my code:

ccfsisims <- read.csv(file = "f:/purdue university/ra_position/phd_researchanddissert/phd_draft/gtap-cge/gtap_newaggdatabase/newfiles/gtap_consindex.csv", header=true, sep=",", na.string="na", dec=".", strip.white=true) ccfsirsts <- as.data.frame(ccfsisims) ccfsirsts[6:24] <- sapply(ccfsirsts[6:24],as.numeric) ccfsirsts <- droplevels(ccfsirsts) ccfsirsts <- transform(ccfsirsts,sres=factor(sres,levels=unique(sres))) library(ggplot2) #------------------------------------------------------------------------------------------ #### plot of nutrient security index kingdom of morocco , turkey sector #------------------------------------------------------------------------------------------ #_code_begin... datamortur <- melt(ccfsirsts[ccfsirsts$region %in% c("tur","mar"), ]) # selecting regions of involvement datamortur1 <- datamortur[datamortur$variable %in% c("pfsi2"), ] # selecting nutrient security index of involvement datamortur2 <- datamortur1[datamortur1$sector %in% c("wht","gro","vegtfrut","osd","othcrop","vegtoil","xprfood"), ] # selecting nutrient sectors of involvement datamortur3 <- subset(datamortur2, tradlib !="basedata") # eliminating "basedata" scenario results allfsi.f <- datamortur3 fsi.wht <- allfsi.f[allfsi.f$sector %in% c("wht"), ] figure29 <- ggplot(data=fsi.wht, aes(x=factor(sres),y=value,colour=factor(tradlib))) figure29 + geom_line(aes(group=factor(tradlib),size=2)) + facet_grid(regionsfull~., scales="free_y", labeller=reg_labeller) + scale_colour_brewer(type = "div") + theme(axis.text.x = element_text(colour = 'black', angle = 90, size = 13, hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) + ylab("fsi (%change)") + theme(axis.text.y = element_text(colour = 'black', size = 12), axis.title.y = element_text(size = 12, hjust = 0.5, vjust = 0.2)) + theme(strip.text.y = element_text(size = 11, hjust = 0.5, vjust = 0.5, face = 'bold'))

my result:

newresult aes(size=2):

my question: there way command line width more exactly avoid result in sec plot? particularly find document-unfriendly, , more publishing purposes include plot newly defined line width.

best, ismail

whilst @didzis has correct answer, expand on few points

aesthetics can set or mapped within ggplot call.

an aesthetic defined within aes(...) mapped data, , legend created.

an aesthetic may set single value, defining outside aes().

as far can tell, want set size single value, not map within phone call aes()

when phone call aes(size = 2) creates variable called `2` , uses create size, mapping constant value within phone call aes (thus appears in legend).

using size = 1 (and without reg_labeller perhaps defined somewhere in script)

figure29 + geom_line(aes(group=factor(tradlib)),size=1) + facet_grid(regionsfull~., scales="free_y") + scale_colour_brewer(type = "div") + theme(axis.text.x = element_text(colour = 'black', angle = 90, size = 13, hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) + ylab("fsi (%change)") + theme(axis.text.y = element_text(colour = 'black', size = 12), axis.title.y = element_text(size = 12, hjust = 0.5, vjust = 0.2)) + theme(strip.text.y = element_text(size = 11, hjust = 0.5, vjust = 0.5, face = 'bold'))

and size = 2

figure29 + geom_line(aes(group=factor(tradlib)),size=2) + facet_grid(regionsfull~., scales="free_y") + scale_colour_brewer(type = "div") + theme(axis.text.x = element_text(colour = 'black', angle = 90, size = 13, hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) + ylab("fsi (%change)") + theme(axis.text.y = element_text(colour = 'black', size = 12), axis.title.y = element_text(size = 12, hjust = 0.5, vjust = 0.2)) + theme(strip.text.y = element_text(size = 11, hjust = 0.5, vjust = 0.5, face = 'bold'))

you can define size work appropriately final image size , device type.

r ggplot2 line-plot

java - Displaying keypress count in JTextField or Jbutton -



java - Displaying keypress count in JTextField or Jbutton -

i'm having problem displaying amount of times key has been pressed , display number in jtextfield or jbutton. give me hand that?

i have keyevent.vk_numpad3 displayed, seems keyevent.vk_2 having such problem with:

i can display number doesn't update each time key pressed.

here total code.. bit big asked it.. :)

public class display extends jframe{ public static final int canvas_width = 1000; public static final int canvas_height = 450; public static final color line_color = color.black; public static final color ground_color = color.green; public static final color canvas_background = color.cyan; public static final int trans = color.opaque; private int x1 = canvas_width / 2; private int y1 = canvas_height / 2; private int x2 = canvas_width /2; private int y2 = canvas_height / 2; private int sx1 = canvas_width ; private int sy1 = canvas_height ; private int sy2 = canvas_height ; private int rx1 = canvas_width - canvas_width; private int ry1 = canvas_height; private int rx2 = canvas_width; private int ry2 = canvas_height ; private int lx1 = canvas_width / 2; private int ly1 = canvas_height / 2; private int lx2 = canvas_width / 2; private int ly2 = canvas_height / 2; private int mx1 = canvas_width / 2; private int my1 = canvas_height / 2; private int mx2 = canvas_width / 2; private int my2 = canvas_height / 2; int[] xs = {380, 460, 460, 540, 540, 620, 500, 380}; int[] ys = {260, 260, 250, 250, 260, 260, 205, 260}; private drawcanvas canvas; private jtextfield altitude; private jtextfield taspeed; private jlabel altbutton; private int counta = 0; private int counts = 0; private int bcount1 = 0; public string ccount = integer.tostring(bcount1); public class countupaltitude extends abstractaction { /** constructor */ public countupaltitude(string name, string shortdesc, integer mnemonic) { super(name); putvalue(short_description, shortdesc); putvalue(mnemonic_key, keyevent.vk_3); bcount1 += 1; } //right @override public void actionperformed(actionevent e) { addkeylistener(new keyadapter() { public void keypressed(keyevent evt) { switch(evt.getkeycode()) { case keyevent.vk_numpad6: //original count counta += 5; altitude.settext(counta + ""); } } }); } } public class countdownaltitude extends abstractaction { /** constructor */ public countdownaltitude(string name, string shortdesc, integer mnemonic) { super(name); putvalue(short_description, shortdesc); putvalue(mnemonic_key, keyevent.vk_4); } //right @override public void actionperformed(actionevent e) { addkeylistener(new keyadapter() { public void keypressed(keyevent evt) { switch(evt.getkeycode()) { case keyevent.vk_numpad3: //original count counta -= 5; altitude.settext(counta + ""); } } }); } } public class countuptaspeed extends abstractaction { /** constructor */ public countuptaspeed(string name, string shortdesc, integer mnemonic) { super(name); putvalue(short_description, shortdesc); putvalue(mnemonic_key, keyevent.vk_1); } //left @override public void actionperformed(actionevent e) { addkeylistener(new keyadapter() { public void keypressed(keyevent evt) { switch(evt.getkeycode()) { case keyevent.vk_numpad4: //original count counts += 5; taspeed.settext(counts + ""); } } }); } } public class countdowntaspeed extends abstractaction { /** constructor */ public countdowntaspeed(string name, string shortdesc, integer mnemonic) { super(name); putvalue(short_description, shortdesc); putvalue(mnemonic_key, keyevent.vk_2); } //left @override public void actionperformed(actionevent e) { addkeylistener(new keyadapter() { public void keypressed(keyevent evt) { switch(evt.getkeycode()) { case keyevent.vk_numpad1: //original count counts -= 5; taspeed.settext(counts + ""); } } }); } } public display() { canvas = new drawcanvas(); canvas.setpreferredsize(new dimension(canvas_width, canvas_height)); canvas.setlayout(new borderlayout()); container cp = getcontentpane(); cp.setlayout(new borderlayout()); // create actions shared button , keys action countupaltitude = new countupaltitude("count up", "", new integer(keyevent.vk_enter)); action countdownaltitude = new countdownaltitude("count down", "", new integer(keyevent.vk_d)); action countuptaspeed = new countuptaspeed("count up", "", new integer(keyevent.vk_enter)); action countdowntaspeed = new countdowntaspeed("count down", "", new integer(keyevent.vk_d)); height = new jtextfield("0", 5); altitude.sethorizontalalignment(jtextfield.center); altitude.seteditable(false); altitude.setopaque(false); altitude.setfont(altitude.getfont().derivefont(25f)); taspeed = new jtextfield("0", 5); taspeed.sethorizontalalignment(jtextfield.center); taspeed.seteditable(false); taspeed.setopaque(false); taspeed.setfont(altitude.getfont().derivefont(25f)); altbutton = new jlabel(); altbutton.settext(ccount); canvas.add(altbutton, borderlayout.south); canvas.add(altitude, borderlayout.line_end); canvas.add(taspeed, borderlayout.line_start); //invisible jbutton btncountup = new jbutton(); btncountup.setfocusable(false); btncountup.sethideactiontext(true); // btncountup.setcontentareafilled(false); // btncountup.setborderpainted(false); canvas.add(btncountup, borderlayout.north); //invisible jbutton btncountdown = new jbutton(); btncountdown.setfocusable(false); btncountdown.sethideactiontext(true); // btncountdown.setcontentareafilled(false); // btncountdown.setborderpainted(false); canvas.add(btncountdown, borderlayout.north); // set actions buttons btncountup.setaction(countupaltitude); btncountdown.setaction(countdownaltitude); jbutton btncountups = new jbutton(); btncountups.setfocusable(false); btncountups.sethideactiontext(true); // btncountups.setcontentareafilled(false); // btncountups.setborderpainted(false); canvas.add(btncountups, borderlayout.south); //invisible jbutton btncountdowns = new jbutton(); btncountdowns.setfocusable(false); btncountdowns.sethideactiontext(true); // btncountdowns.setcontentareafilled(false); // btncountdowns.setborderpainted(false); canvas.add(btncountdowns, borderlayout.south); // set actions buttons btncountups.setaction(countuptaspeed); btncountdowns.setaction(countdowntaspeed); addkeylistener(new keyadapter() { public void keypressed(keyevent evt) { switch(evt.getkeycode()) { case keyevent.vk_left: rx1 -= 10; ry1 += 10; rx2 += 10; ry2 -= 10; x1 -=10; x2 +=10; mx1 += 10; mx2 -= 10; repaint(); break; case keyevent.vk_right: rx1 -= 10; ry1 -= 10; rx2 += 10; ry2 += 10; x1 += 10; x2 += 10; mx1 -= 10; mx2 += 10; repaint(); break; case keyevent.vk_down: y1 -= 10; y2 -= 10; ly1 -= 10; ly2 -= 10; sy1 += 10; sy2 -= 10; ry1 +=10; ry2 += 10; repaint(); break; case keyevent.vk_up: y1 += 10; y2 += 10; ly1 += 10; ly2 += 10; sy1 -= 10; sy2 += 10; ry1 -= 10; ry2 -= 10; repaint(); break; case keyevent.vk_m: system.exit(0); } } }); cp.add(canvas, borderlayout.line_start); setdefaultcloseoperation(jframe.exit_on_close); settitle("flight display"); pack(); setvisible(true); requestfocus(); } class drawcanvas extends jpanel { public void paintcomponent(graphics g) { super.paintcomponent(g); setbackground(canvas_background); g.setcolor(ground_color); //draw ground color g.drawrect(sx1 - sx1,sy1 /2, canvas_width, sy2 /2); g.fillrect(sx1 - sx1, sy1 /2, canvas_width, sy2 /2); g.setcolor(line_color); //draw line centre horizontal g.drawline(rx1, ry1 /2, rx2, ry2 /2); g.drawoval(x1 -15, y1 -15, 30, 30); g.filloval(x1 - 5, y1 -5, 10, 10); //draw line centre vertical //draw line dim g.setcolor(color.yellow); g.fillarc(300, 0, 400, 140, 0, 180); g.setcolor(line_color); g.drawline(lx1 -25, ly1 +20, lx2 +25, ly2 +20); g.drawline(lx1 -50, ly1 +40, lx2 +50, ly2 +40); g.drawline(lx1 -25, ly1 +60, lx2 +25, ly2 +60); g.drawline(lx1 -75, ly1 +80, lx2 +75, ly2 +80); g.drawline(lx1 -25, ly1 +100, lx2 +25, ly2 +100); //draw line dim g.drawline(lx1 -25, ly1 -20, lx2 +25, ly2 -20); g.drawline(lx1 -50, ly1 -40, lx2 +50, ly2 -40); g.drawline(lx1 -25, ly1 -60, lx2 +25, ly2 -60); g.drawline(lx1 -75, ly1 -80, lx2 +75, ly2 -80); g.drawline(lx1 -25, ly1 -100, lx2 +25, ly2 -100); //draw polyline centre plane g.drawpolyline(xs, ys, 8); g.setcolor(color.black); g.drawarc(300, 0, 400, 140, 0, 180); g.drawline(mx1+30, my1 + my1, mx2, my2 - my2); g.drawline(mx1-30, my1 + my1, mx2, my2 - my2); g.drawline(mx1, my1 + my1, mx2, my2 - my2); } } public static void main(string[] args) { swingutilities.invokelater(new runnable() { public void run() { new display(); } }); } }

keyevent.vk_2 nil key number 2 in non-numpad area on standard keyboard.

public static final int vk_2 = 0x32;

the below code works fine me, not expect have not added switch case key, can little testing print ascii value of desired key , find out corresponds in keyevent class.

public void keypressed(keyevent e) { switch (e.getkeycode()) { case keyevent.vk_2: system.out.println("non numpad 2"); case keyevent.vk_numpad3: system.out.println("numpad 3"); } }

java swing jbutton jtextfield keyevent

ios - Creating a custom template in Xcode - how can I make a required option based on a checkbox? -



ios - Creating a custom template in Xcode - how can I make a required option based on a checkbox? -

i trying create custom template in xcode. in templateinfo.plist, key options, have code pasted below. template class more not (but not always) utilize delegation when events occur.

the issue having value @ bottom, requiredoptions. want text box enabled only if withprotocol checkbox checked. however, can't figure out value , type of value use. have tried following:

<true/> (as below) - text box enabled. <string>yes</string> - text box disabled. <integer>1</integer> - text box enabled.

does have ideas else try? improve yet, know of decent reference xcode templates?

i have read through apple's plist manual pages , article @ this website.

<array> <dict> <key>description</key> <string>the name of class create</string> <key>identifier</key> <string>productname</string> <key>name</key> <string>class</string> <key>notpersisted</key> <true/> <key>required</key> <true/> <key>type</key> <string>text</string> </dict> <dict> <key>default</key> <string>false</string> <key>identifier</key> <string>withxib</string> <key>name</key> <string>with xib user interface</string> <key>type</key> <string>checkbox</string> </dict> <dict> <key>description</key> <string>choose whether or not delegate skeleton included.</string> <key>default</key> <string>false</string> <key>identifier</key> <string>withprotocol</string> <key>name</key> <string>with delegate skeleton</string> <key>type</key> <string>checkbox</string> </dict> <dict> <key>description</key> <string>the name of protocol used delegation.</string> <key>identifier</key> <string>protocolname</string> <key>name</key> <string>protocol</string> <key>notpersisted</key> <true/> <key>required</key> <true/> <key>type</key> <string>text</string> <key>requiredoptions</key> <dict> <key>withprotocol</key> <true/> </dict> </dict> </array>

i fixed own problem replacing <true/> <string>true</string>.

ios xcode cocoa-touch templates plist

html5 - How do i use KineticJS polygon object with geoJSON coordinates rather than points? -



html5 - How do i use KineticJS polygon object with geoJSON coordinates rather than points? -

i creating interactive map on html5 canvas using kineticjs, problem map info in geojson, have polygon coordinates rather polygon points.

this how polygon points(according tutorial)

//javascript object map info var mymap = { 'russia': { points: [44,1,397,1,518,2,518,151,515,..............6,43,4,43,4] }, 'azerbaijan': { points: [198, 242, 201, 245, 203,..............197, 242] }, 'uae': { points: [224,406,225,410,...............225,407] } }; //function homecoming map info function getdata() { homecoming mymap; }

then utilize kineticjs polygon object draw map on html5 canvas.

//store map info in variable var areas = getdata(); //loop through map (var key in areas) { (function () { var k = key; var area = areas[key]; var points = area.points; var shape = new kinetic.polygon({ points: points, fill: '#fff', stroke: '#555', strokewidth: .5, alpha: 0.1 }); } ()); }

does know how can accomplish same geojson coordinates? here sample of geojson. coordinates nested within geometry object.

{ "type": "featurecollection", "features": [{ "type": "feature", "id": 0, "properties": { "objectid_1": 29, "objectid": 29, "county_nam": "baringo", "county_cod": 30, "shape_leng": 5.81571392065, "shape_area": 0.88451236881 }, "geometry": { "type": "polygon", "coordinates": [ [ [ 36.028686523000033, 1.276123047000056 ], [ 36.036499023000033, 1.263916016000053 ], [ 36.039306641000053, 1.259887695000032 ],............[ 36.028686523000033, 1.276123047000056 ] ] ] } } ] }

var myarray = new array(); for( var level1 in coordinates ){ // each array in coordinates for( var level2 in level1){ // each array in array for( var number in level2){ // each number in array myarray.push(number); } } } var points = myarray;

maybe many levels of nesting, main idea:

go through sub arrays , grab numbers in each , place them in new array.

html5 gis kineticjs geojson

javascript - How to find and edit a elements' href values without losing query params? -



javascript - How to find and edit a elements' href values without losing query params? -

how find element <a> in page contain href attr /dailytickets/front/user.form.php, alter /dailytickets/front/contacts.form.php?

notice want maintain url query parameters (id) next path (user.form.php). example, changing this:

<a id="user_648_648" href="/dailytickets/front/user.form.php?id=648">conseilleruser</a>

to this:

<a id="user_648_648"href="/dailytickets/front/contacts.form.php?id=648">conseilleruser</a>

i'm starting this, don't know how end it:

$('a[href*="dailytickets/front/user.form.php"]').each(function () { if ($(this).children().length == 0) { ........... } });

there's no need loop, jquery interally you, , using selector outright alter , elements match:

$('a[href*="dailytickets/front/user.form.php"]').attr('href', function(i,href) { homecoming href.replace('user.form.php', 'contacts.form.php'); });

javascript jquery html

ide - How do I make IntellIJ use JVM options for all main files in a project? -



ide - How do I make IntellIJ use JVM options for all main files in a project? -

i can configure main file utilize natives needed, in project there multiple main functions need files to utilize jvm alternative when can take debug whichever 1 want without having create configuration each one

you can alter configuration under defaults node, new configurations inherit settings. create sure alter right default configuration type, application need.

refer documentation details.

ide intellij-idea jvm native

ipad - Converting an iphone app to universal app -



ipad - Converting an iphone app to universal app -

i have created iphone app @ begining.but want alter universal app.in converting have changed target universal.gone through google , found have create different xibs ipad.when alter universal asked me create mainwindow ipad .i clicked yes.now on application launch tabbarcontroller .so have created viewcontroller.xib ipad linked in tabbarcontroller. error [ setvalue:forundefinedkey:]: class not key value coding-compliant key delegate.

- (bool)application:(uiapplication *)application didfinishlaunchingwithoptions:(nsdictionary *)launchoptions { if (ui_user_interface_idiom() == uiuserinterfaceidiompad) { viewcontroller *first=[[viewcontroller alloc] initwithnibname:@"viewcontroller-ipad" bundle:nil] ; login *second=[[login alloc]initwithnibname:@"login" bundle:nil]; second.title=@"login"; nsarray *viewarray=[[nsarray alloc] initwithobjects: first,second,nil]; uitabbarcontroller *tabbarcontroller1=[[uitabbarcontroller alloc] init]; [tabbarcontroller1 setviewcontrollers:viewarray animated:no]; for(uiviewcontroller *tab in tabbarcontroller1.viewcontrollers) { [tab.tabbaritem settitletextattributes:[nsdictionary dictionarywithobjectsandkeys: [uifont fontwithname:@"timesnewromanps-boldmt" size:16.0], uitextattributefont, nil] forstate:uicontrolstatenormal]; } [self.window addsubview:tabbarcontroller1.view]; [self.window makekeyandvisible]; cgrect rect = [[uiscreen mainscreen] bounds]; [self.window setframe:rect]; [viewarray release]; [first release]; [second release]; homecoming yes; } else { //code load tabbarcontroller iphone xib's

where link ?i dont find outlets when click filesowner?

iphone ipad xcode4.5

c# - Do a post since a JQUERY dialog? -



c# - Do a post since a JQUERY dialog? -

i've got 2 buttons within of htmlform , working well, differenciate of pass name of button in actionname. below:

[httppost] public actionresult index(string button, quizcompletedviewmodel q) { // quizcompletedviewmodel model of razor view ... } @using (html.beginform("index", "quiz", formmethod.post, new { id = "form" })) { <div> <!-- old code using 2 buttons post --> <div class="float-right"> @* <input name="button" type="submit" value="save" /> <input name="button" type="submit" value="done" />*@ <input name="button" type="button" value="done" /> </div> <div id="dialog-form"> <input name="button" type="button" value="cancel" /> <input name="button" type="submit" value="save" /> <input name="button" type="submit" value="done" /> </div> </div> <div id="question-container"> @for (int = 0; < model.questions.count; i++) { ... } </div> }

then need alter 2 buttons of current view , show pop these 2 buttons above (id="dialog-form"). momment little hard me using jquery when user press buttons , perform post old code.

can lend me hand?

i think might help you, have tweak needs, jquery dialog displays go on button in code illustration , bind function it, can replace asp.net webforms __dopostback cause postback on mvc page.

$("#dialog").dialog({ autoopen: false, height: 380, width: 650, modal: true, close: function () { $('#btncreateaccount').button('refresh'); }, buttons: { 'continue': function () { $(this).dialog('close'); __dopostback($("#<%=btncreateaccount.clientid %>").attr("name"), ''); } } });

c# jquery asp.net-mvc jquery-ui asp.net-mvc-4

gdb step debugging a C program -



gdb step debugging a C program -

consider case function has 10 lines of code , doing step debugging via gdb , on line six. realize function phone call @ line 4 did goof due @ line 5.

assuming line 4 function phone call not drastic (mem free, etc) wish create sp point @ line 4 , step func without re-running test case.

i have been able doing registry modification.

what wanted know, there gdb commands can help me accomplish above without manual registry mod.

thanks,

use jump command described here.

c gdb

css - Font tag and word spacing issue -



css - Font tag and word spacing issue -

to start: 100% understand font tag depresiated , should not used. i'd love meet terrible person did me, trust me :)

i have big cms scheme custom entries use:

<span> <font size="5"> long sentence gives me problem every time. </font> </span>

now happening i'm getting random spacing between words (like between , is, it's twice big space between gives , me). i've tried using letter-spacing -0.1em, screws other areas of site. love utilize text-align prepare it, it's not working.

how can command word spacing/alignment font tag. messing span tags, unless there's way won't mess grandfathered content, isn't alternative appears.

thanks ton

try reset of typographic styles:

font { padding: 0; letter-spacing: 1px; display: block; }

the property display not inherited default. need set explicitly.

css

entity framework - .NET EF - dividing a byte field results an int instead of double -



entity framework - .NET EF - dividing a byte field results an int instead of double -

interesting one.

see next entity framework query:

entities.select(x => new { x.experiencemonths, calculated = (x.experiencemonths > 0 ? x.experiencemonths / 12 : 0) })

the column experiencemonths tinyint in database, means it's byte in ef model.

i'd expect calculated column double (float), since we're dividing number, no matter ends int , decimal portion of result removed, ex 3.7 ends 3.

is there way forcefulness ef convert result somehow double? adding (double) cast before partition look breaks @ runtime.

using ef5.

thanks!

i tried:

calculated = (x.experiencemonths > 0 ? ((double)x.experiencemonths) / 12 : 0)

and worked fine

.net entity-framework

r - pdf font and graph formatting (win.graph) -



r - pdf font and graph formatting (win.graph) -

i came upon problem in r in combination have tried solve , searched in internet, not solve yet. hope can help me.

i run r(x64) on windows 7. graphic device automatically uses arial font, , when save graphs bitmap "font" naturally remains is. however, prefer saving graphs pdf, in case font in resulting pdf exchanged helvetica when save via gui save button.

i found solution in internet, using arial afm-files , pdf("test_auto.pdf", family = "arial"), resulted in pdf using arial font---so far good.

now have to/want alter graph layout using win.graph, , problems start. here example:

arial <- type1font(family = "arial", metrics = c("c:/r_fonts/arialplain.afm", "c:/r_fonts/arialbold.afm", "c:/r_fonts/arialitalic.afm", "c:/r_fonts/arialbolditalic.afm")) pdffonts(arial = arial) setwd("c:/pdfcrop") d1<-matrix(c(1,2,3,4,6,3),3,2) d2<-matrix(c(1,2,3,5,3,1),3,2) #pdf("test_auto.pdf", family = "arial") win.graph(8.3,12,12) layout(matrix(c(1,2),1,2,byrow=true)) plot(d1,type="l",main="gobble r") plot(d2,type="l",main="gobble r") #dev.off()

now code works create graph looks want look, have save graph manually (file->save as) , helvetica font in pdf.

alternatively can alter lower part in

pdf("test_auto.pdf", family = "arial") #win.graph(8.3,12,12) layout(matrix(c(1,2),1,2,byrow=true)) plot(d1,type="l",main="gobble r") plot(d2,type="l",main="gobble r") dev.off()

and produces pdf-file uses arial, graph has other dimensions intending. when using both pdf "cannot opened because does't contain pages" (though not 0kb in size).

is there way work, or alternative win.graph can utilize between pdf() , dev.off()?

thanks help.

oh god, i'm sorry, stupid!

during overlooked, pdf-device has own size parameters.

arial <- type1font(family = "arial", metrics = c("c:/r_fonts/arialplain.afm", "c:/r_fonts/arialbold.afm", "c:/r_fonts/arialitalic.afm", "c:/r_fonts/arialbolditalic.afm")) pdffonts(arial = arial) setwd("c:/pdfcrop") d1<-matrix(c(1,2,3,4,6,3),3,2) d2<-matrix(c(1,2,3,5,3,1),3,2) pdf("test_auto.pdf", width=8.3, height=12, family = "arial") #win.graph(8.3,12,12) layout(matrix(c(1,2),1,2,byrow=true)) plot(d1,type="l",main="gobble r") plot(d2,type="l",main="gobble r") dev.off()

thank hint, dwin

r graph fonts pdf-generation

Why am I seeing ZgotmplZ in my Go HTML template output? -



Why am I seeing ZgotmplZ in my Go HTML template output? -

when i'm calling go template function output html, displays zgotmplz.

sample code:

http://play.golang.org/p/tfuja_pfkm

package main import ( "html/template" "os" ) func main() { funcmap := template.funcmap{ "printselected": func(s string) string { if s == "test" { homecoming `selected="selected"` } homecoming "" }, "safe": func(s string) template.html { homecoming template.html(s) }, } template.must(template.new("template").funcs(funcmap).parse(` <option {{ printselected "test" }} {{ printselected "test" | safe }} >test</option> `)).execute(os.stdout, nil) }

output:

<option zgotmplz zgotmplz >test</option>

"zgotmplz" special value indicates unsafe content reached css or url context @ runtime. output of illustration be

<img src="#zgotmplz">

you can add together safe , attr function template funcmap:

package main

import ( "html/template" "os" ) func main() { funcmap := template.funcmap{ "attr":func(s string) template.htmlattr{ homecoming template.htmlattr(s) }, "safe": func(s string) template.html { homecoming template.html(s) }, } template.must(template.new("template").funcs(funcmap).parse(` <option {{ .attr |attr }} >test</option> {{.html|safe}} `)).execute(os.stdout, map[string]string{"attr":`selected="selected"`,"html":`<option selected="selected">option</option>`})

}

the output looks like:

<option selected="selected" >test</option> <option selected="selected">option</option>

you may want define other functions can convert string template.css,template.js,template.jsstr,template.url etc.

go go-templates

iphone - Errors while trying to play sounds with AudioToolbox in Xcode 4.6 -



iphone - Errors while trying to play sounds with AudioToolbox in Xcode 4.6 -

this issue have been trying prepare while. error in header file app trying create ios using audiotoolbox framework. here code:

#import <iad/iad.h> #import <uikit/uikit.h> #import <audiotoolbox/audiotoolbox.h> #import <iad/adbannerview_deprecated.h> #import <foundation/foundation.h> #import <avfoundation/avfoundation.h> @interface viewcontroller : uiviewcontroller <adbannerviewdelegate> { adbannerview *adview; bool bannerisvisible; } @property (nonatomic, assign) bool bannerisvisible; - (ibaction)cstring:(id)sender { cfbundleref mainbundle = cfbundlegetmainbundle(); cfurlref soundfileurlref; soundfileurlref = cfbundlecopyresourceurl(mainbundle, (cfstringref) @"cstring", cfstr ("caf"), null); uint32 soundid; audioservicescreatesystemsoundid(soundfileurlref, &soundid); audioservicesplaysystemsound(soundid); } @end

also, sound file in supporting files folder.

ahhh, see problem.

you set function declarations .h (or header) file, "@interface" while actual code you'll set .m file, has keyword "@implementation".

it looks have code in wrong place.

iphone ios objective-c audio audiotoolbox

.net - retrieving binded text from xaml in c# -



.net - retrieving binded text from xaml in c# -

i have xaml code :

<listbox x:name="secondlistbox" margin="0,0,-12,0" > <listbox.itemtemplate> <datatemplate> <stackpanel margin="0,0,0,17" width="432" height="78"> <toolkit:toggleswitch name="toggle3" header="{binding name}" height="120" horizontalalignment="left" margin="35,20,0,0" verticalalignment="center" width="440" content="{binding descrip}" checked="toggleswitch1_checked" unchecked="toggleswitch1_unchecked" tap="toggleswitch1_tap"/> </stackpanel> </datatemplate> </listbox.itemtemplate> </listbox> </controls:pivotitem>

now want retrieve toggleswitch(toggle 3)'s header text in c# code. how can done?

when create info binding did, should automatically update variable bound to, name

c# .net xaml windows-phone-7.1