Monday 15 July 2013

php - How to count and sum a group of rows that share the same first letter -



php - How to count and sum a group of rows that share the same first letter -

i have info like:

studyid | participantid | question | problems 1 | 1 | a100 | 3 1 | 1 | a200 | 2 1 | 1 | a300 | 4 1 | 1 | b100 | 2 1 | 1 | b200 | 5 1 | 2 | a100 | 3 1 | 2 | a200 | 3 1 | 2 | a300 | 3 1 | 2 | b100 | 1 1 | 2 | b200 | 6

and want output like:

section | num questions| total problems | average problems | 3 | 18 | 6 b | 2 | 14 | 7

the code go in sql fiddle given below:

set @old_unique_checks=@@unique_checks, unique_checks=0; set @old_foreign_key_checks=@@foreign_key_checks, foreign_key_checks=0; set @old_sql_mode=@@sql_mode, sql_mode='traditional,allow_invalid_dates'; create schema `interviewcodes` default character set utf8 ; utilize `interviewcodes` ; create table `interviewerlkup` ( `interviewerid` int(11) not null auto_increment, primary key (`interviewerid`)) engine = innodb default character set = utf8; create table `studylkup` ( `studyid` int(11) not null auto_increment, primary key (`studyid`)) engine = innodb default character set = utf8; create table `studyinterviewers` ( `studyid` int(11) not null, `interviewerid` int(11) not null, primary key (`studyid`, `interviewerid`), index `fk_studyinterviewers_interviewerlkup1_idx` (`interviewerid` asc), constraint `fk_studyinterviewers_interviewerlkup1` foreign key (`interviewerid`) references `interviewcodes`.`interviewerlkup` (`interviewerid`) on delete no action on update no action, constraint `fk_studyinterviewers_studylkup1` foreign key (`studyid`) references `interviewcodes`.`studylkup` (`studyid`) on delete no action on update no action) engine = innodb default character set = utf8; create table `participant` ( `participantid` int(11) not null auto_increment, `participantcaseid` varchar(45) not null, `studyid` int(11) not null, `interviewerid` int(11) not null, primary key (`participantid`), index `fk_participant_studyinterviewers1_idx` (`interviewerid` asc), constraint `fk_participant_studyinterviewers1` foreign key (`interviewerid`) references `interviewcodes`.`studyinterviewers` (`interviewerid`) on delete no action on update no action, constraint `fk_participant_studylkup1` foreign key (`studyid`) references `interviewcodes`.`studylkup` (`studyid`) on delete no action on update no action) engine = innodb default character set = utf8; create table `coderlkup` ( `coderid` int(11) not null auto_increment, primary key (`coderid`)) engine = innodb default character set = utf8; create table `studycoders` ( `studyid` int(11) not null, `coderid` int(11) not null, primary key (`studyid`, `coderid`), index `fk_studycoders_coderlkup1_idx` (`coderid` asc), constraint `fk_studycoders_coderlkup1` foreign key (`coderid`) references `interviewcodes`.`coderlkup` (`coderid`) on delete no action on update no action, constraint `fk_studycoders_studylkup1` foreign key (`studyid`) references `interviewcodes`.`studylkup` (`studyid`) on delete no action on update no action) engine = innodb default character set = utf8; create table `studyquestion` ( `studyquestionlabel` varchar(45) not null, `studyid` int(11) not null, primary key (`studyquestionlabel`, `studyid`), constraint `fk_studyquestion_studylkup` foreign key (`studyid`) references `interviewcodes`.`studylkup` (`studyid`) on delete no action on update no action) engine = innodb default character set = utf8; create table `codedata` ( `studyid` int(11) not null, `participantid` int(11) not null, `coderid` int(11) not null, `studyquestionlabel` varchar(45) not null, `totalscore` int(11) null default 0, index `fk_codedata_participant1_idx` (`participantid` asc), index `fk_codedata_studycoders1_idx` (`coderid` asc), index `fk_codedata_studyquestion1_idx` (`studyquestionlabel` asc), primary key (`studyid`, `participantid`, `coderid`, `studyquestionlabel`), constraint `fk_codedata_participant1` foreign key (`participantid`) references `interviewcodes`.`participant` (`participantid`) on delete no action on update no action, constraint `fk_codedata_studycoders1` foreign key (`coderid`) references `interviewcodes`.`studycoders` (`coderid`) on delete no action on update no action, constraint `fk_codedata_studylkup1` foreign key (`studyid`) references `interviewcodes`.`studylkup` (`studyid`) on delete no action on update no action, constraint `fk_codedata_studyquestion1` foreign key (`studyquestionlabel`) references `interviewcodes`.`studyquestion` (`studyquestionlabel`) on delete no action on update no action) engine = innodb default character set = utf8; set sql_mode=@old_sql_mode; set foreign_key_checks=@old_foreign_key_checks; set unique_checks=@old_unique_checks; insert `studylkup` (`studyid`) values ('3'); insert `interviewerlkup` (`interviewerid`) values ('1'); insert `interviewerlkup` (`interviewerid`) values ('2'); insert `coderlkup` (`coderid`) values ('1'); insert `coderlkup` (`coderid`) values ('2'); insert `studyinterviewers` (`studyid`, `interviewerid`) values ('3', '2'); insert `studyinterviewers` (`studyid`, `interviewerid`) values ('3', '1'); insert `studycoders` (`studyid`, `coderid`) values ('3', '2'); insert `studycoders` (`studyid`, `coderid`) values ('3', '1'); insert `participant` (`participantid`, `participantcaseid`, `studyid`, `interviewerid`) values ('1', 'ajw123', '3', '2'); insert `participant` (`participantid`, `participantcaseid`, `studyid`, `interviewerid`) values ('3', 'ajw125', '3', '1'); insert `studyquestion` (`studyquestionlabel`, `studyid`) values ('a100', '3'); insert `studyquestion` (`studyquestionlabel`, `studyid`) values ('a200', '3'); insert `studyquestion` (`studyquestionlabel`, `studyid`) values ('a300', '3'); insert `studyquestion` (`studyquestionlabel`, `studyid`) values ('b100', '3'); insert `studyquestion` (`studyquestionlabel`, `studyid`) values ('b200', '3'); insert `codedata` (`studyid`, `participantid`, `coderid`, `studyquestionlabel`, `totalscore`) values ('3', '1', '1', 'a100', '3'); insert `codedata` (`studyid`, `participantid`, `coderid`, `studyquestionlabel`, `totalscore`) values ('3', '1', '1', 'a200', '3'); insert `codedata` (`studyid`, `participantid`, `coderid`, `studyquestionlabel`, `totalscore`) values ('3', '1', '1', 'a300', '3'); insert `codedata` (`studyid`, `participantid`, `coderid`, `studyquestionlabel`, `totalscore`) values ('3', '1', '1', 'b100', '3'); insert `codedata` (`studyid`, `participantid`, `coderid`, `studyquestionlabel`, `totalscore`) values ('3', '1', '1', 'b200', '3'); insert `codedata` (`studyid`, `participantid`, `coderid`, `studyquestionlabel`, `totalscore`) values ('3', '3', '2', 'a100', '3'); insert `codedata` (`studyid`, `participantid`, `coderid`, `studyquestionlabel`, `totalscore`) values ('3', '3', '2', 'a200', '3'); insert `codedata` (`studyid`, `participantid`, `coderid`, `studyquestionlabel`, `totalscore`) values ('3', '3', '2', 'a300', '3'); insert `codedata` (`studyid`, `participantid`, `coderid`, `studyquestionlabel`, `totalscore`) values ('3', '3', '2', 'b100', '3'); insert `codedata` (`studyid`, `participantid`, `coderid`, `studyquestionlabel`, `totalscore`) values ('3', '3', '2', 'b200', '3');

update

i have tried:

print("<table align = 'center' border = '2'>"); print("<tr>"); print("<td align = 'center'>section</td>"); print("<td align = 'center'>total number of items</td>"); print("<td align = 'center'>total number of problems</td>"); print("<td align = 'center'>average number of problems</td>"); print("</tr>"); $sql1 = "select left(codedata.studyquestionlabel, 1) section, count(*) numquestions, sum(codedata.totalscore) totalproblems, avg(codedata.totalscore) avgproblems interviewcodes.codedata codedata (codedata.studyid = ".$studyid.") grouping left(codedata.studyquestionlabel, 1) order left(codedata.studyquestionlabel, 1) asc;"; // run query , result set $rs1 = $conn->query($sql1); // check if query1 wrong; if ($rs1 == false) { $errmsg = "wrong sql1: ".$sql1."error: ".$conn->error; trigger_error($errmsg, e_user_error); } else { while ($arr1 = $rs1->fetch_array(mysqli_assoc)) { print_r($arr1); print("<tr>"); print("<td align = 'center'>".$arr1['section']."</td>"); print("<td align = 'center'>".$arr1['numquestions']."</td>"); print("<td align = 'center'>".$arr1['totalproblems']."</td>"); print("<td align = 'center'>".$arr1['avgproblems']."</td>"); print("</tr>"); } } print('</table>');

i changed above code little bit , got next output.

section | num questions| total problems | average problems | 6 | 18 | 3 b | 4 | 14 | 3.5

i want instead:

section | num questions| total problems | average problems | 3 | 18 | 6 b | 2 | 14 | 7

it seems counting every record question starts w/ letter when want count distinct questions start letter a. how do that?

in sql, substr() starts counting @ 1 , not 0. in case, can utilize left() function , not have worry that:

select left(question, 1) section, count(*) numquestions, sum(problems) totalproblems codedata (studyid = ".$studyid.") grouping left(question, 1);

you can add together ration, seem want, or utilize avg() function:

select left(question, 1) section, count(*) numquestions, sum(problems) totalproblems, avg(problems) averageproblems codedata (studyid = ".$studyid.") grouping left(question, 1);

php mysql count group-by substring

python - How to build a recursive dictionary tree from an ordered adjacency list -



python - How to build a recursive dictionary tree from an ordered adjacency list -

i've been trying figure out day , im @ wits end. maybe i'm getting old this.

i'm trying build tree load_bulk feature on django-treebeard specified here

to save looking, should this:

