Thursday 15 March 2012

javascript - Get content from URL data by class or ID using JS -



javascript - Get content from URL data by class or ID using JS -

i thinking solution night can't figure out.

i have php code download url content:

function get_data($url) { $ch = curl_init(); $timeout = 5; curl_setopt($ch, curlopt_url, $url); curl_setopt($ch, curlopt_returntransfer, 1); curl_setopt($ch, curlopt_connecttimeout, $timeout); $data = curl_exec($ch); curl_close($ch); homecoming $data; } $data = get_data($url);

and want content divs or whatever class name or id send variable js this:

<script> var info = <?php echo json_encode($data); ?>; alert(data); //alert shows code of downloaded url //$( ".content" ).html( info ); //this line show whole page want specific element/class </script>

how can accomplish this? let's want content of h1 tag class="productmaintitle" "data" variable in javascript ?

any tip appreciated!

depends want do.

1. send relevant fragment of html client-side

see @artm's answer.

2. send html client-side , sort out there

<script> var $data = $("<?php echo $data; ?>"); $data.find("h1.productmaintitle").appendto(".content"); </script>

assume json_encode() unnecessary. if i'm wrong, reinsert.

if want "h1.productmaintitle" fragment less efficient (1), if want farther fragments, viable approach.

javascript php jquery css curl

haskell - Parsing an expression grammar having function application with parser combinators (left-recursion) -



haskell - Parsing an expression grammar having function application with parser combinators (left-recursion) -

as simplified subproblem of parser real language, trying implement parser expressions of fictional language looks similar standard imperative languages (like python, javascript, , so). syntax features next construct:

integer numbers identifiers ([a-za-z]+) arithmetic expressions + , * , parenthesis structure access . (eg foo.bar.buz) tuples (eg (1, foo, bar.buz)) (to remove ambiguity one-tuples written (x,)) function application (eg foo(1, bar, buz())) functions first class can returned other functions , straight applied (eg foo()() legal because foo() might homecoming function)

so complex programme in language is

(1+2*3, f(4,5,6)(bar) + qux.quux()().quuux)

the associativity supposed be

( (1+(2*3)), ( ((f(4,5,6))(bar)) + ((((qux.quux)())()).quuux) ) )

i'm using nice uu-parsinglib applicative parser combinator library.