data = [{'data':{'desc':'1'}}, {'data':{'desc':'2'}, 'children':[ {'data':{'desc':'21'}}, {'data':{'desc':'22'}}, {'data':{'desc':'23'}, 'children':[ {'data':{'desc':'231'}}, ]}, {'data':{'desc':'24'}}, ]}, {'data':{'desc':'3'}}, {'data':{'desc':'4'}, 'children':[ {'data':{'desc':'41'}}, ]}, ]

'data' holds record, , if has children, 'children' list of more 'data' dicts (that can contain list of children , on recursively)

i info ordered list (ordered in depth first, not id):

e.g:

[ {'id': 232, 'name': 'jon', 'parent': 'none'} {'id': 3522, 'name': 'dave', 'parent': '232'} {'id': 2277, 'name': 'alice', 'parent': '3522'} {'id': 119, 'name': 'gary', 'parent': '232'} {'id': 888, 'name': 'gunthe', 'parent': '119'} {'id': 750, 'name': 'beavis', 'parent': 'none'} {'id': 555, 'name': 'urte', 'parent': '750'} ]

how can transform treebeard compliant dictionary (typo's excepted):

[ {'data': {'id': 232, 'name': 'jon', 'parent': 'none'}, 'children': [ {'data': {'id': 3522, 'name': 'dave', 'parent': '232'}, 'children': [ {'data': {'id': 2277, 'name': 'alice', 'parent': '3522'}} ] } {'data': {'id': 119, 'name': 'gary', 'parent': '232'}, 'children': [ {'id': 888, 'name': 'gunthe', 'parent': '119'} ] } ] {'data': {'id': 750, 'name': 'beavis', 'parent': 'none'}, 'children': [ {'id': 555, 'name': 'urte', 'parent': '750'} ] }

]

i guess need kind of recursion function seeing recursive construction attempts have failed. brain doesnt recursion good.

i did lot of searching , found solutions pertaining lists or other structures cant mould fit. i'm relative noob. ps had more fun manually typing out illustration did rest of day (apart dinner time).

maybe there improve ways, here 1 solution:

users = [ { 'id': 232, 'name': 'jon', 'parent': none }, { 'id': 3522, 'name': 'dave', 'parent': 232 }, { 'id': 2277, 'name': 'alice', 'parent': 3522 }, { 'id': 119, 'name': 'gary', 'parent': 232 }, { 'id': 888, 'name': 'gunthe', 'parent': 119 }, { 'id': 750, 'name': 'beavis', 'parent': none }, { 'id': 555, 'name': 'urte', 'parent': 750 } ] users_map = {} user in users: users_map[user['id']] = user users_tree = [] user in users: if user['parent'] none: users_tree.append(user) else: parent = users_map[user['parent']] if 'childs' not in parent: parent['childs'] = [] parent['childs'].append(user) print(users_tree) #user {data: user, childs: []} users_map = {} user in users: users_map[user['id']] = {'data': user, 'childs': []} users_tree = [] user in users: if user['parent'] none: users_tree.append(users_map[user['id']]) else: parent = users_map[user['parent']] parent['childs'].append(users_map[user['id']]) print(users_tree)

python django algorithm recursion dictionary

c# - How to bind ReactiveList to WPF ListBox or ListView using code-behind? -



c# - How to bind ReactiveList to WPF ListBox or ListView using code-behind? -

i have problem display contents of reactivelist in listboxcontrol in view. when seek bind via code-behind bindings (using this.onewaybind(...)) list stays empty. using latest reactiveui version (6.1.0). if alter binding xaml-binding , remove phone call onewaybind(...), list display 5 string elements.

i don't know why isn't working, simple textblock.text-binding works expected (see code).

mainwindow.xaml:

<window x:class="view_location_test.mainwindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:local="clr-namespace:view_location_test" xmlns:system="clr-namespace:system;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" title="mainwindow" height="350" width="525"> <stackpanel> <listbox x:name="toasterlist"> <!-- working if uncomment above line , remove onewaybind phone call in view-code: --> <!--<listbox x:name="toasterlist" itemssource="{binding toasterlist}">--> <listbox.resources> <datatemplate datatype="{x:type system:string}"> <textblock text="{binding}" /> </datatemplate> </listbox.resources> </listbox> <textblock x:name="toastername" /> </stackpanel>

mainwindow.xaml.cs:

public partial class mainwindow : window, iviewfor<viewmodel> { public mainwindow() { viewmodel = new viewmodel(); datacontext = viewmodel; initializecomponent(); // bind this.onewaybind(viewmodel, vm => vm.toasterlist, v => v.toasterlist.itemssource); this.bind(viewmodel, vm => vm.name, v => v.toastername.text); } public viewmodel viewmodel { { homecoming (viewmodel)getvalue(viewmodelproperty); } set { setvalue(viewmodelproperty, value); } } public static readonly dependencyproperty viewmodelproperty = dependencyproperty.register("viewmodel", typeof(viewmodel), typeof(mainwindow), new propertymetadata(null)); object iviewfor.viewmodel { { homecoming viewmodel; } set { viewmodel = (viewmodel)value; } } }

viewmodel.cs:

public class viewmodel : reactiveobject { public viewmodel() { toasterlist.add("toaster 1"); toasterlist.add("toaster 2"); toasterlist.add("toaster 3"); toasterlist.add("toaster 4"); toasterlist.add("toaster 5"); } private string name = "my name"; public string name { { homecoming name; } set { this.raiseandsetifchanged(ref name, value); } } private reactivelist<string> toasterlist = new reactivelist<string>(); public reactivelist<string> toasterlist { { homecoming toasterlist; } set { this.raiseandsetifchanged(ref toasterlist, value); } } }

this because you've set itemstemplate in weird way™, reactiveui thinks have no itemstemplate , setting convention-based 1 (which overkill string).

instead, set this:

<listbox x:name="toasterlist"> <listbox.itemtemplate> <datatemplate> <textblock text="{binding}" /> </datatemplate> </listbox.itemtemplate> </listbox>

c# wpf reactiveui

Environment specific prompt when migrating or seeding in Laravel/Artisan -



Environment specific prompt when migrating or seeding in Laravel/Artisan -

i artisan prompt me before running potentially destructive operations migrating , seeding on production , i'm wondering if there's way me functionality in other environments, such staging. example, if run php artisan migrate output:

************************************** * application in production! * ************************************** wish run command?

if set app_env=production in .env file, should show message. think that's main purpose of app_env unless using "local" environment other purposes don't want happening in production.

laravel seeding migrating artisan

replace - I want to make this program without using a selection and iteration... does anyone know? (VBScript) -



replace - I want to make this program without using a selection and iteration... does anyone know? (VBScript) -

create programme asks input number between 0 , 5 input requirements in form of text (e.g. zero, one, two, etc.). then, programme display messagebox button corresponding input number (e.g. 0 - ok, 1 - okcancel, 2 - abortretryignore, ff.). 1 time user presses 1 of buttons, display text of button pressed user.

i grateful if in here solve this, spent 2 hours didn't solve t_t

only using vbscript

a dictionary can used avoid loop- , if-control-structures. such replacement of command statements info thing, can't programme in vbscript @ to the lowest degree ifs , loopings:

option explicit dim dicb : set dicb = createobject("scripting.dictionary") dicb.comparemode = vbtextcompare dicb("zero") = array(vbokonly, "vbokonly") ' ... dicb("five") = array(vbretrycancel, "vbretrycancel") dim vinp ' inputbox(prompt[, title][, default][, xpos][, ypos][, helpfile, context]) vinp = inputbox("enter button code: zero, one, ...") if vbempty = vartype(vinp) msgbox "aborting ..." exit else if dicb.exists(vinp) ' msgbox(prompt[, buttons][, title][, helpfile, context]) vinp = msgbox(vinp & ": " & dicb(vinp)(1), dicb(vinp)(0), "you asked for:") else if "" = trim(vinp) msgbox "nice try" else msgbox vinp & "- no such button code!" end if end if end if loop

cf msgbox, msgbox consts, inputbox.

replace vbscript

mysql - phpMyAdmin - #1267 - Illegal mix of collations for operation '<' -



mysql - phpMyAdmin - #1267 - Illegal mix of collations for operation '<' -

i getting error when trying run next sql:

select * syshealth 'timestamp' < date_sub(now(),interval 15 minute)

i getting next error:

#1267 - illegal mix of collations (utf8mb4_general_ci,coercible) , (latin1_swedish_ci,numeric) operation '<'

i have table , database collation set utf8_unicode_ci

i have read few articles already, , have tried top reply here, without success...

any more idea's?

edit: additional info - 'timestamp' column of type datetime

you need utilize ` (backtick) identify column if utilize single ' , treated string literal.

select * syshealth `timestamp` < date_sub(now(),interval 15 minute)

mysql phpmyadmin collation

Generating CRUD with Appfuse Maven Plugin(AMP) -



Generating CRUD with Appfuse Maven Plugin(AMP) -

a few days ago used command mvn appfuse:gen generate crud appfuse. generated folllowing files/classes given class (say, category):

1) category-validation.xml

2) categoryaction-validation.xml

3) categoryaction.java

4) categoryactiontest.java

5) categoryform.jsp

6) categorylist.jsp

i expected generate categorydao/categorydaohibernate or maybe categorymanager/categorymanagerimpl classes @ to the lowest degree !!! wrong.

instead, have next code in categoryaction class:

private genericmanager categorymanager;

and in contradiction appfuse's standard tutorial (see page)

can tells me how generate categorydao/categorydaohibernate , categorymanager/categorymanagerimpl classes project?

use -damp.genericcore=false when run appfuse:gen. following:

mvn appfuse:gen -dentity=category -damp.genericcore=false

maven appfuse amp

javascript - How to create global objects in MongoBD's V8 engine to be accessible via db.eval? -



javascript - How to create global objects in MongoBD's V8 engine to be accessible via db.eval? -

i'm trying utilize mongodb server-side javascript in nodejs/node-mongodb-native project , interested how save custom functions in global context of mongodb , access them db.eval script?

let's have next unit function:

var mydocumentutils = { dostuff: function (doc) { // stuff doc ... homecoming doc; } }

and have next javascript function stored in db.system.js collection:

function processdocument (id) { var doc = db.mycollection.findone({ _id : objectid(id)}); doc = mydocumentutils.dostuff(doc); // need access global mydocumentutils object db.mycollection.save(doc); homecoming doc; };

i execute processdocument function nodejs application following:

db.eval('processdocument(54382cb3233283cd3331ca1d)', function (err, doc) { if (err) throw err; });

so question how save mydocumentutils in global mongodb v8 context accessible in db.eval function?

add sec parameter processdocument below:

function processdocument (id, mydocumentutils) { var doc = db.mycollection.findone({ _id : objectid(id)}); doc = mydocumentutils.dostuff(doc); // need access global mydocumentutils object db.mycollection.save(doc); homecoming doc; };

then write db.eval() way:

db.eval(function() { homecoming processdocument.apply(this, arguments); }, "54382cb3233283cd3331ca1d", mydocumentutils);

for environment, can add together phone call behind lastly parameter mydocumentutils.

append ---------------------

store below tow functions db.system.js :

function getmydocumentutils() { homecoming mydocumentutils = { dostuff: function (doc) { // stuff doc ... homecoming doc; } }; } function processdocument (id) { var doc = db.mycollection.findone({ _id : objectid(id)}); var mydocumentutils = getmydocumentutils(); // added line doc = mydocumentutils.dostuff(doc); // need access global mydocumentutils object db.mycollection.save(doc); homecoming doc; };

then phone call db.eval() original style.

javascript node.js mongodb node-mongodb-native

ios - QLPreviewController shows blank page in iOS8 inside UINavigationController, but not independently -



ios - QLPreviewController shows blank page in iOS8 inside UINavigationController, but not independently -

this follow question quicklook/qlpreviewcontroller shows blank page instead of pdf on ios 8 works fine on ios7.

in lastly answer's comments, appears if got nesting qlpreviewcontroller within uinavigationcontroller work ("we add together view, added uinavigationcontroller"), , i'm wondering how done.

this works in ios7, in ios8, can see document when nowadays qlpreviewcontroller independently.

this code works in ios7/8:

qlpreviewcontroller* previewcontroller = [[qlpreviewcontroller alloc] initwithnibname:nil bundle:nil]; previewcontroller.datasource = self; previewcontroller.delegate = self; previewcontroller.modalpresentationstyle = uimodalpresentationfullscreen; [baseviewcontroller presentviewcontroller:previewcontroller animated:no completion:nil;

this code works in ios7 (in ios8 see nav/toolbars, blank screen instead of doc):

qlpreviewcontroller* previewcontroller = [[qlpreviewcontroller alloc] initwithnibname:nil bundle:nil]; previewcontroller.datasource = self; previewcontroller.delegate = self; previewcontroller.modalpresentationstyle = uimodalpresentationfullscreen; uinavigationcontroller* navigationcontroller = [[[uinavigationcontroller alloc] init] autorelease]; [navigationcontroller setviewcontrollers:@[anotherviewcontroller]]; [anotherviewcontroller addchildviewcontroller:previewcontroller]; [anotherviewcontroller.view addsubview:previewcontroller.view]; [baseviewcontroller presentviewcontroller:navigationcontroller animated:no completion:nil;

ios uinavigationcontroller ios8 qlpreviewcontroller

Python, NLTK, can't import "parse_cfg"? -



Python, NLTK, can't import "parse_cfg"? -

so i'm working through tutorial involving python , nltk.

i'm working context free grammars.

i type next command , error...

>>> nltk import parse_cfg traceback (most recent phone call last): file "(stdin)", line 1, in (module) importerror: cannot import name parse_cfg

does have thought causing that? of cfg commands work, not one.

we updated api nltk 3. please read docs

the way access old nltk.parse_cfg() using cfg.fromstring()

example http://www.nltk.org/howto/grammar.html:

>>> nltk import cfg >>> grammar = cfg.fromstring(""" ... s -> np vp ... pp -> p np ... np -> det n | np pp ... vp -> v np | vp pp ... det -> 'a' | 'the' ... n -> 'dog' | 'cat' ... v -> 'chased' | 'sat' ... p -> 'on' | 'in' ... """) >>> grammar <grammar 14 productions> >>> grammar.start() s >>> grammar.productions() [s -> np vp, pp -> p np, np -> det n, np -> np pp, vp -> v np, vp -> vp pp, det -> 'a', det -> 'the', n -> 'dog', n -> 'cat', v -> 'chased', v -> 'sat', p -> 'on', p -> 'in']

python nltk context-free-grammar

html - Hyperlink for an image inside the div -



html - Hyperlink for an image inside the div -

i have multiple div's used image slider contains image path shown below.

<div data-src="images/slides/slideone.jpg"> </div> <div data-src="images/slides/slideone.jpg"> </div> <div data-src="images/slides/slideone.jpg"> </div>

i want add together hyperlink each image how can that...?

if slider static , remain same can add together hyperlink below:-

<a href="url">link text</a>

html

javascript read from a txt file and inject text into form -



javascript read from a txt file and inject text into form -

i apologize in advance total beginner. have pre-existing html form text fields. need have button allow me upload txt file (since when trying reply this, learned javascript can't access file pc without me actively uploading it). need values txt file inserted text fields (for example, form has: name, lastly name, phone etc - , file fill out info).

i going crazy trying collect bits , pieces other people's questions. help appreciated!

it depends on how have handled, there 2 options:

file upload , page redirect

you provide file upload form upload textfile, redirect same page via form submission, handle info on serverside (e.g. parse file , values out of it) , allow server inject values default properties form file returned browser

xmlhttprequest file upload

in modern browsers, native xhr object supports upload property, send file via upload property. has sent serverside script parses file , returns values in fitting format, e.g. json (which this: {'name':'somename', 'lastname':'someothername'}). have register eventlistener on completion of upload (e.g. onload) , set these values on javascript side.

check out xmlhttprequest upload (better solution in opinion): https://developer.mozilla.org/en-us/docs/web/api/xmlhttprequest/using_xmlhttprequest#submitting_forms_and_uploading_files

edit: well, easiest solution provide textfield , paste content of file field, nail button , content parsed. wouldn't rely on network traffic or serverside handling, javascript, e.g. this: dom:

<textarea id="tf"></textarea> <button id="parse">fill form!</button>

js:

var tf = document.getelementbyid("tf"); document.getelementbyid("parse").addeventlistener("click", function(){ var formdata = json.parse(tf.value); //if textfile in json format, formdata object has values });

edit: link posted in comments:

<!-- html --> <input id="the-file" name="file" type="file"> <button id="sendfile">send</button>

and

document.getelementbyid('sendfile').addeventlistener("click", function(){ var fileinput = document.getelementbyid('the-file'); var file = fileinput.files[0]; var formdata = new formdata(); formdata.append('file', file); var xhr = new xmlhttprequest(); // add together event handlers here... xhr.open('post', '/upload/path', true); xhr.onreadystatechange = function(){ if(xhr.readystate == 4 && xhr.status == 200){ var values = json.parse(xhr.responsetext); //these input elements want fill! formnameinput.setattribute('value', values.name); formfirstnameinput.setattribute('value', values.firstname); } } xhr.send(formdata); });

as said, serverside has parse file , respond json

javascript

python - Django: reusable app testing -



python - Django: reusable app testing -

by next official django doc, i've extracted app project , made reusable , installable using pip (currently still have larn how release on pypi that's story)... far good... have no thought how run tests wrote app, since after installing in project using pip django stopped execute tests (by default in django 1.7 project-apps tests picked up)... question is: how can run tests apps has been extracted main project sources?

ps: of course of study don't want forcefulness potential users of app run tests wrote, have run them while working on app on machine

ok, i'm idiot... thing have passing app name in test command:

python manage.py test -v 2 -p "test*.py" --noinput --settings=settings.test my_app

python django unit-testing tdd pip

sap - Testing string contents -



sap - Testing string contents -

is there function in business objects web intelligence (version 2010) test if string contains constant? know match() function can used test string pattern, similar how sql implements condition.

for example:

mystring = 'abc,def,ghi' mystring2 = 'def,ghi,jkl'

both string variables above contain constant 'def', there function test rather using:

=if(match([dimension];"def") or match([dimension];"*def") or match([dimension];"def*") or match([dimension];"*def*")) //do

i have looked through functions , formulas manual , haven't found looking for, hence, here am.

match([dimension];"*def*")) produce result need. wildcard match origin of string.

alternatively, can utilize pos():

=pos("def abc ghi";"def") returns 1

=pos("def abc ghi";"abc") returns 5

=pos("def abc ghi";"xyz") returns 0

sap business-intelligence business-objects

javascript - Getting the result one by one from Ajax Request -



javascript - Getting the result one by one from Ajax Request -

i have next files

index.html <div><ul></ul></div> <button>click me</button> main.js $.ajax({ type: 'post', url: 'get_db.php', data: {name: 'users'}, success: function(result) { $(result).hide().appendto('div ul').fadein(1000); } }); get_db.php include('db_connect.php'); $db_name = $_post['name']; $query = "select * ".$db_name; if($result = $conn->query($query)) { while($row = $result->fetch_assoc()) { $content .= "<li>".$row['id']." ".$row['name']."</li>"; echo $content; } } and question is: how can results 1 1 , append 'div ul'? in case result show @ once.

you can iterate on <li> elements in response, , append each @ time timeout

$.ajax({ type : 'post', url : 'get_db.php', info : {name: 'users'} }).done(function(result) { $(result).each(function(index, li) { settimeout(function() { $(li).hide().appendto('div ul').fadein(1000); }, index * 300); }); });

javascript jquery ajax

c++ - Qt-how to convert a QByteArray to struct -



c++ - Qt-how to convert a QByteArray to struct -

i need convert qbytearray structure. have construction :

struct mavlink_attitude_t { /// <summary> timestamp (milliseconds since scheme boot) </summary> quint32 time_boot_ms; /// <summary> roll angle (rad, -pi..+pi) </summary> float roll; /// <summary> pitch angle (rad, -pi..+pi) </summary> float pitch; /// <summary> yaw angle (rad, -pi..+pi) </summary> float yaw; /// <summary> roll angular speed (rad/s) </summary> float rollspeed; /// <summary> pitch angular speed (rad/s) </summary> float pitchspeed; /// <summary> yaw angular speed (rad/s) </summary> float yawspeed; };

and have qbytearray comes serial port. used union think can't used qbytearray. there other way? illustration can help! tanks.

you can cast it:

qbytearray arr; mavlink_attitude_t* m = reinterpret_cast<mavlink_attitude_t*>(arr.data());

c++ qt data-structures struct qbytearray

I have an array but how do i now insert as csv values php mysql -



I have an array but how do i now insert as csv values php mysql -

i have print_r

array ( [jform] => array ( [itinerary] => array ( [0] => 1 [1] => 2 ) ) )

i have code , bit

foreach($_post $value) { $extradata[] = $value; } $extradata = implode(',',$extradata); $updatentry="update #__tours set itinerary='$extradata' id='$id'"; $db->setquery($updatentry); $db->query();

i can not array produce 1,2 can update row.

cheers in advance jonny

sounds wanna like:

$extradata = implode(',', $_post['jform']['itinerary']);

basically wanna implode() child-array has no more children.

php mysql arrays csv

mysql - LimeSurvey use JSON string from Database -



mysql - LimeSurvey use JSON string from Database -

when utilize admin tool limesurvey add together additional field survey, attributedescriptions field in database looks this;

a:1: { s:11:"attribute_1"; a:4: { s:11:"description"; s:4:"unit"; s:9:"mandatory"; s:1:"n"; s:13:"show_register"; s:1:"n"; s:7:"cpdbmap"; s:0:""; } }

when come in another, field in database looks this;

a:2: { s:11:"attribute_1"; a:4: { s:11:"description"; s:4:"unit"; s:9:"mandatory"; s:1:"n"; s:13:"show_register"; s:1:"n"; s:7:"cpdbmap"; s:0:""; } s:11:"attribute_2"; a:4: { s:11:"description"; s:9:"something"; s:9:"mandatory"; s:1:"n"; s:13:"show_register"; s:1:"n"; s:7:"cpdbmap"; s:0:""; } }

i need dynamic way words "unit" , "something" in array can use.

this code json string;

$sql = $dbh->prepare($sql); $sql->execute(); $result = $sql->fetchall(pdo::fetch_assoc); print $result[0]["attributedescriptions"];

i terrible @ pdo. have tried;

$result = var_dump(json_decode($result[0]["attributedescriptions"], true); $result = var_dump(json_decode($result["attributedescriptions"], true); $result = var_dump(json_decode($result[0], true);

i error;

warning: json_decode() expects parameter 1 string, array given in /var/www/html/surveys/survey-admin/functions/functions.php on line 189 null

this not json, serialized data:

serialize:

$serialized_data = base64_encode(serialize($data));

unserialize:

$unserialized_data = unserialize(base64_decode($serialized_data));

base64_encode() used avoid corruption, if info corrupted unserialize() homecoming false.

mysql json pdo

css - Extra "Search web" appears when scrolling my site on iPhone -



css - Extra "Search web" appears when scrolling my site on iPhone -

i experiencing next (strange) bug:

when site seen on iphone 4 (haven't tested on 5), "search web" bar appears when scrolling , down. slows downwards browsing dramatically. happens on both safari , chrome. doesn't happen on other sites on same device (so not problem phone or browse).

i cannot find similar reports on internet.

has seen this?

could have @ site www.justrunlah.com , check if wrong?

can reproduce it?

screenshot:

thanks lot in advance

try hiding search bar within website (header-search) , see if problem still exists (just test see if own searchbar that's causing problem).

css iphone responsive-design scroll

jquery - jqGrid server response - different format, but it works. Why? -



jquery - jqGrid server response - different format, but it works. Why? -

i figured out jqgrid demmands server response format this:

{ "total": "xxx", "page": "yyy", "records": "zzz", "rows" : [ {"id" :"1", "cell" :["cell11", "cell12", "cell13"]}, {"id" :"2", "cell":["cell21", "cell22", "cell23"]}, ... ] }

and should utilize json reader map properties in case server response properties other jqgrid defaults.

but server response quite different yet plugin works. there no "rows" or "page" properties in our json. , total records displayed properly. server response example:

[ {"id":1,"price":3.99,"title":"foo"}, {"id":2,"price":3.99,"title":"bar"}, ... ]

how come?

thanks lot.

it's absolutely right question! first format of input info input format back upwards oldest versions of jqgrid. able read sec format (array of items) 1 have utilize tricky , not known jsonreader feature of jqgrid properties of jsonreader defined functions. next jsonreader used

class="lang-js prettyprint-override">jsonreader: { repeatitems: false, root: function (obj) { homecoming obj; }, page: function () { homecoming 1; }, total: function () { homecoming 1; }, records: function (obj) { homecoming obj.length; } }

later after introduction loadonce: true feature usage of sec input format (array of items named properties) become more usual. first format of info means server side paging, sorting , filtering/searching of data. server should homecoming only 1 page of data , inform jqgrid total number of pages using total parameter. in case of usage loadonce: true server have homecoming all info @ once. if response contains total, page , records properties, properties ignored , jqgrid calculate valued based on array of returned data.

it lot of errors usage of wrong format of input info or usage of wrong properties of jsonreader didn't corresponds input data. had thought modify code of jqgrid detect , fix definitively wrong alternative of jsonreader based on format of input data. posted suggestions pull request excepted , merged main code of jqgrid. starting version 4.4.5 (see here) jsonreader can not used in cases. because of feature both of input formats can read jqgrid without specifying additional jsonreader option.

jquery jqgrid

c++ - Converting const struct reference to non-const pointer -



c++ - Converting const struct reference to non-const pointer -

i trying work out how convert const struct reference non-const struct pointer.

i have struct called foo:

struct foo { foo& somefunc() { //do homecoming *this; } };

i have method:

struct bar { foo* foopointer; void anotherfunc(const foo& foo) { // set foopointer foo's pointer } };

i phone call this:

foo foo; bar bar; bar.anotherfunc(foo.somefunc());

but how write anotherfunc()?

void anotherfunc(const foo& foo) { foopointer = &foo; // <-- doesn't work foo still const }

you take straight pointer or non-const reference foo.

the way you're passing foo, won't able without const_cast, feels wrong except in few precise case.

as you're storing pointer non-const foo, should take parameter non-const also. think interface: struct has function takes foo const qualification, implying "i peak @ it", function casts , stores in way allows modification. it's bit lying users of code (and first user of code).

c++ pointers struct reference

html5 - createjs bitmap image rotation makes image jagged in chrome -



html5 - createjs bitmap image rotation makes image jagged in chrome -

when seek rotate bitmap image createjs (not resize, rotate) bitmap image gets jagged in chrome. in firefox fine.

here code:

var backcard = new createjs.bitmap(assetsloader.getresult("back")); backcard.rotation = 24; stage.addchild(backcard); stage.update();

any ideas on how prepare ?

i don't know if want prevent or enable antialiasing on chrome, since me chrome gets rotated bitmaps antialiased , firefox don't, i'll talk both things...

enable antialiasing

there's no way of doing natively, can create workaround if want forcefulness antialiasing: adding blur filter in little amounts rotated images. maintain in mind blur expensive filter should avoid using, in case utilize it, you'll need cache bitmap after applying filter cut down cpu usage.

backcard.filters = [new createjs.blurfilter(2, 2, 1);]; // 2 blur radius, 1 blur quality. more quality means more expensive blur. var bounds = backcard.getbounds(); backcard.cache(bounds.x, bounds.y, bounds.width, bounds.height);

prevent antialiasing

i think there's no way of doing yet too, can utilize next version of easeljs allows define if objects antialiased stage, because of webgl. note if webgl isn't supported on user's browser easeljs fallback html5 canvas, still have antialiasing.

html5 google-chrome antialiasing easeljs createjs

Jquery onClick toggleClass: only one div at a time -



Jquery onClick toggleClass: only one div at a time -

i have menu target using jquery function below. problem when home clicked , highlighted , want jump products there both active + both block-1 , block-2 show.

what trying when user clicked on , there decides switch b inactive , on. class stays constant meanwhile 1 of menu items active "content-removed".

what missing?

$(document).ready(function() { $(".home").click(function() { $(this).toggleclass("item-active"); $(".block-1").toggleclass("display"); $(".b1").toggleclass("visibility"); $(".content").toggleclass("content-removed"); }); $(".products").click(function() { $(this).toggleclass("item-active"); $(".block-2").toggleclass("display"); $(".b2").toggleclass("visibility"); $(".content").toggleclass("content-removed"); }); });

here html

<div class="block-1"> <div class="b1"><a href="#">home</a></div> <div class="b1"><a href="#">about</a></div> </div> <div class="block-2"> <div class="b2"><a href="#">overview</a></div> <div class="b2"><a href="#">health</a></div> </div>

jquery

vb.net - Error querying DTO navigation properties with "any" -



vb.net - Error querying DTO navigation properties with "any" -

in breezecontroller have method returns dto 2 properties. 1 property navigation property 1 of entities, , other boolean:

class="lang-vb prettyprint-override">public function projectlist() iqueryable homecoming p in _contextprovider.context.projects not p.isdeleted select new projectlistitem() { .project = p, .hastasks = (from t in _contextprovider.context.projecttasks t.projectid = p.id).any() } end function public class projectlistitem public property project project public property hastasks boolean end class

simple queries against method work fine, project class has collection of project managers, , using "any" query against collection failing in breeze client code, before sending query server, next error message:

class="lang-none prettyprint-override">exception thrown @ line 10698, column 13 in http://localhost:2780/myapp/scripts/breeze.debug.js 0x800a138f - javascript runtime error: unable property 'isanonymous' of undefined or null reference

this in proto._validate method of fnnode, entitytype null.

my query (i'm trying find projects specific project manager) built in pieces, relevant parts are:

var p = breeze.predicate.create("projectmanagerid", op.equals, id); var predicate = breeze.predicate.create("project.projectmanagers", "any", p); // code mutual queries... var query = breeze.entityquery.from("projectlist"); query = query.where(predicate); query = query.select("project.prop1,project.prop2,project.etc,hastasks"); homecoming query.using(this.manager).execute();

i create other predicates , run them through same mutual logic , work fine, seems limited "any" queries, e.g. 1 works...

predicate = breeze.predicate.create("project.clientnumber", op.contains, search) .or("project.clientname", op.contains, search) .or("project.notes", op.contains, search);

i still using breeze 1.4.16 (webapi v1, .net 4.0), have tried updating breeze.client bundle 1.5.1, makes no difference.

any ideas i'm doing wrong?

if manually build odata query looking for, results want, e.g.

class="lang-none prettyprint-override">http://localhost:1234/myapp/breeze/mycontroller/projectlist?$filter=project/projectmanagers/any(p:p/projectmanagerid eq 234)&$select=project/prop1,project/prop2,hastasks

vb.net breeze

openssl - Is the truncated to 64 bit sha1 of a 64 bit number guarenteed to be unique? -



openssl - Is the truncated to 64 bit sha1 of a 64 bit number guarenteed to be unique? -

i'm not crypto expert, or trying cryptography, need decorrelate 64 bit hash (for simhash algorithm, in case cares). if take lowest 64 bits of sha1 has on 64 bit key (8 bytes), result guaranteed unique? "close plenty unique", i'd know sure.

(to reply "what i've tried", i've run loop upper 32 sectiion iterating 0 10000, , lower 32 bit doing same without hits.)

per raymond chen, reply no

openssl sha1

javascript - pdf download using php and onclick function -



javascript - pdf download using php and onclick function -

i have next code.

<div onclick="registerationform.pdf">something</div> <?php header('content-disposition: attachment; filename=registerationform.pdf'); header('content-type: application/pdf'); readfile('registerationform.pdf');

this code straight downloads output if page loaded. need pdf downloaded if something button clicked.help me

php code executed before page content shown or javascript executed, , not sequentially see in example.

what want create php page downloadpdf.php includes headers specified, , redirect user page through link:

link.php:

<a href="downloadpdf.php" target="_blank"> download pdf </a>

note: target="_blank" added here actual page not redirected instead new page opened in new tab-> browser downloads file , closes tab, "feeling" it's immediate download current page on.

downloadpdf.php

<?php header('content-disposition: attachment; filename=registerationform.pdf'); header('content-type: application/pdf'); readfile('registerationform.pdf');

javascript php download dompdf html-to-pdf

windows - Command Line to Delete Files and Folders and Sub Folders in Directory, Except Those Who Were Created Today -



windows - Command Line to Delete Files and Folders and Sub Folders in Directory, Except Those Who Were Created Today -

i want write batch file cleanup downloads folder deleting in except files , folders created today. thanks.

if using modern windows, recommend utilize forfiles,

folder can still messy. want based on timestamp of directory itself? want process recursively through folders, deleting files based on date , delete folder if empty after deleting files of given age. there other reasonable interpretations of question well. personally, utilize python script can create file cleanup want. may why uriil suggested powershell.

arguably, windows services unix downloadable microsoft considered fair game (allowing find command mentioned johnride). if utilize this, create sure johnride suggestion matches actual intent. find command, using alternative -print instead of -exec great debugging

if can utilize forfiles, article may give want. taking liberty of pasting in batch file solution using forfiles article.

@echo off :: set folder path set dump_path=c:\shares\dump :: set min age of files , folders delete set max_days=1 :: remove files %dump_path% forfiles -p %dump_path% -m *.* -d -%max_days% -c "cmd /c del /q @path" :: remove sub directories %dump_path% forfiles -p %dump_path% -d -%max_days% -c "cmd /c if @isdir == true rd /s /q @path"

windows batch-file command-line windows-7

ruby on rails - How can save array values? (multiple inserts) -



ruby on rails - How can save array values? (multiple inserts) -

how can multiple insert after saving main issue?

tables:

flow_budgets |id| |proyected_money| 1 5000 category_expense_budgets |id| |amount| |flow_budget_id| |category_expense_id| 1 1000 1 1 2 2000 1 1 3 3000 1 1 4 4000 1 2 5 5000 1 2 6 6000 1 2 category_expenses |id| |name| |analysis_expense_id| 1 category 1 1 2 category 2 1 3 category 3 2 4 category 4 2 analysis_expenses |id| |name| 1 analysis 1 2 analysis 2

here controller:

def new_flow @analysis_expenses = analysisexpense.all @obj_flow = flowbudget.new(params[:obj_flow]) end def create_flow obj_flow = flowbudget.new(params[:obj_flow]) obj_flow.save() if obj_flow.save() @flow_budget_id = flowbudget.last.id obj_proyected = categoryexpensebudget.new end end

here view:

<% form_for :obj_flow, :url => {:controller=>"flow_budget",:action=>'create_flow'} |f|%> <%= f.text_field :proyected_money %> <% @analysis_expenses.each |analysis_expense| %> <label><%= analysis_expense.name %></label> <%= text_field_tag "proyected_analysis_expenses",{},:name => "proyected_analysis_expense[amount][]", :id => "proyected_analysis_expense_#{analysis_expense.id}" %> <table> <% analysis_expense.category_expenses.each |category_expense|%> <tr> <td><%= category_expense.name %>:</td> <td><%= text_field_tag "proyected_category_expenses",{},:name => "proyected_category_expense[name][]", :id => "proyected_category_expense_#{category_expense.id}" %></td> </tr> <% end %> </table> <% end %> <% end %>

here log:

processing flowbudgetcontroller#create_flow (for 127.0.0.1) [post] parameters: {"proyected_money"=>"8000", "proyected_category_expense"=>{"amount"=>["2100", "2500" ], "proyected_analysis_expense"=>{"amount"=>["1000", "1100", "1200", "1300" ]} insert `flow_budgets` (`proyected_money` ) values(8000)

i want save

insert `flow_budgets` (`proyected_money` ) values(8000) insert `category_expense_budgets` (`amount`,'flow_budget_id','category_expense_id' ) values(1000,1,1) insert `category_expense_budgets` (`amount`,'flow_budget_id','category_expense_id' ) values(1100,1,2) insert `category_expense_budgets` (`amount`,'flow_budget_id','category_expense_id' ) values(1200,1,3) insert `category_expense_budgets` (`amount`,'flow_budget_id','category_expense_id' ) values(1300,1,4)

please can help me?

i think looking accepts_nested_attributes_for :category_expense_budgets

i presume model objflow has has_many :category_expense_budgets.

then should work if add together acceptance of nested attributes , format form params hash gets right format. easiest way accomplish think like:

<% form_for @obj_flow, :url => {:controller=>"flow_budget",:action=>'create_flow'} |f|%> <%= f.text_field :proyected_money %> <% @analysis_expenses.each |analysis_expense| %> <% f.fields_for analysis_expense |nested_f| %> # new of import line <label><%= analysis_expense.name %></label> <%= nested_f.text_field "proyected_analysis_expenses",{},:name => "proyected_analysis_expense[amount][#{analysis_expense.id}]", :id => "proyected_analysis_expense_#{analysis_expense.id}" %> <table> <% analysis_expense.category_expenses.each |category_expense|%> <tr> <td><%= category_expense.name %>:</td> <td><%= text_field_tag "proyected_category_expenses",{},:name => "proyected_category_expense[name][#{analysis_expense.id}]", :id => "proyected_category_expense_#{category_expense.id}" %></td> </tr> <% end %> </table> <% end %> <% end %> <% end %>

read more here if like: http://api.rubyonrails.org/classes/activerecord/nestedattributes/classmethods.html

ruby-on-rails ruby

c++ - error: use of deleted function. Why? -



c++ - error: use of deleted function. Why? -

i trying create function applies arbitrary functor f every element of provided tuple:

#include <functional> #include <tuple> // apply functor every element of tuple namespace detail { template <std::size_t i, typename tuple, typename f> typename std::enable_if<i != std::tuple_size<tuple>::value>::type foreachtupleimpl(tuple& t, f& f) { f(std::get<i>(t)); foreachtupleimpl<i+1>(t, f); } template <std::size_t i, typename tuple, typename f> typename std::enable_if<i == std::tuple_size<tuple>::value>::type foreachtupleimpl(tuple& t, f& f) { } } template <typename tuple, typename f> void foreachtuple(tuple& t, f& f) { detail::foreachtupleimpl<0>(t, f); } struct { a() : a(0) {} a(a& a) = delete; a(const a& a) = delete; int a; }; int main() { // create tuple of types , initialise them zeros using t = std::tuple<a, a, a>; t t; // creator simple function object increments objects fellow member struct f { void operator()(a& a) const { a.a++; } } f; // if works should end tuple of a's members equal 1 foreachtuple(t, f); homecoming 0; }

live code example: http://ideone.com/b8nlcy

i don't want create copies of a because might expensive (obviously in illustration not) deleted re-create constructor. when run above programme get:

/usr/include/c++/4.8/tuple:134:25: error: utilize of deleted function ‘a::a(const a&)’ : _m_head_impl(__h) { }

i know constructor deleted (that intentional) don't understand why trying create copies of struct. why happening, , how can accomplish without copying a?

this problem you're getting "deleted constructor" error for:

std::function<void(a)> f = [](a& a) { a.a++; };

you're trying set std::function passes a value. a, having no copy-constructor, can't passed value.

try matching actual argument type more carefully:

std::function<void(a&)> f = [](a& a) { a.a++; };

but since aren't capturing variables, can try

void(*f)(a&) = [](a& a) { a.a++; };

you've got major problem base of operations case of template recursion: if enable_if working, seems not be, you'll have ambiguous call. think need disable main case.

c++ c++11 gcc4.8

oop - How to define a generic data type containing enums in C? -



oop - How to define a generic data type containing enums in C? -

i trying define generic macro in c state transition in state machine , "logs" info on state transition (reason of transition , number of transitions done).

as approach shall used in multiple state machines want utilize generic macro like:

#define state_transition(state_variable, new_state, reason) / state_variable.state = new_state; / /* new_state enum value */ state_variable.transition_reason = reason; / /* reason enum value */ state_variable.state_transition_counter++; /* counter may overflow */

to create possible thinking of state type this

struct specific_state { enum possible_states state; enum state_transition_reasons transition_reason; uint8 state_transition_counter; }

which can used specific state machine.

to create sure every state uses same construction (to create macro work) seek utilize parent type state. problem enum possible_states , enum state_transition_reasons can vary different statemachines. generic fellow member in struct state_transition_counter :)

my question now:

is there possibility define type in c represents base of operations "class" like:

struct debuggable_state { enum state; enum transition_reason; uint8 state_transition_counter; }

which can subclassed afterwards (to apply specific enum types)?

perhaps replace macro inline function create type safe, still not sure if approach possible @ all.

you utilize int instead of enums in generic struct, enums represented int anyway..

c oop enums

java - Solr: copy a text field to another and transform into keywords -



java - Solr: copy a text field to another and transform into keywords -

i'm pretty new solr, , i'm trying accomplish build keywords list , store other fields in document. have text field in solr schema defined :

<field name="title" type="text_general" indexed="true" stored="false" />

what need create field store keywords, same after processing title after analyzing (tokenizing, stemming etc.). goal expose keywords associated document (built title) 1 can obtain them document.

while possible process title using lucene analyzer (the code in java) , submit pre-built keywords field each document, wonder there way accomplish using copyfield , transforming text field keywords. please allow me know if question not clear.

stored contains non-analyzed input. sounds you're looking termvectors feature: http://wiki.apache.org/solr/termvectorcomponent

java solr lucene keyword analyzer

java - NumberFormatException and TypeMismatchException for using propertyPlaceholderConfigurer in xml configuration -



java - NumberFormatException and TypeMismatchException for using propertyPlaceholderConfigurer in xml configuration -

i using list beingness initialized in spring.xml. need utilize propertyplaceholderconfigurer loose-couple initial values in pointlist.cfg.properties file.

this spring.xml code:

<bean id="parenttriangle" class="edu.akarimin.koushik.triangle" autowire="byname" init-method="myinit" destroy-method="cleanup"> <property name="pointlist"> <list> <ref bean="pointa" /> </list> </property> </bean> <bean id="triangle" class="edu.akarimin.koushik.triangle" parent="parenttriangle"> <property name="pointlist"> <list merge="true"> <ref bean="pointb" /> <ref bean="pointc" /> <ref bean="pointd" /> </list> </property> </bean> <bean id="pointa" class="edu.akarimin.koushik.point"> <property name="x" value="${pointa.pointx}" /> <property name="y" value="${pointa.pointy}" /> </bean> <bean id="pointb" class="edu.akarimin.koushik.point"> <property name="x" value="${pointb.pointx}" /> <property name="y" value="${pointb.pointy}" /> </bean> <bean id="pointc" class="edu.akarimin.koushik.point"> <property name="x" value="${pointc.pointx}" /> <property name="y" value="${pointc.pointy}" /> </bean> <bean id="pointd" class="edu.akarimin.koushik.point"> <property name="x" value="${pointd.pointx}" /> <property name="y" value="${pointd.pointy}" /> </bean> <bean id="pointe" class="edu.akarimin.koushik.point"> <property name="x" value="${pointe.pointx}" /> <property name="y" value="${pointe.pointy}" /> </bean> <bean class="org.springframework.beans.factory.config.propertyplaceholderconfigurer"> <property name="locations"> <list> <value>classpath:pointlist.cfg.properties</value> </list> </property> </bean>

triangle class code is:

package edu.akarimin.koushik; public class triangle{

private list<point> pointlist; public void draw(){ (point point : pointlist) { system.out.println("point= (" +point.getx()+ ","+point.gety()+")"); } public void myinit(){ system.out.println("myinit method called triangle"); } public void cleanup(){ system.out.println("cleanup method called triangle");

}

and main method is:

public class drawingapp { public static void main(string[] args) { applicationcontext context = new classpathxmlapplicationcontext("spring.xml"); triangle triangle = context.getbean("triangle", triangle.class); triangle.draw(); }

}

class point is:

public class point { private int x; private int y; public int getx() { homecoming x; } public void setx(int x) { this.x = x; } public int gety() { homecoming y; } public void sety(int y) { this.y = y; }

}

any ideas prepare problem ?

java xml spring spring-mvc

c++ - Extract a specific text pattern from a string -



c++ - Extract a specific text pattern from a string -

i have string follows,

"0/41/9/71.94 pc:0x82cc (add)"

the desired output text between brackets ( )

ex: output = add,

for string specified above

how done using sscanf? there improve way in c++?

with string operations exclusively:

std::string text = "0/41/9/71.94 pc:0x82cc (add)"; auto pos = text.find('(') + 1; auto opcode = text.substr(pos, text.find(')', pos) - pos);

demo.

with sscanf this:

std::string opcode(5, '\0'); // suitable maximum size sscanf(text.c_str(), "%*[^(](%[^)]", &opcode[0]);

demo.

c++ string sscanf

c++ - Constructor definition with a member initializer list -



c++ - Constructor definition with a member initializer list -

i have code given me finish few things unfamiliar me. first of all, what's point of fellow member initializer in first function?

class circle { private: double r; public: circle(double radius) : r(radius) {} double get_perimeter() { homecoming 2*pi*r; } double get_radius() { homecoming get_perimeter()/2*pi; } };

and in main() function:

int main() { double radius; cin >> radius; circle c(radius); cout << c.get_radius << endl; homecoming 0; }

the circle c(radius); line makes no sense me. can narrate me few lines addressed?

circle(double radius) : r(radius) {}

the point of fellow member initializer, r(radius), initialize fellow member r, of course! line defines constructor of circle. constructor takes argument of type double , initialises fellow member r value.

circle c(radius);

this declares variable c type circle , passes radius constructor. compare std::string str("foo"); or int x(5); - these of same form.

c++

wordpress - Ignore posts from before today PHP -



wordpress - Ignore posts from before today PHP -

i have next loop in wordpress , though worked (at least, think so), stopped working should:

<?php $items = 0; $thiscat = get_category(3); $cat_slug = $thiscat->slug; $args = array( 'post_type' => 'course', 'posts_per_page' => 3, 'meta_key' => 'date_start', 'orderby' => 'meta_value', 'category_name' => $cat_slug, 'order' => 'asc', ); ?> <ul> <?php $loop = new wp_query( $args ); while ( $loop->have_posts() , $items < 3) { $loop->the_post(); $category_course = get_the_category(3); global $post; $category_detail = get_the_category( $post->id ); $date_start = get_post_meta(get_the_id(), 'date_start', true); $place = get_post_meta(get_the_id(), "place", true); if( $date_start >= strtotime('today') ) { ?> <li> <a href="<?php the_permalink(); ?>" class="date_fp"><?php echo strftime("%a, %e. %b. %y", $date_start); ?> - <?php echo $place;?></a> <?php foreach ($category_detail $category_id) { if($category_id->cat_name == 'z_aflyst') { echo "- <strong>aflyst</strong>"; } }?> </li> <?php $items++; } } if($items==0) { ?> <li> ingen kommende kurser </li> <?php } ?>

the expected result: count courses held in future, display maximum of 3 on front end page

the outcome: count courses in database (both past , present) maximum of 3, display ones held on front end page (the ones held in past not displayed, counted). if 3 or more courses held in past, doesn't display of courses held in future.

in head, should ignoring posts date before today, apparently still counts them, output on front end page 1 course of study (in case of above loop, there 2 courses held in past , 3 planned future), instead of available 3. found out if alter posts_per_page 4, it'll display 1 more course, has fact counts courses in past post in posts_per_page.

it's little tweak of code, how , create sure ignores posts before strotime('today')?

by adapting $args's meta-query, managed compare value of meta-key value of choosing (in case time()).

by adding this, possible remove if-sentence find out if course of study placed in future or past.

$args['meta_query'] = array( array( 'key' => 'date_start', 'value' => time(), 'compare' => '>=' ) )

this results in $args variable grabbing posts equal or greater time(). epic solution stackoverflow, made code more readable.

php wordpress

php - Error during installing RSGallery2 -



php - Error during installing RSGallery2 -

i have problem during installation of rsgallery2. when finished installation, rsgallery has not create table in database like: #__rsgallery2_files,...

can body help me this?

php mysql

c - my execv() function not working in linux ubuntu -



c - my execv() function not working in linux ubuntu -

i wrote next code output: "error!" (the execv function not scheduled return)

what doing wrong???

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <math.h> #include <string.h> #include <malloc.h> #include "lineparser.h" #define location_len 200 char* getl(void); int main(int argc,char *argv[]) { char *loc = getl(); char *args[] = {loc,"ls",null}; int i; execv(args[0],args); printf("error!"); free(loc); } char* getl(void) { char *buff = (char**)malloc(sizeof(char)*location_len); getcwd(buff,location_len); homecoming buff; }

read documentation of execv(3) , of execve(2) , of perror(3). @ least, should code

int main(int argc,char *argv[]) { char *loc = getl(); char *args[] = {loc,"ls",null}; int i; execv(args[0],args); perror("execv"); free(loc); }

you should compile gcc -wall -g utilize gdb debugger.

your usage of execv wrong (you need total path, e.g. "/bin/ls", , order of arguments wrong). want exevcp(3) , should in fact code @ least:

char*args= {"ls", loc, null); execvp ("ls", args); perror("execvp")

if insist on using execv(3) try

char*args= {"ls", loc, null); execv ("/bin/ls", args); perror("execv")

i don't understand code supposed do. might interested glob(7) & glob(3).

you should read advanced linux programming. seems there several concepts don't understand enough. guess strace(1) useful (at to the lowest degree running strace ls *.c understand happening).

maybe getl gnu function get_current_dir_name(3) doing, (char**) cast within grossly wrong. , should improve clear buffer buff using memset(3) before calling getcwd(2) (and should test against failure of ̀ mallocand ofgetcwd`)

perhaps want opendir(3), readdir(3), asprintf(3), stat(2); these, avoid running ls

if coding shell, should strace existing shell, , after having read references giving here, study source code of free software shells sash , gnu bash

c linux ubuntu-14.04 execv

javascript - Delayed repaint on Scroll to Top of Fixed Header -



javascript - Delayed repaint on Scroll to Top of Fixed Header -

example: http://www.arkansasmatters.com/beta/news/politics

i have simple javascript keeps fixed header on website. when scrolling up, header on rare occasion show reddish bar disappear if go on scrolling up.

function stickynav() { var win = $(window), nav = $('#primary_nav_wrap'), pos = nav.offset().top, sticky = function () { win.scrolltop() > pos ? nav.addclass('sticky') : nav.removeclass('sticky'); }; win.scroll(sticky); }

is there reason script cause following:

blank bar on scrolling up flickering while scrolling down

additional informaation:

browser: google chrome user agent: mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, gecko) chrome/37.0.2062.124 safari/537.36

alternatively: there ie7+ cross browser solution similar missed?

update

this issue replicable if user scrolls , down. calling js function on , on again.

this solution worked similar problem having in chrome v38+ js/css accordion plugin. believe happened when js initiated css alter occurred plenty chrome's repaint function fell behind.

using translatez(0) nudge browser using gpu acceleration speed css transforms. here couple articles more detail:

http://www.smashingmagazine.com/2012/06/21/play-with-hardware-accelerated-css/

http://blog.teamtreehouse.com/increase-your-sites-performance-with-hardware-accelerated-css

https://developer.mozilla.org/en-us/docs/web/css/transform

javascript jquery html css

logging - Hadoop log files missing -



logging - Hadoop log files missing -

coming older version of hadoop, looking user log files (log.index, stderr, stdout, syslog) in hadoop 2.2.0. first looked web interface, there nil running @ port 50030. looked hadoop_home_dir/logs, did not see userlogs dir, nor jobnumber. nex location looked temp dir (/tmp), , found folders looked it:

$ find . -name "job_local1643076800_0001" ./hadoop-tom/mapred/staging/tom1643076800/.staging/job_local1643076800_0001 ./hadoop-tom/mapred/local/localrunner/tom/jobcache/job_local1643076800_0001 ./hadoop-tom/mapred/local/localrunner/tom/job_local1643076800_0001

in here found directories in format expected: attempt_local1643076800_0001_m_000000_0 empty.

i set "export hadoop_log_dir=/path", not fill either. missing here? or went wrong when build hadoop source?

thanks in advance!

default mapreduce framework in hadoop 2.2.0 yarn. 50030 port jobtracker webui, in yarn instead of jobtracker uses resource manager webui accessible @ 8088.

in case job beingness executed localrunner, means either client side, yarn not configured or yarn services down. validate configurations.

hadoop logging

How to get an url in a string with regex -



How to get an url in a string with regex -

i'm trying utilize regex url miss end of url here illustration of string containing url

<div class=\"externalclassc7001553ffc442dd9b99547999723c7b\">http://bazar.flow.be/knowledge/legal/fr/ina/circul/circul bb adm. 2014/circ_bb_p_2014_xxx.doc</div>

i've in output:

http://bazar.flow.be/knowledge/legal/fr/ina/circul/circul bb adm. 2014/circ_bb_p_2014_xxx.doc

for now, utilize regex homecoming me: "http://bazar.flow.be/knowledge/legal/fr/ina/circul/circul"

@"((https?|ftp|file)\://|www.)[a-za-z0-9\.\-]+(/[a-za-z0-9\?\&\=;\+!'\(\)\*\-\._~%]*)*"

thanks solution

((https?|ftp|file)\://|www.)[a-za-z0-9\.\-]+(/[a-za-z0-9\?\&\=;\+!'\(\)\*\-\._~%]*)*([^<]+)*

try this.see demo.

http://regex101.com/r/hq1rp0/83

regex

big o - time complexity for binary search trees -



big o - time complexity for binary search trees -

if utilize insert() function bst, time complexity can bad o(n) , o(log n). i'm assumng if had balanced tree, time complexity log n because able ignore half of tree every time go downwards "branch". , if tree unbalanced o(n). right thinking this?

yes, correct, see e.g. wikipedia, http://en.wikipedia.org/wiki/binary_search_tree#searching.

if utilize e.g. c++ stl std::map or std::set, red-black, balanced tree. worth noting these stl info structures, performance 100% of time, can of import in e.g. hard real-time systems. hash tables faster, not fast 100% of time red-black trees.

big-o time-complexity

android - Google Play Store: "Designed for phones" - How to get rid of? -



android - Google Play Store: "Designed for phones" - How to get rid of? -

i facing problem google play store lately. far, able publish apps phones , tablets without problems. lately in newer apps message "designed phones" , app rank low in tablets. google has made rules tablets more strict, don't know how create app compatible new rules.

what have done far:

i have made large, , xlarge folders appropriate layout files. i have upload hi-res screenshots 7' , 10' tablets. i target sdk v. 19. i no suggestions in developer console, seems there no problems .apk

and still getting "designed phones" tag. missing something? above steps worked fine far apps.

any ideas?

some other things try, stated in guidelines

targetsdkversion , minsdkversion in element must greater 10 (you have though).

you must have assets tablets. means providing icons (and other image assets)for @ to the lowest degree 1 of these: hdpi, xhdpi, or xxhdpi.

if declared in manifest, < supports-screens> 'must not specify android:largescreens="false" or android:xlargescreens="false".'

declare hardware features correctly: not tablets back upwards hardware features such camera. find such features in in manifest , replace

< uses-feature android:name="android.hardware.camera" android:required="false" />

your app should work seamlessly if user not have photographic camera on tablet.

android optimization tablet

http - Node.js proxy for monitor network requests and responses -



http - Node.js proxy for monitor network requests and responses -

i using nodejitsu's http proxy build tool monitor web traffic.

httpproxy.createproxyserver({ target: 'http://localhost:9000' }) .listen(8000); util.puts('proxy server listening on port 8000'); http.createserver(function targetserver(req, res) { res.writehead(302, { 'location': req.headers.host }); util.puts('request proxied to: ' + req.url + '\n' + json.stringify(req.headers, true, 2)); res.end(); }) .listen(9000); util.puts('target server listening on port 9000');

what want is

proxy outgoing requests client (browser) target server send them original destination url target server receive response on target server send response client

basically have middleman placed between client , destination server can monitor traffic. when seek this, create 302 request, econn error.

error: connect econnrefused @ errnoexception (net.js:901:11) @ object.afterconnect [as oncomplete] (net.js:892:19)

can help me figure out whats going on

update

i changed 302 location argument so:

res.writehead(302, { 'location': '/' });

now, when browser tries hitting proxy server, enters redirection loop. why happening?

node.js http http-proxy node-http-proxy

Create new recent testimonials widget in wordpress -



Create new recent testimonials widget in wordpress -

i have created new post type testimonials , portfolio. have created new widget areas,with this

register_sidebar( array( 'name' => __( 'testimonial sidebar', 'my-theme' ), 'description' => __( 'testimonial widgets area', 'my-theme' ), 'id' => 'sidebar-3', 'before_widget' => '', 'after_widget' => '', 'before_title' => '', 'after_title' => '', ) );

i have created page sidebar-testimonial.php , phone call them in single-testimonial.php get_sidebar('testimonial');

now question is, how create widget "recent testimonials" same "recent post", dragging in 'testimonial sidebar' can display them in pages.

it real easy create own recent post widget.

here steps:

copy default recent posts widget core can found here.

add relevant code widget in functions.php , rename widget ever like

register new widget. see widget in backend

final customization here alter query within widget. need add together 'post_type' => 'your post type name', query arguments on line 702 of link provided above

you can alternatively create utilize of filter provided , filter arguments of default recent post widget

wordpress

php - Zend index action parameters -



php - Zend index action parameters -

i want have url example.com/invoice/id/5

create action

function indexaction(){ echo "test"; }

now seek access action url

example.com/invoice/ or example.com/invoice/index

and pass parameters

example.com/invoice/id/5

here i'm error because zend seek render

id.phtml

my question how have url example.com/invoice/id/5 , not utilize example.com/invoice/index/id/5

by default zend route follows: http://www.example.com/controller/action/param_name/param_value/param_name_1/param_name_1_value

for custom url, have define routes in bootstrap.php of zf1.

$frontcontroller = zend_controller_front::getinstance(); $router = $frontcontroller->getrouter();

$router->addroute( 'someidentifier', new zend_controller_router_route( '/invoice/:id', array( 'controller'=>'invoice', 'action'=>'index' ) ) );

if zf2 think have define custom route in module.php, onbootstrap function , attach eventmanager.

php zend-framework zend-route

How to implement raw sql query in Tastypie -



How to implement raw sql query in Tastypie -

i trying simple query, not work. thanks.

select * tsimple (start_date < '2012-04-20' , end_date null) or (end_date > '2012-04-20' , start_date < '2012-04-20') class tsimple (models.model): start_date = models.datetimefield() end_date = models.datetimefield(blank=true, null=true) ... class tsimpleresource(modelresource): def dehydrate(self, bundle): request_method = bundle.request.meta['request_method'] if request_method=='get': new_date = bundle.request.get.get('new_date', '') qs = tsimple.objects.raw( 'select * tsimple (start_date<=\'' + new_date + '\' , end_date>=\'' + new_date + '\') or (start_date<=\'' + new_date + '\' , end_date null)') ret_list = [row row in qs] // not work. not able right json info in javascript. // needs homecoming bundle. how replace bundle? // right way it? homecoming ret_list else: // ok. homecoming bundle

i have next questions:

1) (raw sql method) if implementing in dehydrate method right way it? if is, above not work. should homecoming bundle object. how build new bundle?

if above method ok, noticed bundle constructed .data field default query(?), thrown away new query. raise questions if right way it.

2) if there other raw sql method it? execute sql?

3) how in filter?

4) know sql , not familiar complex filter. that's why trying utilize raw sql method quick prototype. draw back? noticed using tastypie has many unnecessary queries don't know how rid of it. example, query on table foreign key trigger query table's data, don't want get.

i figure out filter , seems worked. still interested in raw sql.

def apply_filters(self, request, applicable_filters): base_filter = super(tsimpleresource, self).apply_filters(request, applicable_filters) new_date = request.get.get('new_date', none) if new_date: qset = ( ( q(start_date__lte=new_date) & q(end_date__gte=new_date) ) | ( q(start_date__lte=new_date) & q(end_date__isnull=true) ) ) base_filter = base_filter.filter(qset) homecoming base_filter

tastypie

ios - UITextField Not really working -



ios - UITextField Not really working -

i'm starting larn ios development , objective c , i'm next apple's tutorial (https://developer.apple.com/library/ios/referencelibrary/gettingstarted/roadmapios/thirdtutorial.html#//apple_ref/doc/uid/tp40011343-ch10-sw1)

i have text field adds new task array. when press "done" task added array , appears in tableview - in debug:

[xyzviewcontroller addtaskfield:]: unrecognized selector sent instance 0x7fb13348c8c0 2014-10-16 18:00:36.120 tutorial123[7880:1837804] *** terminating app due uncaught exception 'nsinvalidargumentexception', reason: '-[xyzviewcontroller addtaskfield:]: unrecognized selector sent instance 0x7fb13348c8c0'