the first problem intuitive look grammar (expr -> identifier | number | expr * expr | expr + expr | (expr) left-recursive. solve problem using the pchainl combinator (see parseexpr in illustration below).

the remaining problem (hence question) function application functions returned other functions (f()()). again, grammar left recursive expr -> fun-call | ...; fun-call -> expr ( parameter-list ). ideas how can solve problem elegantly using uu-parsinglib? (the problem should straight apply parsec, attoparsec , other parser combinators guess).

see below current version of program. works function application working on identifiers remove left-recursion:

{-# language flexiblecontexts #-} {-# language rankntypes #-} module testexprgrammar ( ) import data.foldable (asum) import data.list (intercalate) import text.parsercombinators.uu import text.parsercombinators.uu.utils import text.parsercombinators.uu.basicinstances info node = numberliteral integer | identifier string | tuple [node] | memberaccess node node | functioncall node [node] | binaryoperation string node node parsefunctioncall :: parser node parsefunctioncall = functioncall <$> parseidentifier {- `parseexpr' right left-recursive -} <*> parseparenthesisednodelist 0 operators :: [[(char, node -> node -> node)]] operators = [ [('+', binaryoperation "+")] , [('*' , binaryoperation "*")] , [('.', memberaccess)] ] sameprio :: [(char, node -> node -> node)] -> parser (node -> node -> node) sameprio ops = asum [op <$ psym c <* pspaces | (c, op) <- ops] parseexpr :: parser node parseexpr = foldr pchainl (parseidentifier <|> parsenumber <|> parsetuple <|> parsefunctioncall <|> pparens parseexpr ) (map sameprio operators) parsenodelist :: int -> parser [node] parsenodelist n = case n of _ | n < 0 -> parsenodelist 0 0 -> plistsep (psymbol ",") parseexpr n -> (:) <$> parseexpr <* psymbol "," <*> parsenodelist (n-1) parseparenthesisednodelist :: int -> parser [node] parseparenthesisednodelist n = pparens (parsenodelist n) parseidentifier :: parser node parseidentifier = identifier <$> psome pletter <* pspaces parsenumber :: parser node parsenumber = numberliteral <$> pnatural parsetuple :: parser node parsetuple = tuple <$> parseparenthesisednodelist 1 <|> tuple [] <$ psymbol "()" instance show node show n = allow shownodelist ns = intercalate ", " (map show ns) showparenthesisednodelist ns = "(" ++ shownodelist ns ++ ")" in case n of identifier -> tuple ns -> showparenthesisednodelist ns numberliteral n -> show n functioncall f args -> show f ++ showparenthesisednodelist args memberaccess f g -> show f ++ "." ++ show g binaryoperation op l r -> "(" ++ show l ++ op ++ show r ++ ")"

looking briefly @ the list-like combinators uu-parsinglib (i'm more familiar parsec), think can solve folding on result of psome combinator:

parsefunctioncall :: parser node parsefunctioncall = foldl' functioncall <$> parseidentifier {- `parseexpr' right left-recursive -} <*> psome (parseparenthesisednodelist 0)

this equivalent alternative some combinator, should indeed apply other parsing libs mentioned.

parsing haskell parsec recursive-descent uu-parsinglib

javascript - X's Replaces O's -



javascript - X's Replaces O's -

i'm making tic tac toe game , im trying prepare bug have now.

when play game , click on o's changes x how can prepare this?

i thought like: if (turn == 0 && ('td') == "") { doesn't work

var newgame = function () { $('td').one('click', function (event) { if (turn == 0) { $(this).text(human); boardcheck(); checkwin(); turn == 1; compmove(); boardcheck(); checkwin(); } }); };

// variables

var human = 'x'; // turn = 0 var computer = 'o'; // turn = 1 var compmove; var turn = 0; // toggles btw 0 , 1 switching turns var boardcheck; // function check value in each cell var a1; // value within each cell var a2; var a3; var b1; var b2; var b3; var c1; var c2; var c3; var checkwin; // function checks board winning combo var xwin = false; // true if x wins var owin = false; // true if o wins var winalert; // function declares winner , restarts game var newgame; var clearboard; // places x or o in box when clicked. toggles. var newgame = function () { $('td').one('click', function (event) { if (turn == 0) { $(this).text(human); boardcheck(); checkwin(); turn == 1; compmove(); boardcheck(); checkwin(); } }); }; // initializes game - maintain after var newgame $(document).ready(function () { newgame(); }); // comp move ai detects if there 2 in row next empty cell , places move there var compmove = function () { if (a1 == "" && ((a3 == "x" && a2 == "x") || (c3 == "x" && b2 == "x") || (c1 == "x" && b1 == "x"))) { $('#a1').text("o"); turn = 0; } else { if (a2 == "" && ((a1 == "x" && a3 == "x") || (c2 == "x" && b2 == "x"))) { $('#a2').text("o"); turn = 0; } else{ if (a3 == "" && ((a1 == "x" && a2 == "x") || (c1 == "x" && b2 == "x") || (c3 == "x" && b3 == "x"))) { $('#a3').text("o"); turn = 0; } else{ if (c3 == "" && ((c1 == "x" && c2 == "x") || (a1 == "x" && b2 == "x") || (a3 == "x" && b3 == "x"))) { $('#c3').text("o"); turn = 0; } else{ if (c1 == "" && ((c3 == "x" && c2 == "x") || (a3 == "x" && b2 == "x") || (a1 == "x" && b1 == "x"))) { $('#c1').text("o"); turn = 0; } else{ if (c2 == "" && ((c3 == "x" && c1 == "x") || (a2 == "x" && b2 == "x"))) { $('#c2').text("o"); turn = 0; } else{ if (b1 == "" && ((b3 == "x" && b2 == "x") || (a1 == "x" && c1 == "x"))) { $('#b1').text("o"); turn = 0; } else{ if (b3 == "" && ((a3 == "x" && c3 == "x") || (b2 == "x" && b1 == "x"))) { $('#b3').text("o"); turn = 0; } else{ if (b2 == "" && ((a3 == "x" && c1 == "x") || (c3 == "x" && a1 == "x") || (b3 == "x" && b1 == "x") || (c2 == "x" && a2 == "x"))) { $('#b2').text("o"); turn = 0; } else{ // if no opp block win, play in 1 of these squares if (b2 == "") { $('#b2').text("o"); turn = 0; } else{ if (a1 == "") { $('#a1').text("o"); turn = 0; } else{ if (c3 == "") { $('#c3').text("o"); turn = 0; } else { if (c2 == "") { $('#c2').text("o"); turn = 0; } else{ if (b1 == "") { $('#b1').text("o"); turn = 0; } } } } } } } } } } } } } } }; // creates function observe in each box after each move boardcheck = function () { a1 = $('#a1').html(); a2 = $('#a2').html(); a3 = $('#a3').html(); b1 = $('#b1').html(); b2 = $('#b2').html(); b3 = $('#b3').html(); c1 = $('#c1').html(); c2 = $('#c2').html(); c3 = $('#c3').html(); }; // creates function observe win or tie checkwin = function () { // checks if x won if ((a1 == a2 && a1 == a3 && (a1 == "x")) || //first row (b1 == b2 && b1 == b3 && (b1 == "x")) || //second row (c1 == c2 && c1 == c3 && (c1 == "x")) || //third row (a1 == b1 && a1 == c1 && (a1 == "x")) || //first column (a2 == b2 && a2 == c2 && (a2 == "x")) || //second column (a3 == b3 && a3 == c3 && (a3 == "x")) || //third column (a1 == b2 && a1 == c3 && (a1 == "x")) || //diagonal 1 (a3 == b2 && a3 == c1 && (a3 == "x")) //diagonal 2 ) { xwin = true; winalert(); } else { // checks if o won if ((a1 == a2 && a1 == a3 && (a1 == "o")) || //first row (b1 == b2 && b1 == b3 && (b1 == "o")) || //second row (c1 == c2 && c1 == c3 && (c1 == "o")) || //third row (a1 == b1 && a1 == c1 && (a1 == "o")) || //first column (a2 == b2 && a2 == c2 && (a2 == "o")) || //second column (a3 == b3 && a3 == c3 && (a3 == "o")) || //third column (a1 == b2 && a1 == c3 && (a1 == "o")) || //diagonal 1 (a3 == b2 && a3 == c1 && (a3 == "o")) //diagonal 2 ) { owin = true; winalert(); } else { // checks tie game if cells filled if (((a1 == "x") || (a1 == "o")) && ((b1 == "x") || (b1 == "o")) && ((c1 == "x") || (c1 == "o")) && ((a2 == "x") || (a2 == "o")) && ((b2 == "x") || (b2 == "o")) && ((c2 == "x") || (c2 == "o")) && ((a3 == "x") || (a3 == "o")) && ((b3 == "x") || (b3 == "o")) && ((c3 == "x") || (c3 == "o"))) { alert("it's tie!"); clearboard(); } } } }; // declares won var winalert = function () { if (xwin == true) { alert("you won!"); clearboard(); // doesn't work } else { if (owin == true) { alert("sorry, lose!"); clearboard(); // doesn't work } } }; // newgame button clears board, restarts game, , resets wins var clearboard = $('#restart').click(function (event) { a1 = $('#a1').text(""); b1 = $('#b1').text(""); c1 = $('#c1').text(""); a2 = $('#a2').text(""); b2 = $('#b2').text(""); c2 = $('#c2').text(""); a3 = $('#a3').text(""); b3 = $('#b3').text(""); c3 = $('#c3').text(""); xwin = false; owin = false; newgame(); window.location.reload(true); // without this, there's bug places multiple 0's on games after first }); // still need fix: // * alert tie game or xwin appears twice // * x's can replace o's // * missed opportunities o win // * never let's human win // * clean logic compmove'

if (turn == 0 && $(this).text() == "") {

javascript jquery tic-tac-toe

matlab - Array filter based on multiple columns -



matlab - Array filter based on multiple columns -

suppose have 4 x n array:

a = [1 2 3 4; ... 2 4 8 9; ... 6 7 9 4; ... 1 8 3 4];

i want filter whole array based on content of first 2 columns.

for example, if want homecoming array rows contain 2 in first 2 columns, reply i'm looking isl

r = [1 2 3 4;... 2 4 8 9];

or, if want homecoming rows containing 1 in first 2 columns, reply i'm looking is...

a = [1 2 3 4;... 1 8 3 4];

i'm sure it's obvious how can in matlab? filtering whole array based on find or evaluation commands (e.g. a == 2) totally fine. it's filtering based on multiple columns in order can't figure out.

to check a given number, apply any along 2nd dimension restricted desired columns, , utilize logical index select desired rows:

cols = [1 2]; %// columns @ val = 1; %// value r = a(any(a(:, cols)==val, 2), :);

if want several values, example, select rows contain either 2 or 3 in columns 1 or 2: utilize ismember instead of ==:

cols = [1 2]; %// columns @ vals = [2 3]; %// values r = a(any(ismember(a(:, cols), vals), 2), :);

if want check if numbers within range:

cols = [1 2]; %// columns @ v1 = 6; %// numbers should greater or equal this... v2 = 8; %// ...and less r = a(any(a(:, cols)>=v1, 2) & any(a(:, cols)<v2, 2), :);

arrays matlab matrix

java - Avoid if/else in constructor - NavigableMap? -



java - Avoid if/else in constructor - NavigableMap? -

i have next code, based on input constructor need initialise values wrapped in simple pojo.. these values constant can see.

however don't if/else build , had read navigablemap alternative holding range values.. thoughts on how improve/clean below or indeed utilize construct?

thanks

private calibrated calibratedvalues; public calibrationproperties(long odnumber) { setcalibratedvalues(odnumber); } private void setcalibratedvalues(long odnumber) { if (odnumber < 762) { this.calibratedvalues = new calibrated(k0, h0, k0_inv, h0_inv, f0); } else if (odnumber < 866) { this.calibratedvalues = new calibrated(k1, h1, k0_inv, h0_inv, f1); } else if (odnumber < 1011) { this.calibratedvalues = new calibrated(k2, h2, k2_inv, h2_inv, f2); } else { this.calibratedvalues = new calibrated(k3, h3, k3_inv, h3_inv, f3); } //two exceptions if (odnumber == 858){ this.calibratedvalues = new calibrated(k2, h2, k2_inv, h2_inv, f2); } if (odnumber == 1005){ this.calibratedvalues = new calibrated(k3, h3, k3_inv, h3_inv, f3); } } public calibrated getcalibratedvalues() { homecoming calibratedvalues; } /** convenience class used hold calibrated values */ static class calibrated { private double[] k; private double[] h; private double[] kinv; private double[] hinv; private double f; calibrated(double[] k, double[] h, double[] kinv, double[] hinv, double f) { this.k = k; this.h = h; this.kinv = kinv; this.hinv = hinv; this.f = f; } public double[] getk() { homecoming k; } public double[] geth() { homecoming h; } ...

you not using if/else in constructors here, have created mill method.

use more meaningful names, if read code after year not know mean - mean constructor parameters , class properties your constructor has big argument list. create within of class mill methods

example:

public static calibrated createsmallcaribration(){ homecoming new calibrated(k0, h0, k0_inv, h0_inv, f0); }

if can create contructor bundle visible. , know each constructor configuration ment be,

java

node.js - MEAN.js not showing in iframe -



node.js - MEAN.js not showing in iframe -

i have display mean.js app within iframe, started simple html file:

<iframe style="height: 100%; width: 100%;" src="http://localhost:3000/#!/workouts"></iframe>

but iframe content empty, can please help me?

got it: app using helmet (https://github.com/evilpacket/helmet) setted deny in x-frame-options. so, in express configuration setted:

app.use(helmet.xframe('allow-from', 'www.mydomain.com'));

and worked

node.js angularjs meanjs

javascript - How can I make this for only one element? -



javascript - How can I make this for only one element? -

this code works spans in page. should set this specific one?

class="snippet-code-js lang-js prettyprint-override"> var next = function(e) { var current = $('.active'); var prev = $('#prev'); pos = $('.active').attr('id'); $("#num").text('(' + pos + '/' + researchplaces.length + ')'); $(current).next().attr("class", "active"); $(current).attr("class", "passive"); e.stoppropagation(); } class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="address"><a id="prev">prev </a> <span id="address" class="active">0 elgin street</span> <span id="address" class="passive">1 elgin street</span> <span id="address" class="passive">2 elgin street</span> <span id="address" class="passive">3 elgin street</span> <span id="address" class="passive">4 elgin street</span> <span id="address" class="passive">5 elgin street</span> <span id="address" class="passive">6 elgin street</span> <span id="address" class="passive">7 elgin street</span> <span id="address" class="passive">8 elgin street</span> <span id="address" class="passive">9 elgin street</span> <a id="next"> next</a> </div>

<div class="container"> <span id="address1" class="passive active">0 elgin street</span> <span id="address2" class="passive">1 elgin street</span> <span id="address3" class="passive">2 elgin street</span> <span id="address4" class="passive">3 elgin street</span> <span id="address5" class="passive">4 elgin street</span> <span id="address6" class="passive">5 elgin street</span> <span id="address7" class="passive">6 elgin street</span> <span id="address8" class="passive">7 elgin street</span> <span id="address9" class="passive">8 elgin street</span> <span id="address10" class="passive">9 elgin street</span> </div>

now js example

$(function(){ var current = $('.active'); var prev = $('#prev'); $('.active').on('click',function(){ alert(this.id); }); });

so if active changes can utilize this in click event. html , js help clarify went wrong. 1 time state pos , researchplace should i'll update you.

javascript jquery

javascript - jQuery Get value from multi dimensional arrays -



javascript - jQuery Get value from multi dimensional arrays -

i can't find match question,

i have task of getting values elements

card record 1 : <input type="text" name="card[][company]" /> <input type="text" name="card[][bank]" /> <input type="text" name="card[][hospital]" /> card record 2 : <input type="text" name="card[][company]" /> <input type="text" name="card[][bank]" /> <input type="text" name="card[][hospital]" />

i want values can pass on controller via ajax (ci)

[0] card[0][company] = abc card[1][bank] = def card[2][hospital] = ghi [1] card[0][company] = abc card[1][bank] = def card[2][hospital] = ghi

i have tried $.each .push , .map can't figure out right manipulation, jquery answers please.

well, can this

var arr = $('input[name^=card]').map(function(){ homecoming { this.name : this.value } }).get(), newarr = []; while(arr.length > 0) newarr.push(arr.splice(0 , 3));

newarr contain want.

javascript jquery arrays

java - Javafx - how to change the behavior of upTableColumn -



java - Javafx - how to change the behavior of upTableColumn -

i have tableview 2 columns (tablecolumn).

i delegated 1 of columns (tablecolumn) "on edit commit" (via scene builder).

when write new value 1 of cells column , press come in i'm getting delegated function.

but, if i'm writing value , click mouse on other cell, value not saved (and delegated function not beingness called) (because didn't press enter).

is there way alter behavior ? there way via scene builder or code ?

thanks

the default textfield behavior requires user presses come in key commit edit. can changed extending tablecell class commit editing on focus change, in this tableview tutorial. precisely, @ implementation of editingcell class , usage in example.

basically, needed text field table cell set focus alter listener phone call commitedit(), in next example:

textfield.focusedproperty().addlistener(new changelistener<boolean>(){ @override public void changed(observablevalue<? extends boolean> arg0, boolean arg1, boolean arg2) { if (!arg2) { commitedit(value); } } });

above mentioned illustration shows how set new table cell type table column in java code can set in fxml too.

java javafx

postgresql - Best way to set an API server using Node.js and Postgres? -



postgresql - Best way to set an API server using Node.js and Postgres? -

i'm new in node.js. i'm trying find out , larn best way set api server, crud (create, read, update , delete) requests.

i've beingness looking around different server frameworks used node.js:

express

restify

hapi

i'm using node-postgres library connecting database , making queries, haven't found guide or illustration using either of previous frameworks set api server postgresql.

i'd thankful point me right direction or show me basic example.

thank you

hapi has best performance. otherwise hope can help you:

http://blog.newrelic.com/2014/08/15/node-js-frameworks-hapi-js-restify-geddy

http://blog.nodeknockout.com/post/34571027029/making-an-api-happy-with-hapi

http://blog.modulus.io/nodejs-and-hapi-create-rest-api

node.js postgresql

linux - Getting awk return value with Java -



linux - Getting awk return value with Java -

writing simple shell command our java application. have no experience in linux shell , need simple command. seek user's active window's process name. question found script follows:

ps -e | grep $(xdotool getwindowpid $(xdotool getwindowfocus)) | grep -v grep | awk '{print $4}'

source:http://unix.stackexchange.com/questions/38867/is-it-possible-to-retrieve-the-active-window-process-title-in-gnome

i able test , print result but. can't value java side. if run simple script like

echo asdasd

i can "asdasd" string fine. understand java can echo commands.

at java side utilize method: private string executecommand(string command) {

stringbuffer output = new stringbuffer(); process p; seek { p = runtime.getruntime().exec(command); p.waitfor(); bufferedreader reader = new bufferedreader(new inputstreamreader(p.getinputstream())); string line = ""; while ((line = reader.readline())!= null) { output.append(line + "\n"); } } grab (exception e) { e.printstacktrace(); } homecoming output.tostring(); }

source: http://www.mkyong.com/java/how-to-execute-shell-command-from-java/

------solved------

solved smasseman's answer, changed command string th next string array,

string[] args = {"/bin/sh","-c",command };

"command" script not filepath gave errors.

you can not utilize pipes when execute java. trick write linux commands , pipes script , execute script java. create script (lets phone call script activewin.sh):

#!/bin/bash ps -e | grep $(xdotool getwindowpid $(xdotool getwindowfocus)) | grep -v grep | awk '{print $4}'

make executable chmod +x activewin.sh can execute script in java p = runtime.getruntime().exec("./activewin.sh");

you of course of study write script file java, execute , remove if want application more "stand alone".

java linux shell unix terminal

c# - how to set limits for datetime in xtracharts devexpress -



c# - how to set limits for datetime in xtracharts devexpress -

i using devexpress xtrachart in in x-axis there date. now, date in x-axis binding database as: y-axis has values

chartcontrol1.datasource=dt;//used datatable chartcontrol1.seriesdatamember = "variablename"; chartcontrol1.seriestemplate.argumentdatamember = "lasttime"; chartcontrol1.seriestemplate.valuedatamembers.addrange(new string[] { "lastvalue" }); chartcontrol1.seriestemplate.changeview(viewtype.line); ((devexpress.xtracharts.xydiagram)(chartcontrol1.diagram)).axisx.label.datetimeoptions.format = datetimeformat.general;

now, datetime in database today date , different hours

but in chart showing below 1 datetime:

how can prepare this, want show today's datetime(and time not 00:00:00) if today range in x-axis must like: startdate in x-axis 1 hr before current datetime , enddate in x-axis 1 hr after current datetime or 1 hr difference

example if current datetime 2014-10-11 10:00:00 in x-axis show 2014-10-11 09:00:00 , 2014-10-11 10:00:00 , 2014-10-11 11:00:00 ..

i tried visualrange , wholerange not working.

it's 2 step process show date , time in scale:

set axis.datetimeoptions.format property datetimeformat.general.

then axis.datetimescaleoptions property custom settings.

(xydiagram)chartcontrol1.diagram).axisx.datetimeoptions.format = datetimeformat.general; (xydiagram)chartcontrol1.diagram).axisx.datetimescaleoptions.gridalignment = devexpress.xtracharts.datetimegridalignment.minute; (xydiagram)chartcontrol1.diagram).axisx.datetimescaleoptions.measureunit = devexpress.xtracharts.datetimemeasureunit.minute;

currently axis.datatimescaleoptions.gridalignment , meaureunit property default set day, able see single info data aggregation operation(sum etc).

refer: devexpress xtracharts showing date only

i want show today's datetime(and time not 00:00:00) if today range in x-axis must like: startdate in x-axis 1 hr before current datetime , enddate in x-axis 1 hr after current date time or 1 hr difference

try tweak range properties, below illustration snippet:

datetime start = datetime.today; xydiagram diagram = (xydiagram)charteditor.diagram; diagram.axisx.wholerange.auto = false; diagram.axisx.visualrange.setminmaxvalues(start.addhours(0), start.addhours(24));

c# charts devexpress

sqlite - Count columns in a table where columns are same and then subtract from a column in another table -



sqlite - Count columns in a table where columns are same and then subtract from a column in another table -

lets pretend have supermarket. got table called sales every record 1 article), if scan 3 articles have 3 rows next columns: articleid , amount amount 1. , have table called articles have columns: articleid , availableamount.

when sale done need count records same in sales table , update availableamount availableamount subtracted sum of each article.

i'm thinking dont know if im thinking right:

update articles set availableamount = availableamount - ( select articleid,count(*) sales grouping articleid having count(*) > 1 ) articleid in(select distinct articleid sales)

this query correct, but

the subquery must homecoming 1 column, having count(*) > 1 not create sense, and

the subquery must homecoming 1 value, need correlated subquery:

update articles set availableamount = availableamount - (select count(*) sales articleid = articles.articleid) articleid in (select articleid sales)

sqlite

php - Laravel 4.2 - Using entrust and confide -



php - Laravel 4.2 - Using entrust and confide -

i using "zizaco/confide": "~4.0@dev" , "zizaco/entrust": "1.2.*@dev".

i have set described in 2 tutorials(confide migrations). furthermore, have created next models:

user:

<?php utilize zizaco\confide\confideuser; utilize zizaco\confide\confide; utilize zizaco\confide\confideeloquentrepository; utilize zizaco\entrust\hasrole; utilize carbon\carbon; utilize illuminate\auth\userinterface; utilize illuminate\auth\reminders\remindableinterface; class user extends confideuser implements userinterface, remindableinterface{ utilize hasrole; /** * user username * @param $username * @return mixed */ public function getuserbyusername( $username ) { homecoming $this->where('username', '=', $username)->first(); } public function joined() { homecoming string::date(carbon::createfromformat('y-n-j g:i:s', $this->created_at)); } public function saveroles($inputroles) { if(! empty($inputroles)) { $this->roles()->sync($inputroles); } else { $this->roles()->detach(); } } public function currentroleids() { $roles = $this->roles; $roleids = false; if( !empty( $roles ) ) { $roleids = array(); foreach( $roles &$role ) { $roleids[] = $role->id; } } homecoming $roleids; } public static function checkauthandredirect($redirect, $ifvalid=false) { // user info $user = auth::user(); $redirectto = false; if(empty($user->id) && ! $ifvalid) // not logged in redirect, set session. { session::put('loginredirect', $redirect); $redirectto = redirect::to('user/login') ->with( 'notice', lang::get('user/user.login_first') ); } elseif(!empty($user->id) && $ifvalid) // valid user, want redirect. { $redirectto = redirect::to($redirect); } homecoming array($user, $redirectto); } public function currentuser() { homecoming (new confide(new confideeloquentrepository()))->user(); } public function getreminderemail() { homecoming $this->email; } }

role:

<?php utilize zizaco\entrust\entrustrole; class role extends entrustrole { public function validateroles( array $roles ) { $user = confide::user(); $rolevalidation = new stdclass(); foreach( $roles $role ) { // create sure theres valid user, check role. $rolevalidation->$role = ( empty($user) ? false : $user->hasrole($role) ); } homecoming $rolevalidation; } }

permission:

<?php utilize zizaco\entrust\entrustpermission; class permission extends entrustpermission { public function preparepermissionsfordisplay($permissions) { // available permissions $availablepermissions = $this->all()->toarray(); foreach($permissions &$permission) { array_walk($availablepermissions, function(&$value) use(&$permission){ if($permission->name == $value['name']) { $value['checked'] = true; } }); } homecoming $availablepermissions; } /** * convert input array savable array. * @param $permissions * @return array */ public function preparepermissionsforsave( $permissions ) { $availablepermissions = $this->all()->toarray(); $preparedpermissions = array(); foreach( $permissions $permission => $value ) { // if checkbox selected if( $value == '1' ) { // if permission exists array_walk($availablepermissions, function(&$value) use($permission, &$preparedpermissions){ if($permission == (int)$value['id']) { $preparedpermissions[] = $permission; } }); } } homecoming $preparedpermissions; } }

furthermore, seed database in origin values, hence created follwing seeders:

usertableseeder:

<?php class userstableseeder extends seeder { public function run() { db::table('users')->delete(); $users = array( array( 'username' => 'admin', 'email' => 'admin@example.org', 'password' => hash::make('admin'), 'confirmed' => 1, 'confirmation_code' => md5(microtime().config::get('app.key')), 'created_at' => new datetime, 'updated_at' => new datetime, ), array( 'username' => 'moderator', 'email' => 'moderator@example.org', 'password' => hash::make('moderator'), 'confirmed' => 1, 'confirmation_code' => md5(microtime().config::get('app.key')), 'created_at' => new datetime, 'updated_at' => new datetime, ), array( 'username' => 'user', 'email' => 'user@example.org', 'password' => hash::make('user'), 'confirmed' => 1, 'confirmation_code' => md5(microtime().config::get('app.key')), 'created_at' => new datetime, 'updated_at' => new datetime, ) ); db::table('users')->insert( $users ); } }

rolestableseeder:

<?php class rolestableseeder extends seeder { public function run() { db::table('roles')->delete(); $adminrole = new role; $adminrole->name = 'adminrole'; $adminrole->save(); $standrole = new role; $standrole->name = 'userrole'; $standrole->save(); $modrole = new role; $modrole->name = 'modrole'; $modrole->save(); $user = user::where('username','=','admin')->first(); $user->attachrole( $adminrole ); $user = user::where('username','=','user')->first(); $user->attachrole( $standrole ); $user = user::where('username','=','moderator')->first(); $user->attachrole( $modrole ); } }

permissionstableseeder:

<?php class permissionstableseeder extends seeder { public function run() { db::table('permissions')->delete(); $permissions = array( array( // 1 'name' => 'manage_users', 'display_name' => 'manage users' ), array( // 2 'name' => 'manage_roles', 'display_name' => 'manage roles' ), array( // 3 'name' => 'standart_user_role', 'display_name' => 'standart_user_role' ), ); db::table('permissions')->insert( $permissions ); db::table('permission_role')->delete(); $role_id_admin = role::where('name', '=', 'admin')->first()->id; $role_id_mod = role::where('name', '=', 'moderator')->first()->id; $role_id_stand = role::where('name', '=', 'user')->first()->id; $permission_base = (int)db::table('permissions')->first()->id - 1; $permissions = array( array( 'role_id' => $role_id_admin, 'permission_id' => $permission_base + 1 ), array( 'role_id' => $role_id_admin, 'permission_id' => $permission_base + 2 ), array( 'role_id' => $role_id_mod, 'permission_id' => $permission_base + 1 ), array( 'role_id' => $role_id_mod, 'permission_id' => $permission_base + 3 ), array( 'role_id' => $role_id_stand, 'permission_id' => $permission_base + 3 ), ); db::table('permission_role')->insert( $permissions ); } }

however, when running db:seed:

$ php artisan db:seed ************************************** * application in production! * ************************************** wish run command? y seeded: userstableseeder {"error":{"type":"symfony\\component\\debug\\exception\\fatalerrorexception","me ssage":"class user cannot extend trait zizaco\\confide\\confideuser","file" :"c:\\xampp\\htdocs\\laravel_project\\laravel-application\\app\\models\\user.php","line ":11}}

any recommendations doing wrong in seeding?

i appreciate answers!

update

after changing usermodel next exception:

$ php artisan db:seed ************************************** * application in production! * ************************************** wish run command? y seeded: userstableseeder {"error":{"type":"symfony\\component\\debug\\exception\\fatalerrorexception","me ssage":"call undefined method user::where()","file":"c:\\xampp\\htdocs\\larav el_project\\laravel-application\\app\\database\\seeds\\rolestableseeder.php","line":21} }

update 2

when changing user model to(as @marcinnabiałek proposed):

class user extends eloquent implements userinterface, remindableinterface{ utilize confideuser; utilize hasrole;

i getting next error:

$ php artisan db:seed ************************************** * application in production! * ************************************** wish run command? y seeded: userstableseeder seeded: rolestableseeder [errorexception] trying property of non-object db:seed [--class[="..."]] [--database[="..."]] [--force]

you have clear message here - cannot extend trait (message clear plenty think: class user cannot extend trait zizaco\confide\confideuser).

instead of:

class user extends confideuser implements userinterface, remindableinterface{ utilize hasrole;

you should use:

class user implements userinterface, remindableinterface{ utilize confideuser; utilize hasrole;

edit

class user should extend eloquent (this set default) should be:

class user extends eloquent implements userinterface, remindableinterface{ utilize confideuser; utilize hasrole;

php laravel laravel-4 seeding

PHP - cannot find correct regex -



PHP - cannot find correct regex -

i trying figure out regex match 012 wound't match 0. if string 1 character , character equals 0 should false should work values 012, 023, 01, 05, 120.

i tried doesn't want.

^(?=[^0])(?=[0-9]{1,3})$

any idea?

^(?!0$)\d+$

try this.see demo.

http://regex101.com/r/dz1vt6/27

regex

android - AndEngine Popup Scene Error -



android - AndEngine Popup Scene Error -

i making brick breaker game , want show popup when ball hits ground. however, tried both set children scene or create popup object , add together entity. both of methods have same errors show below.

could 1 give me advice?

thank you!

public scene onloadscene() { this.mengine.registerupdatehandler(new fpslogger()); scene.registerupdatehandler(new iupdatehandler() { public void reset() { } public void onupdate(final float psecondselapsed) { if(ball.collideswith(paddle)) { ball.bouncewithrectangle(paddle); } else if (ball.gety() >= game.getcamera_height() - 30) { scene.setbackground(new colorbackground(255f, 0f, 0f)); scene.setignoreupdate(true); **scene.setchildscene(pausescene(), false, true, true); //scene.gettoplayer().addentity(popup);** } }

updated pausescene():

public scene pausescene() { scene pausescene = new scene(1); texture mtexture = new texture(256, 256, textureoptions.bilinear); textureregionfactory.setassetbasepath("popup/"); textureregion texttextregion = textureregionfactory.createfromasset(mtexture, this, "canvas.jpg", 0, 0); sprite box = new sprite(0, 0, texttextregion); pausescene.gettoplayer().addentity(box); homecoming pausescene; }

============================================================ other try:

public dialog oncreatedialog() { alertdialog.builder builder = new alertdialog.builder(this.getapplicationcontext()); builder.setmessage("hello"); alertdialog alert = builder.create(); homecoming alert; }

android popup andengine

php - Array - Undefined offset even if i already defined it -



php - Array - Undefined offset even if i already defined it -

i have 2 pages, page 1 contains array this:

$error=array(); $error[]='first value'; $error[]='second value'; $error[]='third value';

page 2 utilize array values:

include 'page1.php'; echo '<p>'.$error[0].'</p>'; echo '<p>'.$error[1].'</p>'; echo '<p>'.$error[2].'</p>';

it should work, instead keeps showing error:

notice: undefined offset: 0 notice: undefined offset: 1 notice: undefined offset: 2

any idea?

from updated question, shows

$error=array(); if( !empty($_post['email']) && isset($_post['email']) ){ if (!filter_var($email, filter_validate_email)) { $error[] = 'emailul nu este valid!'; }else{ $email=$_post['email']; } }else{ $error[]='utilizatorul este obligatoriu!'; }

in included file, should check conditional logic doing var_dumps

var_dump($_post) , 'email' index.

perhaps status 'email' exists not beingness satisfied!

edited, showing original below...

often you'll find it's less error-prone utilize foreach loop.

foreach($error $err) { echo '<p>'.$err.'</p>'; }

also, may seek using instead of include file.php, using require('file.php') or require_once('file.php')

php arrays

Outlook to excel VBA stops searching body after first match -



Outlook to excel VBA stops searching body after first match -

i wrote code pull info outlook excel, , 80% working :) pull info not whole email.

i receive emails in same format pricing , other info on them. these purchase orders have more 1 line usually. in format:

item number : 00001

vendor sales order number :

vendor material number :

sap material number :

vendor description :

sap description :

vendor quantity : 30.000 ea

sap quantity : 30.000 ea

quantity uom : ea

vendor delivery date : 20.09.2014

sap delivery date : 20.09.2014

action request :

following details not match po line item 00001

vendor cost : usd 0.00 1 ea

sap cost : usd 0.01 1 ea

item number : 00002

vendor sales order number :

vendor material number :

sap material number :

vendor description :

sap description :

vendor quantity : 70.000 ea

sap quantity : 70.000 ea

quantity uom : ea

vendor cost : usd 3.90 1 ea

sap cost : usd 3.90 1 ea

vendor delivery date : 20.09.2014

sap delivery date : 20.09.2014

action request :

quantity , requested date matched po. item 00002

as can see code pulling multiple things these emails have same origin string. after pulls line 1, code moves next email without searching entire body of email farther matches. how can prepare this? stuck :)

option explicit sub copytoexcel() dim xlapp object dim xlwb object dim xlsheet object dim olitem outlook.mailitem dim vtext variant dim stext string dim vitem variant dim long dim rcount long dim bxstarted boolean const strpath string = "excel filepath here" 'the path of workbook if application.activeexplorer.selection.count = 0 msgbox "no items selected!", vbcritical, "error" exit sub end if on error resume next set xlapp = getobject(, "excel.application") if err <> 0 application.statusbar = "please wait while excel source opened ... " set xlapp = createobject("excel.application") bxstarted = true end if on error goto 0 'open workbook input info set xlwb = xlapp.workbooks.open(strpath) set xlsheet = xlwb.sheets("sheet1") 'process each selected record each olitem in application.activewindow.selection stext = olitem.body vtext = split(stext, chr(13)) 'find next empty line of worksheet rcount = xlsheet.usedrange.rows.count + 1 'check each line of text in message body = ubound(vtext) 0 step -1 rcount = rcount if instr(1, vtext(i), "purchase order :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("a" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "vendor :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("b" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "item number :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("c" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "vendor quantity :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("d" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "sap quantity :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("e" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "quantity uom :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("f" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "vendor cost :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("g" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "sap cost :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("h" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "vendor delivery date :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("i" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "sap delivery date :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("j" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "text here:") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("k" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "text here:") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("l" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "text here:") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("m" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "text here") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("n" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "text here") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("o" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "text here") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("p" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "text here") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("q" & rcount) = trim(vitem(1)) end if next xlwb.save next olitem xlwb.close savechanges:=true if bxstarted end if set xlapp = nil set xlwb = nil set xlsheet = nil set olitem = nil end sub

code: option explicit sub copytoexcel() dim xlapp object dim xlwb object dim xlsheet object dim olitem object dim vtext variant dim stext string dim vitem variant dim long dim j long dim rcount long dim bxstarted boolean const strpath string = "excel filepath here" 'the path of workbook if application.activeexplorer.selection.count = 0 msgbox "no items selected!", vbcritical, "error" exit sub end if on error resume next set xlapp = getobject(, "excel.application") if err <> 0 application.statusbar = "please wait while excel source opened ... " set xlapp = createobject("excel.application") bxstarted = true end if on error goto 0 'open workbook input info set xlwb = xlapp.workbooks.open(strpath) set xlsheet = xlwb.sheets("sheet1") 'process each selected record j = 1 application.activeexplorer.selection.count set olitem = application.activeexplorer.selection.item(j) if olitem.class = 43 stext = olitem.body vtext = split(stext, chr(13)) 'find next empty line of worksheet rcount = xlsheet.usedrange.rows.count + 1 'check each line of text in message body = ubound(vtext) 0 step -1 if instr(1, vtext(i), "purchase order :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("a" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "vendor :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("b" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "item number :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("c" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "vendor quantity :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("d" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "sap quantity :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("e" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "quantity uom :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("f" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "vendor cost :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("g" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "sap cost :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("h" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "vendor delivery date :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("i" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "sap delivery date :") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("j" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "text here:") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("k" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "text here:") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("l" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "text here:") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("m" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "text here") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("n" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "text here") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("o" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "text here") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("p" & rcount) = trim(vitem(1)) end if if instr(1, vtext(i), "text here") > 0 vitem = split(vtext(i), chr(58)) xlsheet.range("q" & rcount) = trim(vitem(1)) end if next xlwb.save rcount = rcount + 1 end if next j xlwb.close savechanges:=true if bxstarted end if set xlapp = nil set xlwb = nil set xlsheet = nil set olitem = nil end sub

this should work. reason outlook stop execution without error if encounters non-mail item in selection.

copy , paste whole thing (even dim statements).

excel vba email outlook extract

objective c - why lowercaseString of NSString is not released after the original NSString object is released? -



objective c - why lowercaseString of NSString is not released after the original NSString object is released? -

please check next code:

cfuuidref uuid=cfuuidcreate(kcfallocatordefault); nsstring *struuid=(nsstring *)cfuuidcreatestring(kcfallocatordefault,uuid); nsstring *loweruuid=[struuid lowercasestring]; nslog(@"struuid retaincount:%tu",[struuid retaincount]); cfrelease(struuid); cfrelease(uuid); nslog(@"loweruuid retaincount:%tu",[loweruuid retaincount]); nslog(@"loweruuid:%@",loweruuid);

run code in non-arc project, output be:

struuid retaincount:1 loweruuid retaincount:1 loweruuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

lowercasestring property of nsstring, definition is:

@property (readonly, copy) nsstring *lowercasestring;

so it's reasonable infer if original nsstring object released, lowercasestring property released in nsstring's dealloc method. why in code above, loweruuid still there after original struuid released?

first of all, standard disclaimer: don't -retaincount. has many caveats utilize , can't trusted useful.

that said: inference not describe what's happening. when inquire struuid -lowercasestring, you're not getting sort of "child" object. resulting lowercased string independent object, own internal retain count. (it's possible original string retain own reference lowercased string, that's not concern.)

in code snippet, under standard memory management conventions, happening in general terms statement [struuid lowercasestring] returns "autoreleased" object. if original string released, string returned remains valid either: (a) at least until autorelease pool cleaned or (b) after lastly actual access, depending on arc status on project.

objective-c nsstring

go - How do I dynamically iterate through a package? -



go - How do I dynamically iterate through a package? -

this first week go, please forgive ignorance ;). come in peace python. building simple calculator add-on , subtraction currently.

my addition.go file looks this:

package calculator type add together struct{} func (h add) first(x int) int { x += 5 homecoming x } func (h add) second(x int) int { x += 10 homecoming x }

the layout of subtraction.go file looks similar addition.go , future features multiplication.go , division.go similar. run these have:

package main import ( "fmt" "github.com/mytester/calculator" ) type calc interface { first(x int) int second(x int) int } func main() { x := 10 var calc := &calculator.add{} = i.first(x) fmt.println(x) fmt.println(i.first(x)) fmt.println(i.second(x)) fmt.println("next method...") b := &calculator.sub{} = b fmt.println(x) fmt.println(i.first(x)) fmt.println(i.second(x)) // iterate through rest of calculator methods }

this seems verbose, add together more , more features multiplication, etc. there way find methods of calculator & iterate on of them? i've looked through reflect documentation there doesn't seem way this. order in run doesn't matter....eg subtraction can run before addition.

go not provide feature want. there no mechanism introspect contents of packages. reason compiler keeps functions , variable in executable referenced somewhere. if never explicitly utilize function, won't in executable. iterating on perchance incomplete set of symbols pointless , hence not implemented.

you create array containing objects of types want operate on , iterate on if solves problem.

go

ruby on rails - How to invoke a postgres function using arel? -



ruby on rails - How to invoke a postgres function using arel? -

i have postgres function called 'move_to_end' i'm invoking using find_by_sql below:

def move_to_end self.class.find_by_sql ["select move_to_end(?)", id] end

i'd replace find_by_sql statement arel call, examples i've found require arel work table.

any thoughts on how accomplish appreciated.

you can using namedfunctions in arel. however, still have utilize arel_table reference table column in query. 1 possible workaround alias underscore:

# == schema info # # table name: solution # # solution_id :integer not null, primary key # body :text # class solution class << self alias_method :_, :arel_table def only_checked _.project(checked(_[:solution_id])) end def checked arel::nodes::namedfunction.new('checked', [query]) end end end solution.only_checked.to_sql # -> select checked("solution"."solution_id") "solution";

ruby-on-rails rails-activerecord arel

java - Create an gradle configuration with a filetree (not an archive) -



java - Create an gradle configuration with a filetree (not an archive) -

i have ear format project multiple war modules.

using standard ear mechanisms dependencies:

dependencies { deploy project(path: "war1", configuration: "archives") deploy project(path: "war2", configuration: "archives") }

i can create exploded ear output kinda looks this:

exploded-ear |-- war1.war \-- war2.war

however want is

exploded-ear |-- exploded-war1 \-- exploded-war2

i've been looking while , configuration mechanisms in gradle don't seem allow not archive. want define configuration references filetree (which location of exploded war in subprojects) ear (and consequently exploded ear) contain exploded wars.

java gradle war ear exploded

entity framework - How to use LINQ Group By with Count -



entity framework - How to use LINQ Group By with Count -

i want convert next sql query entity framework + linq query. there 3 tables brands, products , productreviews. products table has brandid fk , productreviews has productid fk.

select top 5 b.id, b.shortname, count(r.id) totalreviews productsreviews r inner bring together products p on r.productid = p.id inner bring together brands b on p.brandid = b.id grouping b.id, b.shortname order totalreviews desc

basically, want display top 5 brands based on reviews posted products of brands. want output below:

id shortname totalreviews ----------------------------------------- 76 adidas 61 120 yamaha 29 109 tommy hilfiger 26 61 mothercare 25 31 haier 22

pseudocode

var results = ( r in productsreviews bring together p in products on r.productid equals p.id bring together b in brands on p.brandid equals b.id grouping c new { b.id, b.shortname } grp select new { id = grp.key.id, shortname = grp.key.shortname, totalreviews = grp.count()} ) .orderby(x=>x.totalreviews).take(5);

linq entity-framework group-by

database - update error in wcf service application -



database - update error in wcf service application -

i'm getting error while updating row in database.

an exception of type 'system.data.oledb.oledbexception' occurred in system.data.dll not handled in user code

additional information: syntax error in update statement.

failed invoke service. possible causes: service offline or inaccessible; client-side configuration not match proxy; existing proxy invalid. refer stack trace more detail. can seek recover starting new proxy, restoring default configuration, or refreshing service.

this update code:

public string updateinventory(string name, int quantity) { string strmessage = string.empty; string sql; //create connection object oledbconnection oleconn = new oledbconnection(connstring); oleconn.open(); //update row sql = "update product set quantity attribute = '" + quantity + "' name = '" + name + "'"; oledbcommand cmd = new oledbcommand(sql, oleconn); int rowsaffected = (int)cmd.executenonquery(); if(rowsaffected > 0) { strmessage = name + "details updated succesfully"; } else { strmessage = name + "details not updated successfully"; } oleconn.close(); homecoming strmessage; }

but if update decimal cost , string description same codes. goes well. getting codes when updating quantity.

your column name quantity attribute has space in it, causing syntax error. can utilize brackets around column name resolve this. also, quantity int, , you're trying utilize string in sql command. it's int in table, don't need ' around value either, without knowing table's schema that's guess.

the biggest problem code is vulnerable sql injection attacks. can guard against using parameterized queries. parameterized queries have added benefit of handling required quoting of values you, based on type of individual parameters.

finally it's considered best practice utilize using block connection, take care of closing , disposing connection when using block exited, if error occurs.

here's illustration wraps of up:

try { using (oledbconnection oleconn = new oledbconnection(connstring)) { oleconn.open(); //update row sql = "update product set [quantity attribute] = ? name = ?"; oledbcommand cmd = new oledbcommand(sql, oleconn); cmd.commandtype = commandtype.text; cmd.parameters.add("@quantity", oledbtype.int).value = quantity; cmd.parameters.add("@name", oledbtype.varchar).value = name; int rowsaffected = (int)cmd.executenonquery(); if(rowsaffected > 0) { strmessage = name + "details updated succesfully"; } else { strmessage = name + "details not updated successfully"; } } } grab (exception ex) { strmessage = string.format("update error: {0}", ex.message); }

note oledb question mark used placeholder parameters, order in add together parameters of import - must match order of placeholders in query string.

the resulting sql (assuming quantity attribute int, , quantity = 20 , name = "sample":

update product set [quantity attribute] = 20 name = 'sample'

as final recommendation wrapped code in try-catch block if exception thrown caught , handled. unhandled exceptions can reveal info programme shouldn't revealed (as can give potential hackers more info refine attempts compromise system). since wcf service, depending on configuration exception details may or may not returned client, unhandled exception can bring service downwards , fault client's channel service.

database wcf

mongodb - How to make MapReduce work with HDFS -



mongodb - How to make MapReduce work with HDFS -

this might sound stupid question. might write mr code can take input , output hdfs locations , don't need worry parallel computing powerfulness of hadoop/mr. (please right me if wrong here).

however if input not hdfs location taking mongodb info input - mongodb://localhost:27017/mongo_hadoop.messages , running mappers , reducers , storing info mongodb, how hdfs come picture. mean how can sure 1 gb or sized big file first beingness distributed on hdfs , parallel computing beingness done on it? direct uri not distribute info , need take bson file instead, load on hdfs , give hdfs path input mr or framework smart plenty itself?

i sorry if above question stupid or not making sense @ all. new big info much excited dive domain.

thanks.

you describing dbinputformat. input format reads split external database. hdfs gets involved in setting job, not in actual input. there dboutputformat. input dbinputformat splits logical, eg. key ranges.

read database access apache hadoop detailed explanation.

mongodb hadoop mapreduce

How to determine with JGit which branches have been merged to master? -



How to determine with JGit which branches have been merged to master? -

how utilize jgit determine branches have been merged master?

i want equivalent of normal git command:

git branch -a --merged

is possible in jgit?

revwalk#ismergedinto() can used determine if commit merged another. is, ismergedinto returns true if commit given in first argument ancestor of sec given commit.

class="lang-java prettyprint-override">revwalk revwalk = new revwalk( repository ); revcommit masterhead = revwalk.parsecommit( repository.resolve( "refs/heads/master" ); revcommit otherhead = revwalk.parsecommit( repository.resolve( "refs/heads/other-branch" ); if( revwalk.ismergedinto( otherhead, masterhead ) ) { ... } revwalk.release();

to list of branches listbranchescommandcan used:

class="lang-java prettyprint-override">list<ref> branches = git.wrap( repository ).listbranches().setlistmode( listmode.all ).call();

jgit

Javascript/HTML error “the value of the property “selectReason” is null or undefined, not a function object -



Javascript/HTML error “the value of the property “selectReason” is null or undefined, not a function object -

hi new javascript , html , wondering if help me understand why error keeps occuring. basic thought have dropdownlist populated several options. when client selects alternative onchange event fires write value of selected alternative textarea. when debug message above have included relevant snippets of code below:

function selectreason() { var selectindex = document.getelementbyid("selectmessage").selectedindex; var selecttext = document.getelementbyid("selectmessage").value; document.getelementbyid("txt").value = selecttxt; } <tr style="display: none; visibility: hidden" id=sel> <td width="60%" align=left>please select reason</td> <td width="40%" align=left> <select id="selectmessage" onchange="selectreason()" style="width: 425px"></select> </td> </tr>

maybe help you

<html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> </head> <body> <table> <tbody> <tr> <td> <select name="" id="selectmessage"> <option value="red">red</option> <option value="gree">green</option> <option value="blue">blue</option> </select> </td> </tr> </tbody> </table> <textarea name="" id="txt" cols="30" rows="10"> </textarea> <script type="text/javascript"> $(document).on('ready', function(){ $('#selectmessage').on('change', function(){ var val = $(this).val(); var txt = $('#txt'); txt.val(val); }); }); </script> </body> </html>

hope :)

javascript html

ios - How can i meassure short distance inside buildings -



ios - How can i meassure short distance inside buildings -

i'm new here im learning xcode , swift myself , things going well.

i wanted inquire best way (and exact way) measure short distances let's 10 meters within of building cant utilize gps want results in millimeters or centimeters.

thank time guys

calculating distances based on device motion , using gyroscope, accelerometer, , other internal sensors impossible.

there few reason why see link explanation...

https://www.youtube.com/watch?v=_q_8d0e3tdk&list=uuj_umpod8ph_ecyn_xexruq&spfreload=10

ios iphone swift

networking - Monitor ppp0 traffic usage with Linux -



networking - Monitor ppp0 traffic usage with Linux -

hey i'm developing 3g connected device raspberry pi. mobile provider allows me utilize 50 mb/month.

this device installed somewhere nobody can have physically access to. concern avoid info traffic overuse. need tool measure accumulated traffic going through (in , out) ppp0 interface in order disconnect interface until next month if 50mb limit reached.

i tried ifconfig since have disconnections counter rested @ each reconnection.

i tried ntop , iftop understood these tools measuring real-time traffic.

i'm looking kind of cumulative traffic use, can find on smartphones.

any idea?

take in iptraf :)

i'm not sure if go in plenty detail relatively lightweight, though may not wise go heavy on raspberry pi processor. seek looking around netflow or snmp based solutions, though think might overkill.

good luck!

linux networking raspberry-pi 3g

entity framework - Naming conventions for Code First migrations -



entity framework - Naming conventions for Code First migrations -

we using code first migrations maintain our database , model in sync. @ moment have version number name migration doesn't work out. problem multiple migrations same name created different developers independent of each other local database. led weird behavior imigrationmetadata.id different because of time stamp classes partial same name.

what way go phone call these migrations? examples ridiculous oversimplified: e.g. adding property readers result in migration addreaders. or should migrations broken downwards these little changes? instead of having accumulate changes 1 big migration. if there dependencies?

thanks!

entity-framework ef-code-first code-first-migrations

bit manipulation - abs function for float value in java -



bit manipulation - abs function for float value in java -

i need create function abs float bitwise operators, function homecoming float value.

i can't utilize < or >.

i seek

(float)((int)f ^ ((int)f>>31)) - ((int)f>>31)

but -2.5 value 2.0, it's not correct.

can help me?

you can this

float abs = float.intbitstofloat(float.floattointbits(x) & 0x7fffffff);

java bit-manipulation bitwise-operators

oop - Why can't we change access modifier while overriding methods in C#? -



oop - Why can't we change access modifier while overriding methods in C#? -

in c#, can not alter access modifier while overriding method base of operations class. e.g.

class base of operations { **protected** string foo() { homecoming "base"; } } class derived : base of operations { **public** override string foo() { homecoming "derived"; } }

this not valid in c#, give compile time error.

i want know reason, why it's not allowed. there technical problem or can lead not consistent in terms of access restriction???

changing access modifier of method in derived type pointless that's why it's not allowed:

case 1: override more restrictive access

this case not allowed due next situation:

class base of operations { public virtual void a() {} } class derived: base of operations { protected override void a() }

now say:

list<base> list; list.add(new derived()); list[0].a() //runtime access exception

case 2: overriding less restrictive access modifier

what point? hide method , done. if calls through base of operations type not have access new method defined in derived type consistent how author of base of operations type wanted things have no "right" alter that. if want specifics of derived class phone call derived class, in case new method works fine.

edit: expanding case 2

what trying in case 2, have means alter accessibility of method (virtual or not) if want alter accessibility.

consider next code:

public class base of operations { protected virtual string whoami() { homecoming "base"; } } public class derived : base of operations { public new virtual string whoami() { homecoming "derived"; } } public class anotherderived : derived { public override string whoami() { homecoming "anotherderived"; } }

with new keyword have created new virtual method derived class same name , signature. take note allowed declare new method virtual, class deriving derived allowed override it.

what not allowed have following:

base of operations newbaseobject = new derived(); newbaseobject.whoami() //whoami not accessible.

but fact has nil beingness able override whoami() or not. whatever case situation can never because base not declare public whoami().

so in theoretical c# derived.whoami() override base.whoami() there no practical benefits in doing because never able phone call virtual method base of operations class anyways, new alternative meets requirements.

i hope makes clearer.

c# oop access-modifiers

javascript - Converting base64 to Blob and Blob to base64 using FileReader in PhantomJS -



javascript - Converting base64 to Blob and Blob to base64 using FileReader in PhantomJS -

i have angular controller, should work images. have watcher property file in scope. if property contain array of files, these files (only first file) should read filereader , converted base64 string , added page. this:

$scope.$watch('file', function (files) { if (files && files.length > 0) { if (files[0].type && files[0].type.match('image.*')) { var reader = new filereader(); reader.onload = function (e) { render(e.target.result); }; reader.readasdataurl(files[0]); } } });

and render function:

function render (src) { var image = new image(); image.addeventlistener('load', function () { if (image.width < min_size || image.height < min_size) { $scope.error = $filter('localize')('uploaderwindow_imagesizeerror'); $scope.$apply(); } else { new global.icropper('original-image', { gap: 0, keepsquare: true, image: src, preview: ['cropped-image'] }); } }); image.addeventlistener('error', function () { $scope.error = $filter('localize')('uploaderwindow_selectimage'); $scope.$apply(); }); image.src = src; };

icropper should create img element in dom base64 in src attribute. problem is, have unit test functionality. test case:

it('should render new image file input', function () { var imagedata = image.split(',')[1], imagetype = image.split(',')[0].replace('data:', '').replace(';base64', ''), file = base64toblob(imagedata, imagetype); expect(originalimage.lastelementchild).tobe(null); runs(function () { $scope.file = [file]; $scope.$apply(); }); waitsfor(function () { homecoming originalimage.lastelementchild; }, 'waiting_original_form'); runs(function () { expect(originalimage.lastelementchild.src).tobe(image); }); });

variable image contains valid base64 string, originalimage.lastelementchild - img element, should created icropper. body of base64toblob function:

function base64toblob (b64data, contenttype) { var binary = atob(b64data.replace(/\s/g, '')), binarylength = binary.length, buffer = new arraybuffer(binarylength), view = new uint8array(buffer); (var = 0; < binarylength; i++) { view[i] = binary.charcodeat(i); } homecoming new blob([view], {type: contenttype}); }

this test passed in chrome, not in phantomjs:

timeout: timed out after 5000 msec waiting waiting_original_form

i think, it's because load event image not fired, error fired instead. don't understand why? know, blob not defined in phantomjs, utilize polyfill: https://github.com/eligrey/blob.js

javascript blob phantomjs karma-runner filereader

vbscript - How to run vbs in Internet Explorer -



vbscript - How to run vbs in Internet Explorer -

i'm trying run vbscript in net explorer, doesnt seem work. works when create .vbs file , double click, not on browser.

dim strwebsite strwebsite = "www.site.org" if pingsite( strwebsite ) wscript.echo "web site " & strwebsite & " , running!" else wscript.echo "web site " & strwebsite & " down!!!" end if function pingsite( mywebsite ) dim intstatus, objhttp set objhttp = createobject( "winhttp.winhttprequest.5.1" ) objhttp.open "get", "http://" & mywebsite & "/", false objhttp.setrequestheader "user-agent", "mozilla/4.0 (compatible; myapp 1.0; windows nt 5.1)" on error resume next objhttp.send intstatus = objhttp.status on error goto 0 if intstatus = 200 pingsite = true else pingsite = false end if set objhttp = nil end function

what right way ?

hot ms press: vbscript no longer supported in ie11 border mode (as knew, other browsers (that don't run on ms renderer) didn't run vbs anyway)

the 'correct' way translate javascript (no seriously, can still mock it's deprecated , advised update old code now), isn't hard since technique originated @ ms. you'd still head-request , check status-no.

this should started: http head request in javascript/ajax?

edit (addressing comment): don't count on reliably setting useragent though (that, above script, seems more thing of past):

https://bugzilla.mozilla.org/show_bug.cgi?id=627942 set request header in javascript xmlhttprequest , setrequestheader in ie returns error

edit2: see/think want somehow differentiate app: myapp 1.0; (in logs perhaps?). if that's case, might want add together custom headers instead: how can add together custom http header ajax request js or jquery?

also, server-logs (by default) pick on get-string, might want use/add-to (so wouldn't have alter log-format if custom header wouldn't show up)?

internet-explorer vbscript

Python - Find second smallest number -



Python - Find second smallest number -

i found code on site find sec largest number:

def second_largest(numbers): m1, m2 = none, none x in numbers: if x >= m1: m1, m2 = x, m1 elif x > m2: m2 = x homecoming m2

source: get sec largest number in list in linear time

is possible modify code find sec smallest number? example

print second_smallest([1, 2, 3, 4]) 2

the function can indeed modified find sec smallest:

def second_smallest(numbers): m1, m2 = float('inf'), float('inf') x in numbers: if x <= m1: m1, m2 = x, m1 elif x < m2: m2 = x homecoming m2

the old version relied on python 2 implementation detail none sorted before else (so tests 'smaller'); replaced using float('inf') sentinel, infinity tests larger other number. ideally original function should have used float('-inf') instead of none there, not tied implementation detail other python implementations may not share.

demo:

>>> def second_smallest(numbers): ... m1, m2 = float('inf'), float('inf') ... x in numbers: ... if x <= m1: ... m1, m2 = x, m1 ... elif x < m2: ... m2 = x ... homecoming m2 ... >>> print second_smallest([1, 2, 3, 4]) 2

python

java - How I can read some specific data from a file that contain different types of data? -



java - How I can read some specific data from a file that contain different types of data? -

i need write info several companies binary file; info includes name of companies (string), year of incorporation (int), , revenue year (double). write info not problem me, don't know how read specific info binary file; example, if have name of company, need homecoming the other info company. far, know read info or maybe line line in binary file. can suggest class or method need utilize so?

you should read serialization/deserialization of objects in java. serialize list of companies (e.g. arraylist<company> companies) deserialize it, can utilize same list of companies 1 time again in code search through list find company want. optionally, can utilize map<string, company> jb nizet suggests.

java io

performance - Fortran - copying matrices efficiently -



performance - Fortran - copying matrices efficiently -

there couple places in code re-create sparse matrices 100,000,000 elements. issue coming coping matrices in loop called around 1000 times , coping matrix takes 2 seconds (it takes hr finish copying taking amount of time). re-create matrices using equal sign (i.e. a=b). utilize next initialize matrix

data a/ myzp * 0.0/

which takes time execute, 'myzp' elements in matrix , 'a' matrix.

my question there more efficient way re-create matrix in fortran using equal sign?

update: here code in question taking 2 seconds,

call cpu_time(t1) = b phone call cpu_time(t2)

where , b both matrices.

performance matrix copy fortran

javascript - Why do I get a Bad request when I run server.js and client.js and access localhost? -



javascript - Why do I get a Bad request when I run server.js and client.js and access localhost? -

i new node.js

i trying utilize pub/sub faye nodemodule create publish/subscribe web application.

i have next files , folders: dependencies in node_modules folder, sever.js file, , client.js

my server.js contains next code:

var http = require('http'), faye = require('faye'); var server = http.createserver(), bayeux = new faye.nodeadapter({mount: '/'}); bayeux.attach(server); server.listen(8000);

as client.js file, contains next code:

var faye = require('faye') var client = new faye.client('http://localhost:8000/'); client.subscribe('/messages', function(message) { alert('got message: ' + message.text); }); client.publish('/messages', { text: 'hai!' })

i go terminal , run node server.js , node client.js

when go browser , run localhost:8000, bad request.

why getting this? suspecting don't have page display something. please point out me missing.

thanks.

you're getting error because you've mounted faye @ /. if seek browsing /, server expecting faye client, not normal http request.

there browser client example shows how connect faye mounted @ /faye. can pass in request handler http.createserver() allows handle request before faye does, in case want respond particular request.

javascript node.js faye

javascript - On input change event? -



javascript - On input change event? -

when using jquery .change on input event fired when input loses focus

in case, need create phone call service (check if value valid) input value changed. how accomplish this?

updated clarification , example

examples: http://jsfiddle.net/pxfunc/5kpej/

method 1. input event

in modern browsers utilize input event. event fire when user typing text field, pasting, undoing, anytime value changed 1 value another.

in jquery this

$('#someinput').bind('input', function() { $(this).val() // current value of input field. });

starting jquery 1.7, replace bind on:

$('#someinput').on('input', function() { $(this).val() // current value of input field. });

method 2. keyup event

for older browsers utilize keyup event (this fire 1 time key on keyboard has been released, event can give sort of false positive because when "w" released input value changed , keyup event fires, when "shift" key released keyup event fires no alter has been made input.). method doesn't fire if user right-clicks , pastes context menu:

$('#someinput').keyup(function() { $(this).val() // current value of input field. });

method 3. timer (setinterval or settimeout)

to around limitations of keyup can set timer periodically check value of input determine alter in value. can utilize setinterval or settimeout timer check. see marked reply on question: jquery textbox alter event or see fiddle working illustration using focus , blur events start , stop timer specific input field

javascript jquery html

Cordova File api : getFile issue in android -



Cordova File api : getFile issue in android -

environment : android

within app im creating file @ location "/data/data/com.my.app/changes/123456789/123456789.json" , have cross checked file exists using custom cordova android plugin.

when trying access file using cordova file api shown below. api fails giving 1000 code.

var path = "/changes/123456789/123456789.json" window.requestfilesystem(localfilesystem.persistent, 0, function(filesystem){ console.log('in got fs'); filesystem.root.getfile(path,{create:true, exclusive: false}, function(fileentry){ console.log('gotfileentry'); }, function(err){ console.log('gotfileentry fail'); console.log('err.code'); console.log(err.code); } ); }, function(){ console.log('fail'); } );

im getting error code "1000" believe "file not found".

as per new plugin docs path file should relative filesystem root. think issue way im passing file path.

the same working when tested on ios device, issue android.

please allow me know im going wrong. im totally stuck. help highly appreciated.

thanks in advance.

hi after lot of digging cordova file api , help post , able access files in android.

used

window.resolvelocalfilesystemurl(cordova.file.datadirectory, function(dir) { console.log("got main dir",dir); dir.getfile("log.txt", {create:true}, function(file) { console.log("got file", file); }); });

to file entry in android. works fine ios also.

android cordova cordova-plugins cordova-3.5

php - User admin status isn't being remembered (admin area disappears after a while) -



php - User admin status isn't being remembered (admin area disappears after a while) -

i'm new php , decided play around cookies on site. added cookies login scheme keeps user logged in 1 year after log in. works fine.

however, don't know how create cookies remember users set admin status in database. there bug admins logged in aren't able view admin area after while though still logged in. ideas be?

login code:

$password=md5($_request['password']); $username=mysql_escape_string($_request['username']); $hour = time() + 60*60*24*30; setcookie("username_cookie", $username, $hour); setcookie("password_cookie", $password, $hour); $query = $mario->db->query("select * `" . dbname . "`.`users` `username` = '" . addslashes($_request['username']) . "' && `password` = '" . md5($_request['password']) . "'"); if($mario->db->numrows($query) > 0) { // success have user! $results = $mario->db->fetch($query); $_session['accountloggedin'] = true; $_session['username'] = $results['username']; $_session['userid'] = $results['userid']; setcookie("marioruns_loggedin", true, time()+3600*24*364,"/" ); /* expire in 1 year */ setcookie("marioruns_username", $results['username'], time()+3600*24*364,"/" ); /* expire in 1 year */ setcookie("marioruns_userid", $results['userid'], time()+3600*24*364,"/" ); /* expire in 1 year */

config code:

if(isset($_cookie["marioruns_loggedin"]))$_session['accountloggedin'] = true; if(isset($_cookie["marioruns_username"]))$_session['username'] = $_cookie["marioruns_username"]; if(isset($_cookie["marioruns_userid"]))$_session['userid'] = $_cookie["marioruns_userid"];

session_start(); included admin status isn't beingness stored anywhere in code, called database when user loads profile page (where admin area is)

edit:

i have feeling code displays admin area on profile page, line of code:

<?php if(($_session['isstaff']) || ($_session['isadmin'])) {?> --- admin area code ---

maybe session has expired? not sure.

php cookies

java - How connect to cassandra cluster via 192.168.x.x ip addres? -



java - How connect to cassandra cluster via 192.168.x.x ip addres? -

this question has reply here:

can't connect cassandra - nohostavailableexception 2 answers

here simple programme test connection cassandra:

package testjava.db.cassandra; import com.datastax.driver.core.cluster; import com.datastax.driver.core.session; public class connectiontester { public static void main (string[] args) { session session = null; seek { cluster cluster = cluster.builder().addcontactpoint("192.168.1.2").build(); session = cluster.connect("myspace"); system.out.println(session.getstate()); } grab (exception ex) { ex.printstacktrace(); } { if (session != null) { session.close(); } } } }

when tun get:

com.datastax.driver.core.exceptions.nohostavailableexception: host(s) tried query failed (tried: /192.168.1.2:9042 (com.datastax.driver.core.transportexception: [/192.168.1.2:9042] cannot connect)) @ com.datastax.driver.core.controlconnection.reconnectinternal(controlconnection.java:199) @ com.datastax.driver.core.controlconnection.connect(controlconnection.java:80) @ com.datastax.driver.core.cluster$manager.init(cluster.java:1199) @ com.datastax.driver.core.cluster.init(cluster.java:154) @ com.datastax.driver.core.cluster.connect(cluster.java:230) @ com.datastax.driver.core.cluster.connect(cluster.java:263) @ testjava.db.cassandra.connectiontester.main(connectiontester.java:11) @ sun.reflect.nativemethodaccessorimpl.invoke0(native method) @ sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:57) @ sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43) @ java.lang.reflect.method.invoke(method.java:606) @ com.intellij.rt.execution.application.appmain.main(appmain.java:134)

when alter localhost 192.168.1.2 every thing works. ipconfig windows command returns:

ethernet adapter local area connection: description . . . . . . . . . . . . . : realtek pcie gbe family controller physical address. . . . . . . . . . . : 40-61-86-7c-4b-0f dhcp enabled. . . . . . . . . . . . . : yes autoconfiguration enabled . . . . . . : yes ipv4-address. . . . . . . . . . . . . : 192.168.1.2(preffered) subnet mask . . . . . . . . . . . . . : 255.255.255.0 default gateway . . . . . . . . . . . : 192.168.1.1 dhcp-server . . . . . . . . . . . . . : 192.168.1.1 dns-servers . . . . . . . . . . . . . : 192.168.1.1

so clear ip address 192.168.1.2

important

yes can remain with localhost or 127.0.0.1 wana know why illustration above not work. when specify 192.168.1.2 address , run application on virtual machine not work too, when ping command works.

configure rpc_address in cassandra.yaml point address client utilize connect cassandra.

these 3 addresses configurable in cassandra.yaml.

listen address - ip address other cassandra nodes utilize talk node. if on cloud, internal ip address here performance.

rpc address - address client connects to, 1 want configure ip accessible client machine.

broadcast address - if using multiple info centers or aws regions, not nodes have access each other via internal ip. can specify external ip address nodes in different info centers can still talk each other. in many cases don't need setting @ all, default hear address.

java windows-7 cassandra ip datastax-java-driver