here's code have on file handles text field:

#import "xyzviewcontroller.h" #import "todoitem.h" @interface xyzviewcontroller () @property (weak, nonatomic) iboutlet uitextfield *addtaskfield; @property (weak, nonatomic) iboutlet uibarbuttonitem *donebutton; @end @implementation xyzviewcontroller - (void)viewdidload { [super viewdidload]; // additional setup after loading view nib. } - (void)didreceivememorywarning { [super didreceivememorywarning]; // dispose of resources can recreated. } - (ibaction)prepareforsegue:(uistoryboardsegue *)segue sender:(id)sender{ if(sender != self.donebutton) return; if(self.addtaskfield.text.length > 0){ self.todoitem = [[todoitem alloc] init]; self.todoitem.itemname = self.addtaskfield.text; self.todoitem.completed = no; } } @end

when wiring addtaskfield button storyboard did create action first deleted method in code , created outlet? if that's happened have go storyboard click on button , connection inspector , see touch within doesn't have addtaskfield: wired up. see image below. added testaction: action. have press little x next view controller testaction: delete it. allow me know if that's happened.

ios objective-c uitextfield

Prim's Algorithm implementation in C++ STL error? -



Prim's Algorithm implementation in C++ STL error? -

i trying implement prim's mst algorithm in c++ using stl.

but next programme seems come in in infinite loop. , exits error.

pseudo-code prim's mst algorithm ;

my code :

#include<algorithm> #include<vector> #include<iostream> #include<queue> using namespace std; typedef vector<int> vi; typedef pair<int,int> ii; typedef vector<ii> vii; #define rep(i,a,b) for(int i=int(a);i<b;i++) #define trvii(c,it) for(vii::iterator it=(c).begin();it!=(c).end();it++) #define inf 2000000000 void prims(int v, int s, vector<vii> &adjlist) { vector<int> dist(v,inf); dist[s] = 0; priority_queue<ii,vector<ii>,greater<ii> > pq; pq.push(ii(0,s)); rep(i,1,v) pq.push(ii(i,inf)); bool inpriorityqueue[v]; rep(i,0,v) inpriorityqueue[i] = true; while(!pq.empty()) { ii top = pq.top(); pq.pop(); int d = top.first,u = top.second; inpriorityqueue[u] = false; trvii(adjlist[u],it) { int v = it->first, weight_u_v = it->second; if(inpriorityqueue[v] && weight_u_v<dist[v]) { dist[v] = weight_u_v; } } } cout << "the shortest distance " << s << " nodes is" << endl; rep(i,0,v) { cout << << " : " << dist[i] << endl; } } int main() { int v,s,edges; printf("enter number of vertices : "); scanf("%d",&v); vector<vii> adjlist(v+1); printf("\nenter source vertex : "); scanf("%d",&s); adjlist[0].push_back(make_pair(1,4)); adjlist[0].push_back(make_pair(7,8)); adjlist[1].push_back(make_pair(0,4)); adjlist[1].push_back(make_pair(2,8)); adjlist[1].push_back(make_pair(7,11)); adjlist[7].push_back(make_pair(0,8)); adjlist[7].push_back(make_pair(1,11)); adjlist[7].push_back(make_pair(8,7)); adjlist[7].push_back(make_pair(6,1)); adjlist[2].push_back(make_pair(1,8)); adjlist[2].push_back(make_pair(3,7)); adjlist[2].push_back(make_pair(8,2)); adjlist[2].push_back(make_pair(5,4)); adjlist[8].push_back(make_pair(2,2)); adjlist[8].push_back(make_pair(7,7)); adjlist[8].push_back(make_pair(6,6)); adjlist[6].push_back(make_pair(7,1)); adjlist[6].push_back(make_pair(5,2)); adjlist[6].push_back(make_pair(8,2)); adjlist[5].push_back(make_pair(6,2)); adjlist[5].push_back(make_pair(2,4)); adjlist[5].push_back(make_pair(3,14)); adjlist[5].push_back(make_pair(4,10)); adjlist[4].push_back(make_pair(3,9)); adjlist[4].push_back(make_pair(5,10)); adjlist[3].push_back(make_pair(2,7)); adjlist[3].push_back(make_pair(5,14)); adjlist[3].push_back(make_pair(4,9)); prims(v, s, adjlist); homecoming 0; }

graph on algorithm implemented :

if had tried debugging have found problem lies line:

trvii(adjlist[u],it)

think u is. in first go around while loop u == s due pq.push(ii(0,s));. in next, , subsequent loops however, u == inf due rep(i,1,v) pq.push(ii(i,inf));.

trying access adjlist[inf] "bad" , results in undefined behaviour (a crash in case).

i suggest debugging algorithm further, perchance simpler test case. step through , watch variables. assumably understand algorithm , states should go through watch variables create sure should be.

c++ algorithm graph stl prims-algorithm

Socket issue c# client to java server -



Socket issue c# client to java server -

this problem, messages sent c# client aren't received server until shutdown socket on client side , server receive info in 1 time time.

c# client side

public static class asynchronousclient { // port number remote device. private const int port = 8888; // manualresetevent instances signal completion. private static manualresetevent connectdone = new manualresetevent(false); private static manualresetevent senddone = new manualresetevent(false); private static manualresetevent receivedone = new manualresetevent(false); public static socket client; // response remote device. private static string response = string.empty; public static void startclient() { // connect remote device. seek { // found remote endpoint socket. // name of // remote device "host.contoso.com". iphostentry iphostinfo = dns.gethostentry("127.0.0.1"); ipaddress ipaddress = iphostinfo.addresslist[0]; ipendpoint remoteep = new ipendpoint(ipaddress, 8888); // create tcp/ip socket. client = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp); // connect remote endpoint. client.beginconnect(remoteep, new asynccallback(connectcallback), client); connectdone.waitone(); // send test info remote device. send(client, "test connection"); sentdown.waitone(); } grab (exception e) { console.writeline(e.tostring()); } } public static void connectcallback(iasyncresult ar) { seek { // retrieve socket state object. socket client = (socket)ar.asyncstate; // finish connection. client.endconnect(ar); console.writeline("socket connected {0}", client.remoteendpoint.tostring()); // signal connection has been made. connectdone.set(); } grab (exception e) { console.writeline(e.tostring()); } } public static void send(socket client, string data) { // convert string info byte info using ascii encoding. byte[] bytedata = encoding.ascii.getbytes(data); // begin sending info remote device. client.beginsend(bytedata, 0, bytedata.length, socketflags.none, new asynccallback(sendcallback), null); } public static void sendcallback(iasyncresult ar) { seek { // retrieve socket state object. // finish sending info remote device. int bytessent = client.endsend(ar); console.writeline("sent {0} bytes server.", bytessent); // signal bytes have been sent. senddone.set(); } grab (exception e) { console.writeline(e.tostring()); } }

java server side

public class connection_to_port extends thread { final static int port = 8888; private socket socket; string message = ""; public static void main(string[] args) { seek { serversocket socketserveur = new serversocket(port); while (true) { socket socketclient = socketserveur.accept(); connection_to_port t = new connection_to_port(socketclient); t.start(); system.out.println("connected client : " + socketclient.getinetaddress()); } } grab (exception e) { e.printstacktrace(); } } public connection_to_port(socket socket) { this.socket = socket; } public void run() { handlemessage(); } public void handlemessage() { seek { bufferedreader in = new bufferedreader(new inputstreamreader(socket.getinputstream())); message = in.readline(); system.out.println(message); } grab (exception e) { e.printstacktrace(); } }

in client have send info server

asynchronousclient.send(asynchronousclient.client, "{myjsondata}");

my client sending, not receive.

the problem is, java server receive nil ! client said it's sent, , see on wireshark that's it's send.

when do asynchronousclient.client.shutdown(socketshutdown.both);

finally see message on server @ same time. if sent 1 message.

the java side trying read line (you using readline).

this method not homecoming until either there end-of-line character, or stream closed.

when shutdown client, in effect, stream closes.

your test message not include end-of-line character, way readline homecoming @ end of stream.

java c# sockets

linux - How to handle files in case-sensitive way in Vagrant on Windows host -



linux - How to handle files in case-sensitive way in Vagrant on Windows host -

on windows 8 i've installed virtualbox + vagrant. used laravel homestead (with ubuntu) box. when running site on vm or running command line expect beingness run on linux , not on windows. found unusual issue:

first folder mappings:

folders: - map: d:\daneaplikacji\easyphp\data\localweb\projects\testprovag\strony to: /home/vagrant/code sites: - map: learn.app to: /home/vagrant/code/my-first-app/public

when run in browser http://learn.app:8000 got right output - page /home/vagrant/code/my-first-app/public same code d:\daneaplikacji\easyphp\data\localweb\projects\testprovag\strony\my-first-app/public clear.

now problem:

in public folder i've created 2 simple files:

file name test (it's empty) , file index.php content:

<?php if (file_exists('test')) { echo "file exists"; } else { echo "file not exists"; }

so run http://learn.app:8000 in browser , output file exists. result wouldn't expect. far know in linux (my box ubuntu) may have files different case in names (in opposite windows) expect got file not exists.

i've tested in vm running php index.php , exact same result file exists 1 time again unexpected.

now did copied 2 files other directory on vm /home/vagrant/tests - directory not mapped using vagrant. when run php index.php file not exists expected result.

to honest doesn't understand it. question - php when using vagrant mapping operating on vm filesystem (in case ubuntu) or on virtual box host filesystem (in case windows). there way create work desired result? know question might bit software related it's connected php , laravel , maybe miss here.

i think issue can solved not using samba or much work.

in windows cmd run:

vagrant plugin install vagrant-winnfsd

it installed plugin nfs windows although @ http://docs.vagrantup.com/v2/synced-folders/nfs.html have clear info nfs doesn't work windows:

windows users: nfs folders not work on windows hosts. vagrant ignore request nfs synced folders on windows.

i modified homestead.yaml file mapping from:

folders: - map: d:\daneaplikacji\easyphp\data\localweb\projects\testprovag\strony to: /home/vagrant/code

to:

folders: - map: d:\daneaplikacji\easyphp\data\localweb\projects\testprovag\strony to: /home/vagrant/code type: "nfs"

(probably if not using homestead.yaml can add together type: nfs, that: config.vm.synced_folder ".", "/vagrant", type: "nfs" in vagrantfile)

now when run

vagrant up

i got 2 or 3 notices admin password (probably windows configuration of nfs - appear when run vagrant up first after adding nfs type) both using url http://learn.app:8000 got case question file not exists , same when run php index.php in box commandline.

note: solution doesn't create can create test , test files in same directory , have them in file system. seems handle file in case sensitive way, if create file in wrong case in app (and later in code want load it/require) notice doesn't work on vagrant linux box (and work on windows wamp , suprised when moving on production).

linux windows virtual-machine vagrant virtualbox