Tuesday 15 March 2011

java - messageReceived not called -



java - messageReceived not called -

i've created class called messagehandler:

@override public void initchannel(socketchannel ch) throws exception { ch.pipeline().addlast( new logginghandler(loglevel.info), new gameserverhandler()); ch.pipeline().addlast("protobufhandler", new messagehandler()); }

also, added messagereceiver function, can't override documentation says because gives me error:

public class messagehandler extends simplechannelinboundhandler<object> { // @override public void messagereceived(channelhandlercontext ctx, object msg) { system.out.println(msg); // super.messagereceived(ctx, msg); } @override public void exceptioncaught(channelhandlercontext ctx, throwable cause) { cause.printstacktrace(); ctx.close(); } @override protected void channelread0(channelhandlercontext arg0, object arg1) throws exception { // todo auto-generated method stub } }

but messagereceived function never called:

info: [id: 0xbb603bfd, /127.0.0.1:54206 => /127.0.0.1:5000] active oct 07, 2014 10:48:49 pm io.netty.handler.logging.logginghandler logmessage info: [id: 0xbf711f5f, /127.0.0.1:54205 => /127.0.0.1:5000] received(383b) // message printed netty logger, not function.

i netty 4.x method need override , set system.out.println(...) stuff in channelread0(...). in netty 5 messagereceived(...).

java netty

c# - How to store meta data in a SQL Server database to differentiate it from other databases? -



c# - How to store meta data in a SQL Server database to differentiate it from other databases? -

i have scenario need show many databases kind of database, done querying see if database has 4 tables:

select case count(*) when 4 'true' else 'false' end sys.tables upper(name) in ('a', 'b', 'c', 'd')

if returns true right db , should show in list. question is, other alternatives there storing sort of meta info access developer, c# decide more (instead of querying every single db) , accurately (someone might add together tables) if right database?

sql server objects have got extended properties associated them purpose. can set extended properties. covered in link http://technet.microsoft.com/en-us/library/ms190243(v=sql.105).aspx.

sp_addextendedproperty @name='isofinteresttome', @value=1

will create extended property of name , value on current database.

c# sql-server database metadata

plsql - Sync between two tables and show the result in an oracle function -



plsql - Sync between two tables and show the result in an oracle function -

i making oracle function sync values between 2 tables , intention show string show how many rows affected , displays when user execute function.

my function creation this

create or replace function weltesadmin.dum_mst_sync(projname in varchar2) homecoming number num_rows number; begin merge master_drawing dst using (select weight_dum, head_mark_dum dummy_master_drawing) src on (dst.head_mark = src.head_mark_dum) when matched update set dst.weight = src.weight_dum dst.project_name = src.project_name_dum , dst.project_name = projname; dbms_output.put_line( sql%rowcount || ' rows merged' ); end;

if execute begin part in toad or sql developer can see how many rows affected. target collect function procedure , when user wants sync tables need run procedure projname value supplied specific project.

please help me on how improve code, best regards

you can utilize sql%rowcount number of rows affected merge. add together next statement in code after merge :

dbms_output.put_line( sql%rowcount || ' rows merged' );

to homecoming value, declare number variable , assign sql%rowcount value it. , homecoming value. :

function ....... homecoming number ....... num_rows number; ...... begin merge.... num_rows := sql%rowcount; homecoming num_rows; end;

and, don't need procedure execute function. can execute in sql :

select function(project_name) dual /

update since op trying utilize dml within function, need create autonomous transaction able perform dml without raising ora-14551.

you utilize directive pragma autonomous_transaction. run function independent transaction able perform dml without raising ora-14551. however, remember, results of dml committed outside of scope of parent transaction. if have single transaction, utilize workaround suggested. add, pragma autonomous_transaction; after return statement before begin.

create or replace function weltesadmin.dum_mst_sync( projname in varchar2) homecoming number num_rows number; pragma autonomous_transaction; begin merge master_drawing dst using (select weight_dum, head_mark_dum dummy_master_drawing ) src on (dst.head_mark = src.head_mark_dum) when matched update set dst.weight = src.weight_dum dst.project_name = src.project_name_dum , dst.project_name = projname; num_rows := sql%rowcount; commit; homecoming num_rows; end; /

oracle plsql

tags - How to manually push stack entry into vim tagstack? -



tags - How to manually push stack entry into vim tagstack? -

just title says: "how manually force stack entry vim tagstack?"

here problem: have been using gtags/global + unite.vim plugins while (btw, these 2 plugins awesome!), failed automatically insert tag entry tagstack. there way prepare it?

in confidential lh-tags plugin, have lh#tags#jump() function utilize inject tags , jump them.

i know there bug happens sometimes, of time, works enough.

nb: lh-tags depends on 2 other plugins, see addon-info file.

vim tags

java - VS-Android produces "wrong" names when linking to shared libraries -



java - VS-Android produces "wrong" names when linking to shared libraries -

i'm using vs-android build ndk program. have 2 libraries, "bridge" , "utils", , first 1 uses sec one. both libraries compile succesfully , files named correctly libbridge.so , libutils.so. however, when seek load files, unsatisfiedlinkerror saying libbridge.so cannot access liblibutils. why trying search liblibutils?

here's java code utilize load libraries:

static { system.loadlibrary("utils"); // loads ok system.loadlibrary("bridge"); // found causes unsatisfiedlinkerror }

the exact error is:

java.lang.unsatisfiedlinkerror: dlopen failed: not load library "liblibutils" needed "libbridge.so"; caused library "liblibutils" not found

both library files located in same folder:

(projectfolder)/libs/armeabi-v7a/libbridge.so (projectfolder)/libs/armeabi-v7a/libutils.so

now, in visual studio, relevant output of linking phase of libutils.so this:

-o e:/ndkproject/debug/armeabi-v7a/libutils.so -lc -lm -llog -lgcc -wl,-soname,libutils

and relevant output of libbridge.so:

-o e:/ndkproject/debug/armeabi-v7a/libbridge.so -le:/ndkproject/debug/armeabi-v7a -lutils -lc -lm -llog -lgcc -wl,-soname,libbridge

the project properties libutils.so this:

target name: libutils 'soname' setting: $(targetname)

and libbridge.so:

target name: libbridge 'soname' setting: $(targetname) additional dependencies: -lutils

i'm baffled. "lib" come when bridge library tries utilize utils library? utils library load succesfully, , bridge library if don't link utils library , comment out calls stuff in utils library.

so far, i've tried alter target name "utils" instead of "libutils", doesn't work. i've tried utilize lib$(targetname) soname setting, doesn't work either.

i don't know why log mentions liblibutils, code should changed if want work on typical android system. reason libutils.so part of standard distribution, , sits in /system/lib. loadlibrary() , native loader, /system/lib takes precedence on app-specific lib directory, , libutils.so never had chance load. hence, unsatisfiedlinkerror inevitable.

use more unique name utils library, , loader happy.

java android c++ android-ndk vs-android

Empty objects using app.post and AngularJS + mongoose on node.js -



Empty objects using app.post and AngularJS + mongoose on node.js -

my rest api posting empty objects.

i getting value req.body.name

if log console.log(req.body.name); value on console.

post: { name: 'typing name', status: null } typing name

so workflow between frontend (angular.js), form , backend (node.js, express, mongoose) seems work. post value, empty object in mongodb.

{"_id":"543a50a974de6e2606bd8478","__v":0}

app.post('/api/offers', function (req, res){ var offer; console.log("post: "); console.log(req.body); console.log(req.body.name); offer = new offermodel({ name: req.body.name, value: req.body.value, title: req.body.title, content: req.body.content, }); offer.save(function (err) { if (!err) { homecoming console.log("created offer" + req.body.name); } else { homecoming console.log(err); } }); homecoming res.send(offer); });

and here model:

var offerschema = mongoose.schema({ offer : { name : string, value : string, title : string, content : string, image : string, start : string, end : string, targets : string, beacons : string, published : string } }); var offermodel = mongoose.model('offer', offerschema);

schema incorrect, must this:

var offerschema = mongoose.schema({ name : string, value : string, title : string, content : string, image : string, start : string, end : string, targets : string, beacons : string, published : string });

node.js angularjs mongodb express mongoose

sql - Sturctured Query Language -



sql - Sturctured Query Language -

create table customer( custno number(10) constraint foo primary key, custname character(15), city character(15), phone number(10)); create table invoice( invo number(10) constraint inv primary key, invdate date(10), constarint c references customer(custno));

i cannot able create sec table , having uncertainty of info type date , if neglected attribute(invdate) still cannot able create sec table.reason please.

create table client ( custno int constraint foo primary key ,custname character(15) ,city character(15) ,phone int ) go create table invoice ( invo int constraint inv primary key constraint ck references customer(custno) ,invdate date )

sql

c++ - What exception is raised in C by GCC -fstack-check option -



c++ - What exception is raised in C by GCC -fstack-check option -

as per gcc documentation

-fstack-check

generate code verify not go beyond boundary of stack. note switch not cause checking done; operating scheme must that. switch causes generation of code ensure operating scheme sees stack beingness extended.

my assumption code generate exception allow os know. when using c language need know exception beingness generated code.

google not helping much. close came know generates storage_error exception in case of ada language (reference).

i working on sort of little os/scheduler need grab exception. using c/c++.

my gcc version 3.4.4

it doesn't generate exception directly. generates code which, when stack enlarged more 1 page, generates read-write access each page in newly allocated region. that's all does. example:

extern void bar(char *); void foo(void) { char buf[4096 * 8]; bar(buf); }

compiles (with gcc 4.9, on x86-64, @ -o2) to:

foo: pushq %rbp movq $-32768, %r11 movq %rsp, %rbp subq $4128, %rsp addq %rsp, %r11 .lpsrl0: cmpq %r11, %rsp je .lpsre0 subq $4096, %rsp orq $0, (%rsp) jmp .lpsrl0 .lpsre0: addq $4128, %rsp leaq -32768(%rbp), %rdi phone call bar leave ret

orq $0, (%rsp) has no effect on contents of memory @ (%rsp), cpu treats read-write access address anyway. (i don't know why gcc offsets %rsp 4128 bytes during loop, or why thinks frame pointer necessary.) theory os can notice these accesses , appropriate if stack has become large. posix-compliant operating system, delivery of sigsegv signal.

you may wondering how os can notice such thing. hardware allows os designate pages of address space inaccessible; effort read or write memory in pages triggers hardware fault os can process sees fit (again, posix-compliant os, delivery of sigsegv). can used place "guard area" past end of space reserved stack. that's why 1 access per page sufficient.

what -fstack-check meant protect from, clear, situation "guard area" little - perhaps 1 page - allocating big buffer on stack moves stack pointer past area , part of accessible ram. if programme happens never touch memory within guard area, won't prompt crash, scribble on whatever other part is, causing delayed-action malfunction.

c++ c exception gcc

.net - Salesforce API not available for this partner or organisation -



.net - Salesforce API not available for this partner or organisation -

i new salesforce , had created trial account on site. trying run sample salesforce .net toolkit given here

now when run next code

using system; using system.collections.generic; using system.configuration; using system.linq; using salesforce.common; using salesforce.common.models; using salesforce.force; using system.threading.tasks; using system.dynamic; namespace consoleapplication3 { class programme { #pragma warning disable 618 private static readonly string securitytoken = configurationsettings.appsettings["securitytoken"]; private static readonly string consumerkey = configurationsettings.appsettings["consumerkey"]; private static readonly string consumersecret = configurationsettings.appsettings["consumersecret"]; private static readonly string username = configurationsettings.appsettings["username"]; private static readonly string password = configurationsettings.appsettings["password"] + securitytoken; private static readonly string issandboxuser = configurationsettings.appsettings["issandboxuser"]; #pragma warning restore 618 static void main() { seek { var task = runsample(); task.wait(); } grab (exception e) { console.writeline(e.message); console.writeline(e.stacktrace); var innerexception = e.innerexception; while (innerexception != null) { console.writeline(innerexception.message); console.writeline(innerexception.stacktrace); innerexception = innerexception.innerexception; } } } private static async task runsample() { var auth = new authenticationclient(); // authenticate salesforce console.writeline("authenticating salesforce"); var url = issandboxuser.equals("true", stringcomparison.currentcultureignorecase) ?"https://test.salesforce.com/services/oauth2/token":https://login.salesforce.com/services/oauth2/token"; await auth.usernamepasswordasync(consumerkey, consumersecret, username, password, ".net- api-client", url); console.writeline("connected salesforce"); var client = new forceclient(auth.instanceurl, auth.accesstoken, auth.apiversion); // retrieve accounts console.writeline("get accounts"); var qry = "select id, name account"; var accts = new list<account>(); var totalsize = 0; seek { queryresult<account> results = await client.queryasync<account>(qry); totalsize = results.totalsize; console.writeline("queried " + totalsize + " records."); accts.addrange(results.records); var nextrecordsurl = results.nextrecordsurl; if (!string.isnullorempty(nextrecordsurl)) { console.writeline("found nextrecordsurl."); while (true) { queryresult<account> continuationresults = await client.querycontinuationasync<account>(nextrecordsurl); totalsize = continuationresults.totalsize; console.writeline("queried additional " + totalsize + " records."); accts.addrange(continuationresults.records); if (string.isnullorempty(continuationresults.nextrecordsurl)) break; //pass nextrecordsurl client.queryasync request next set of records nextrecordsurl = continuationresults.nextrecordsurl; } } } grab (exception e) { console.writeline(e.message); } console.writeline("retrieved accounts = " + accts.count() + ", expected size = " + totalsize); var inp = console.read(); } private class business relationship { public const string sobjecttypename = "account"; public string id { get; set; } public string name { get; set; } } } }

on running above code exception message api not enabled organisation or partner, on execution of line queryresult<account> continuationresults = await client.querycontinuationasync<account>(nextrecordsurl);

i have update app.config contain consumer key, secret key, token , username , password. consumer key , secret key connected app has next configuration

what wrong?

you using trial account, doesn't include api acceess, can sign free developer edition business relationship includes api access.

.net salesforce cloud toolkit

c++ - Simplify GTest case with repeated sequence of operations -



c++ - Simplify GTest case with repeated sequence of operations -

i need test whether sequence of operations repeatedly invoked mycontroller different values. below code related that, how can simplify repeated block calls same operations different values?

class mycontrollertest : public ::testing::test { protected: mycontrollertest() : m_mycontroller(m_databroker, m_eventbroker) { } testing::mockdatabroker m_databroker; testing::mockeventbroker m_eventbroker; mycontroller m_mycontroller; }; test_f(mycontrollertest, configuresequence) { { insequence dummy; expect_call(m_databroker, prepare()); expect_call(m_databroker, setitem(data::id, sp::item_1)); expect_call(m_databroker, end()); expect_call(m_eventbroker, dispatchevent(events::add, _)); m_mycontroller.event(events::added); expect_call(m_databroker, prepare()); expect_call(m_databroker, setitem(data::id, sp::item_2)); expect_call(m_databroker, end()); expect_call(m_eventbroker, dispatchevent(events::add, _)); m_mycontroller.event(events::added); expect_call(m_databroker, prepare()); expect_call(m_databroker, setitem(data::id, event::sp::item_3)); expect_call(m_databroker, end()); expect_call(m_eventbroker, dispatchevent(events::add, _)); m_mycontroller.event(events::added); expect_call(m_databroker, prepare()); expect_call(m_databroker, setitem(data::id, event::sp::item_4)); expect_call(m_databroker, end()); expect_call(m_eventbroker, dispatchevent(events::add, _)); m_mycontroller.event(events::added); expect_call(m_databroker, prepare()); expect_call(m_databroker, setitem(data::id, event::sp::item_5)); expect_call(m_databroker, end()); expect_call(m_eventbroker, dispatchevent(events::add, _)); m_mycontroller.event(events::added); m_mycontroller.start(); } }

a for loop sufficient

const vector<...> items = {event::sp::item_1, event::sp::item_2, ...}; (const auto& item : items) { expect_call(m_databroker, prepare()); expect_call(m_databroker, setitem(data::id, sp::item_1)); expect_call(m_databroker, end()); expect_call(m_eventbroker, dispatchevent(events::add, _)); m_mycontroller.event(events::added); } m_mycontroller.start();

there's nil special expect_call macros. underlying function calls on mock object m_databroker.

c++ googletest

oracle - SQL query that returns a subset of table plus column containing count for whole table -



oracle - SQL query that returns a subset of table plus column containing count for whole table -

i have 1 table named people (sex, age, weight) listed here:

sex age weight m 10 81 f 21 146 m 32 179 f 40 129 f 58 133

i have next info returned (sex, age, weight, count(*) sexcount people age < 35):

sex age weight sexcount m 10 81 2 f 21 146 3 m 32 179 2

i have found answers work if want homecoming people in table (count without group).

but have not found reply if want sexcount include total count whole table...and not total count returned subset. in other words, want returned info include people less 35 years old, want sexcount include count people in table regardless of age.

anyone know query homecoming info want table illustration above? using oracle if makes difference.

i tried using sql phrase in query:

count(*) over(partition sex) sexcount

but counted number in query results, , not in whole table require (and explained above). thanks.

you're looking single column on output built using different criteria rest of group. no matter sql system, need invoke sec record-set.

thankfully, since you're not looking aggregate query, can done single subquery on list.

select p.sex, p.age, p.weight, t.sexcount people p inner bring together (select sex, count(*) sexcount people grouping sex) t on p.sex = t.sex p.age < 35;

sql oracle

php - Add html element between elements in sequence generated from range -



php - Add html element between elements in sequence generated from range -

newb here trying write simple function generate range of numbers (or letters) comma separated gennumeric(1,10,3); homecoming 1, 4, 7, 10 instead of 14710

code:

function gennumeric($numstart, $numend, $numstep){ foreach (range($numstart, $numend, $numstep) $numsequence){ echo $numsequence; } }

no need loop in case, can utilize implode() outright:

function gennumeric($numstart, $numend, $numstep){ echo implode(', ', range($numstart, $numend, $numstep)); } gennumeric(1, 10, 3);

or returned value:

function gennumeric($numstart, $numend, $numstep){ homecoming implode(', ', range($numstart, $numend, $numstep)); } echo gennumeric(1, 10, 3);

php html arrays range sequence

Postgresql function creating ERROR: return type mismatch in function declared to return name -



Postgresql function creating ERROR: return type mismatch in function declared to return name -

almost burning out writing post lastly resort...

hi all, looking help first function need create. read understand need add together function header , footer set of sql commands create function.

i have view have created works fine... here code it

create view invoice_v select customer.firstname, lastname, customer_addresses.address, orders.order_id, order_date, order_total, order_details.product_id, quantity, unitprice, product.product_name customer, customer_addresses, orders, order_details, product customer.customer_id = customer_addresses.customer_id , customer.customer_id = orders.customer_id , orders.order_id = order_details.order_id , product.product_id = order_details.product_id; select firstname, lastname, address, order_id, order_date, product_id, product_name, quantity, unitprice, order_total invoice_v order_id = 02;

what create view invoice details order_id 2.

i need similar thing function. im not sure how done.

this tried do... failed, im sorry if seems extremely stupid, i'm new this...

create function invoiceforprint() returns name ' select customer.firstname, lastname, customer_addresses.address, orders.order_id, order_date, order_total, order_details.product_id, quantity, unitprice, product.product_name customer, customer_addresses, orders, order_details, product customer.customer_id = customer_addresses.customer_id , customer.customer_id = orders.customer_id , orders.order_id = order_details.order_id , product.product_id = order_details.product_id; ' language sql;

the code above gives me error

error: homecoming type mismatch in function declared homecoming name detail: final statement must homecoming 1 column. context: sql function "invoiceforprint"

i don't know parameter supposed utilize return. help on matter, much appreciated.

sorry not near postgres db untested.

what after called table function, there illustration here http://www.postgresql.org/docs/9.1/static/sql-createfunction.html

create function invoiceforprint() returns table(firstname text , lastname text , address text , order_id int , order_date date , order_total numeric , product_id int , quantity numeric , unitprice numeric, , product_name text ) $$ select customer.firstname , lastname , customer_addresses.address , orders.order_id , order_date , order_total , order_details.product_id , quantity , unitprice , product.product_name customer, customer_addresses, orders, order_details, product customer.customer_id = customer_addresses.customer_id , customer.customer_id = orders.customer_id , orders.order_id = order_details.order_id , product.product_id = order_details.product_id; $$ language sql;

function postgresql

jquery - Class not being added to element -



jquery - Class not being added to element -

i can't figure out why class isn't beingness added selected td element.

example of date cell in jquery datepicker table...

<td class=" " data-handler="selectday" data-event="click" data-month="9" data-year="2014"> <a class="ui-state-default" href="#">1</a> </td>

what i'm trying jquery...

<script> var datelist = [ 1, 10, 2014 ]; $("td[data-month='" + datelist[1] + "'][data-year='" + datelist[2] + "']") .filter(function() { homecoming $(this).text() === datelist[0]; }).addclass("cal-selected-date"); </script>

any advice? thanks.

you need homecoming result in filter:

return $(this).trim() === datelist[0];

edit:

since not selecting a td instead, need add together .trim() trim off whitespace. , lastly not to the lowest degree either need convert both number or remove single =

return $(this).text().trim() == datelist[0];

or

return number($(this).text().trim()) === datelist[0];

jquery

playframework - How to download Play! Framework dependencies before test phase? -



playframework - How to download Play! Framework dependencies before test phase? -

i have webjar dependencies (requirejs, jquery, angular etc.) play 2.3.x download target folder before test phase can utilize them in jasmine unit tests. dependencies defined in build.sbt , downloaded in dist phase; jasmine tests run in test phase cannot utilize them.

is there way download or dependencies in play! 2.3.x before test phase? utilize maven build , can configure custom activator tasks (if there any) run before test phase.

alternative configure jasmine tests run during verify phase, these unit tests , them run in test phase.

i go with

activator update activator stage activator test

command "update" download dependencies, "stage" generate project files target directory without generating zip bundle (i utilize jenkins deployment after running tests) , run tests.

playframework

.net - How to read multilines from text file in c# -



.net - How to read multilines from text file in c# -

i have text file contains user records.in text file 1 user record nowadays in 3 lines of text file.now per requirement have read first 3 lines 1 user, process , insert database , next 3 lines sec user , on..

here code have used single line reading text files..

if (system.io.file.exists(location) == true) { using (streamreader reader = new streamreader(location)) { while ((line = reader.readline()) != null) { line = line.trim(); } } }

please help me read multi-lines , in case 3 lines text file ..

thanks..

you like:

if (system.io.file.exists(location) == true) { var lines=file.readalllines(location); int usersnumber = lines.count() / 3; for(int i=0; < usersnumber; i++){ var firstfield=lines[i*3]; var secondfield=lines[i*3 +1]; var thirdfield=lines[i*3 +2]; dostuffs(firstfield,secondfield,thirdfield); } if(lines.count() > usersnumber *3) //in case there'd spare lines left dosomethingelsefrom(lines, index=(usersnumber*3 +1)); }

you're reading lines of file, counting how many users have (group of 3), each grouping you're retrieving associate info, , in end you're processing grouping of 3 fields related same user.

c# .net text-files streamreader

javascript - Why is dynamic textbox returning empty value? -



javascript - Why is dynamic textbox returning empty value? -

created basic input textbox , button dynamically via javascript using bootstrap css. on pressing button need retrieve value of textbox. coming out empty (not undefined).

the dosearch function need pick value.

here jsfiddle: http://jsfiddle.net/9u3kb6rk/3

here code:

(function ($) { function dosearch() { alert($('#name').val());//this empty? } $(document.body).on('click', '#go', function () { alert('doing search'); dosearch(); }); $.fn.searchname = function () { var caller = $(this); var output = ''; output += '<div class="input-group ">'; output += '<span class="input-group-addon area" id="name" name="name">name</span>'; output += '<input type="text" class="form-control" />'; output += '</div>'; output += '<div class="input-group">'; output += '<span class="input-group-btn">'; output += '<button class="btn btn-primary" type="button" id="go">search</button>'; output += '</span>'; output += '</div>'; output += '</div>'; $(caller).html(output); homecoming this; } }(jquery)); $(document).ready(function () { $('#searchname').searchname(); });

the id must in input instead of in span.

output += '<span class="input-group-addon area">name</span>'; output += '<input type="text" id="name" name="name" class="form-control"

your code updated.

javascript jquery html twitter-bootstrap

java - Reading from file into Array -



java - Reading from file into Array -

i have file numbers. looks follows:

1 2 3 4 5 6 7 8 9 10

the problem occurs while reading numbers array.

here piece of code:

scanner file1 = new scanner( new file("file1.txt") ); int lengt_h = 0; // here eclipse crashes... while( file1.hasnext() ) lengt_h++; int[] numberarray = new int[lengt_h]; for(int i=0; i<numberarray.length; i++) { numberarray[i] = file1.nextint(); } for(int n: numberarray) system.out.print(numberarray[n] + " ");

even if alter hasnext() function constant length (e.g 10), numbers in numberarray array looks follows:

1 1 1 2 1 1 5 5 1 3

why code not work properly?

problem code not moving sacanner pointer in while loop infinite loop. in lastly for loop trying access element numberarray[n] wrong because n number array numberarray.

you can seek :

public static void main(string args[]) throws filenotfoundexception { scanner file1 = new scanner(new file("d:\\data.txt")); int lengt_h = 0; while (file1.hasnext()) { lengt_h++; file1.next(); } file1 = new scanner(new file("d:\\data.txt")); // 1 time again set file pointer @ origin int[] numberarray = new int[lengt_h]; (int = 0; < numberarray.length; i++) { numberarray[i] = file1.nextint(); // read integer file } (int n : numberarray) system.out.print(n + " "); }

java arrays file

php - Alternative to foreach pass by reference -



php - Alternative to foreach pass by reference -

i've come case values in foreach passed reference in order modify element, @ later stage in code, same array looped 1 time again calculation time elements passed value. issue php retains reference lastly element in array in first foreach, overwrites element when next foreach starts if local variable has same name.

example code:

<?php $a = array("a" => "foo"); $b = array("b" => "bar"); $x = array($a, $b); foreach ($x &$y) {} print_r($x); foreach ($x $y) {} print_r($x); ?>

this yield

array ( [0] => array ( [a] => foo ) [1] => array ( [b] => bar ) ) array ( [0] => array ( [a] => foo ) [1] => array ( [a] => foo ) )

this absurdity stated in php manual

warning reference of $value , lastly array element remain after foreach loop. recommended destroy unset().

and indeed, using unset($y) resolve issue. fragile , cannot rely on coder remembering unset variable scope isn't obvious. question is: there alternatives foreach-pass-by-reference eliminates need unset variable afterwards?

you can utilize array_walk():

array_walk($x, function(&$y) { /* ... */ });

this makes reference $y local scope of callback function unsetting handled automatically.

php foreach pass-by-reference

python - Difference between wx.TextCtrl .write / .WriteText / .AppendText -



python - Difference between wx.TextCtrl .write / .WriteText / .AppendText -

i new python , new wxpython well. wondering if there difference between these wx.textctrl functions. mini code shows 3 times same output. if there no difference, there historic reason these functions?

import wx class testui(wx.panel): textctrl = '' def __init__(self, parent, name): super(testui, self).__init__(parent, name=name) self.buildui() self.show(true) self.textctrl.write('bli\n') self.textctrl.writetext('bla\n') self.textctrl.appendtext('blub\n') def buildui(self): self.textctrl = wx.textctrl(self, style=wx.te_multiline|wx.te_readonly) box = wx.boxsizer(wx.vertical) box.add(self.textctrl, proportion=1, flag=wx.expand) def main(): app = wx.app(false) root = wx.frame(parent=none, title='testui') testui(parent=root, name='testui') root.show(true) app.mainloop() # standard boilerplate phone call main() function. if __name__ == '__main__': main()

thanks :)

the 3 methods appear functionally same. however, argue utilize appendtext adding additional text text command create you're doing clear in code itself. of time, utilize setvalue. have used writetext when redirecting stdout, that's it. can read utilize case here:

http://www.blog.pythonlibrary.org/2009/01/01/wxpython-redirecting-stdout-stderr/

python wxpython textctrl wxtextctrl

windows - Using java how to find out an application is not used for sometime? -



windows - Using java how to find out an application is not used for sometime? -

using java how find out application not used sometime?

i having 3rd party application illustration can take 'skype'. if there no action (mouse/keyboard input)is given skype 5min, code through popup user. how check whether application getting input user? gone through net found below code giving output if entire desktop idle. need specific application skype. how that?

class="snippet-code-html lang-html prettyprint-override">import java.text.dateformat; import java.text.simpledateformat; import java.util.date; import com.sun.jna.*; import com.sun.jna.win32.*; /** * utility method retrieve idle time on windows , sample code test it. * jna shall nowadays in classpath work (and compile). * @author ochafik */ public class win32idletime { public interface kernel32 extends stdcalllibrary { kernel32 instance = (kernel32)native.loadlibrary("kernel32", kernel32.class); /** * retrieves number of milliseconds have elapsed since scheme started. * @see http://msdn2.microsoft.com/en-us/library/ms724408.aspx * @return number of milliseconds have elapsed since scheme started. */ public int gettickcount(); }; public interface user32 extends stdcalllibrary { user32 instance = (user32)native.loadlibrary("user32", user32.class); /** * contains time of lastly input. * @see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputstructures/lastinputinfo.asp */ public static class lastinputinfo extends construction { public int cbsize = 8; /// tick count of when lastly input event received. public int dwtime; } /** * retrieves time of lastly input event. * @see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/getlastinputinfo.asp * @return time of lastly input event, in milliseconds */ public boolean getlastinputinfo(lastinputinfo result); }; /** * amount of milliseconds have elapsed since lastly input event * (mouse or keyboard) * @return idle time in milliseconds */ public static int getidletimemilliswin32() { user32.lastinputinfo lastinputinfo = new user32.lastinputinfo(); user32.instance.getlastinputinfo(lastinputinfo); homecoming kernel32.instance.gettickcount() - lastinputinfo.dwtime; } enum state { unknown, online, idle, away }; public static void main(string[] args) { if (!system.getproperty("os.name").contains("windows")) { system.err.println("error: implemented on windows"); system.exit(1); } state state = state.unknown; dateformat dateformat = new simpledateformat("eee, d mmm yyyy hh:mm:ss"); (;;) { int idlesec = getidletimemilliswin32() / 1000; state newstate = idlesec < 30 ? state.online : idlesec > 5 * 60 ? state.away : state.idle; if (newstate != state) { state = newstate; system.out.println(dateformat.format(new date()) + " # " + state); } seek { thread.sleep(1000); } grab (exception ex) {} } } }

i think not used mean, user don't utilize active. can utilize windowlistener. here illustration working code(hope that's wanted):

public class awaytimer { private jframe mainframe; // mainframe in private jlabel timelabel; // our label stores time when leaving window private long leavetime = 0; // time set zero, prevent later saying unusual numbers public static void main(string[] args) { new awaytimer(); // create new awaytimer object } public awaytimer() { mainframe = new jframe("away timer"); // create new frame name away timer timelabel = new jlabel ("you 0 seconds away.", swingconstants.center); // create new label shows time away windowlistener listener = new windowlistener() { @override public void windowdeactivated(windowevent e) { // called on leaving focus leavetime = system.currenttimemillis(); // time when leaving window , save leavetime } @override public void windowactivated(windowevent e) { // called on switching frame // gets activated when open program. shows <ahugenumber> seconds away. set 0, check if leavetime 0 initialized if (leavetime == 0) return; // dont need calculate , leave text long difference = (system.currenttimemillis() - leavetime) / 1000; // calculate difference between leave time , , split 1000 time in seconds timelabel.settext("you " + difference + " seconds away."); // alter displayed text } // other listeners, arent of import @override public void windowopened(windowevent e) {/* here*/} @override public void windowiconified(windowevent e) {/* here*/} @override public void windowdeiconified(windowevent e) {/* here*/} @override public void windowclosing(windowevent e) {/* here*/} @override public void windowclosed(windowevent e) {/* here*/} }; mainframe.addwindowlistener(listener); // add together created listener window // add together label frame mainframe.add(timelabel); mainframe.pack(); // resize frame, fits contents mainframe.setvisible(true); // create visible } }

hope help.

java windows desktop

php - More efficient way to set a variable? -



php - More efficient way to set a variable? -

i have created if statement script sets variable based on number represents. after realizing script rather long , can done in more efficient way looked on net , did not find much results. here script

if ($row[position] == 1){ $variable = 1; } elseif ($row[position] == 2){ $variable = 1; } elseif ($row[position] == 3){ $variable = 2; } elseif ($row[position] == 4){ $variable = 2; } elseif ($row[position] == 5){ $variable = 3; } elseif ($row[position] == 6){ $variable = 3; } elseif ($row[position] == 7){ $variable = 4; } elseif ($row[position] == 8){ $variable = 4; } elseif ($row[position] == 9){ $variable = 5; } elseif ($row[position] == 10){ $variable = 5; } elseif ($row[position] == 11){ $variable = 6; } elseif ($row[position] == 12){ $variable = 6; } elseif ($row[position] == 13){ $variable = 7; } elseif ($row[position] == 14){ $variable = 7; } elseif ($row[position] == 15){ $variable = 8; } elseif ($row[position] == 16){ $variable = 8; }

as can see, it's pretty basic pattern.

1 = 1 2 = 1 3 = 2 4 = 2 5 = 3 6 = 3

and on...

i'm not looking work done, since may lot, want know how should go this. thanks.

this should work you

<?php $row["position"] = 4; //example //if (($row["position"] >= 1) && ($row["position"] <= 16) ) -> if want set variable if it's between 1 , 16 or else utilize if statement $variable = ceil($row["position"] / 2); echo $variable; ?>

php

python - Multiprocessing on pandas dataframe. Confusing behavior based on input size -



python - Multiprocessing on pandas dataframe. Confusing behavior based on input size -

i trying implement df.apply function parallelized across chunks of dataframe. wrote next test code see how much gain (versus info copying etc):

from multiprocessing import pool functools import partial import pandas pd import numpy np import time def df_apply(df, f): homecoming df.apply(f, axis=1) def apply_in_parallel(df, f, n=5): pool = pool(n) df_chunks = np.array_split(df, n) apply_f = partial(df_apply, f=f) result_list = pool.map(apply_f, df_chunks) homecoming pd.concat(result_list, axis=0) def f(x): homecoming x+1 if __name__ == '__main__': n = 10^8 df = pd.dataframe({"a": np.zeros(n), "b": np.zeros(n)}) print "parallel" t0 = time.time() r = apply_in_parallel(df, f, n=5) print time.time() - t0 print "single" t0 = time.time() r = df.apply(f, axis=1) print time.time() - t0

weird behavior: n=10^7 works n=10^8 gives me error

traceback (most recent phone call last): file "parallel_apply.py", line 27, in <module> r = apply_in_parallel(df, f, n=5) file "parallel_apply.py", line 14, in apply_in_parallel result_list = pool.map(apply_f, df_chunks) file "/usr/lib64/python2.7/multiprocessing/pool.py", line 227, in map homecoming self.map_async(func, iterable, chunksize).get() file "/usr/lib64/python2.7/multiprocessing/pool.py", line 528, in raise self._value attributeerror: 'numpy.ndarray' object has no attribute 'apply'

does know going on here? i'd appreciate feedback on way of parallelizing. expecting functions take more time inc or sum per individual row , millions of rows.

thanks!

n = 10^8 results 2, n = 10^7 results 13, because operator ^ xor (not power). 2 row length df can not splitted 5 chunks. utilize instead: n = 10**4 , n = 10**5. these values see difference in time. careful values greater n = 10**6 (at value parallel time @ 30 sec, single time @ 167 sec). , utilize pool.close() @ end (before return) in apply_in_parallel() automatically close workers in pool.

python pandas multiprocessing python-multiprocessing

android - List view item to which scroll bar points at -



android - List view item to which scroll bar points at -

i want know listview item scrollbar pointing when click on scrollbar image, can show popup related listview item

@override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); //getwindow().requestfeature(window.feature_action_bar); setcontentview(r.layout.list); list=(listview)findviewbyid(r.id.list); adapter=new lazyadapter(this, mstrings); list.setadapter(adapter); } public view getview(int position, view convertview, viewgroup parent) { view vi=convertview; if(convertview==null) vi = inflater.inflate(r.layout.item, null); textview text=(textview)vi.findviewbyid(r.id.text);; imageview image=(imageview)vi.findviewbyid(r.id.image); text.settext("itemitemitemitemitemitemitemitemitemitemitemitemititemitemitemmitetemitemitemitemitemitememitemitemitemiitemitemitemitem "+position); imageloader.displayimage(data[position], image); homecoming vi; }

you need implement onscroll method of listview below:

yourlistview.setonscrolllistener(new onscrolllistener() { @override public void onscrollstatechanged(abslistview view, int scrollstate) { //inside method can calculate , can found current position } @override public void onscroll(abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcount) { //inside method can calculate , can found current position, here have firstvisibleitem , total visible item count, think using it, can calculate current position. } });

android listview position scrollbar

Using prototype beans defined in a different java-based Spring config file -



Using prototype beans defined in a different java-based Spring config file -

assume have 2 spring config files: configa.java , configb.java.

here's how configa.java may like:

@configuration class configa { @scope("prototype") @bean public foo fooprototype() { homecoming new foo(params); } }

and want inject few instances of foo number of singleton-scoped beans declared in configb.java:

@configuration @import(configa.class) class configb { @bean public bar bar() { homecoming new bar(*** how inject foo instance here? ***); } @bean public buzz buzz() { homecoming new buzz(*** how inject foo instance here? ***); } }

if had single configuration file, replace blocks enclosed in asterisks fooprototype().

but, how inject different foo instances bar() , buzz() beans provided fooprototype() declared in different configuration file?

this looks similar illustration in spring documentation §5.12.5 composing java-based configurations.

this same page gives solution: can autowire configuration beans.

@configuration @import(configa.class) class configb { @autowired configa configa; @bean public bar bar() { homecoming new bar(configa.fooprototype()); } @bean public buzz buzz() { homecoming new buzz(configa.fooprototype()); } }

java spring spring-3

c++ - sending parameters to a function in cpp -



c++ - sending parameters to a function in cpp -

is possible have phone call function this:

test({22,11});

and decode parameter (and type) in function declaration? example:

void test(int *a){...}

i don't know mean "decode parameter", can certanly have test({22,11});.

#include <initializer_list> void test( std::initializer_list<int> params ) { (int : params) std::cout << << ' '; }

c++ function

php - Using find('list') in Cakephp 1.3 with custom fields -



php - Using find('list') in Cakephp 1.3 with custom fields -

i'm working in cakephp 1.3 project. have problem retrieving info database using find('list'). before lastly alter had code:

$listahabilidades = $this->habilidad->find('list',array('fields'=>array('id','habilidad'),'order'=>array('habilidad'))));

this command gives me next array:

array ( [40] => bicicleta [42] => enganches de poleas [28] => escalada [43] => transfer [41] => 4x4 [53] => administración linux [72] => Ángeles [59] => baile flamenco [57] => baloncesto [39] => barranquismo [66] => cante flamenco [30] => conducción [52] => consola linux [80] => cuarta prueba [75] => demonios [84] => esgrima [58] => futbol [76] => limpiar [77] => limpiar2 [54] => linux [27] => montañismo [60] => ms office [65] => natación [45] => patinaje [56] => pc [78] => probar [44] => programación [82] => protocolo [81] => quinta prueba [63] => tenis [79] => tercera prueba [83] => triatlón [55] => w8 [51] => xp [64] => zapateado )

but had problem because info can have spaces @ begining of field 'habilidad' , want info without , order them without them. changed command to:

$listahabilidades = $this->habilidad->find('list',array('fields'=>array('id','trim(habilidad.habilidad)'),'order'=>array('trim(habilidad.habilidad)'))));

it gives me next array:

array ( [41] => [53] => [72] => [59] => [57] => [39] => [40] => [66] => [30] => [52] => [80] => [75] => [42] => [28] => [84] => [58] => [76] => [77] => [54] => [27] => [60] => [65] => [45] => [56] => [78] => [44] => [82] => [81] => [63] => [79] => [43] => [83] => [55] => [51] => [64] => )

how can list trimmed (without loops)?

can add together virtual field model:

public $virtualfields = array( 't_habilidad' => 'ltrim(habilidad.habilidad)' );

then utilize

$listahabilidades = $this->habilidad->find('list', array('fields'=>array('id','habilidad'), 'order' => array('t_habilidad'))));

php cakephp

c++ - Deep copy of TCHAR array is truncated -



c++ - Deep copy of TCHAR array is truncated -

i've created class test functionality need use. class take deep re-create of passed in string , create available via getter. using visual studio 2012. unicode enabled in project settings.

the problem memcpy operation yielding truncated string. output so;

thisisatest: instancedataconstructor: testing testing 123 testing te_ready

where first line check of passed in tchar* string & sec line output populating allocated memory memcpy operation. output expected is; "testing testing 123".

can explain wrong here?

n.b. got #ifndef unicode typedefs here: how-to-convert-tchar-array-to-stdstring

#ifndef instance_data_h//if not defined #define instance_data_h//then define #include <string> //tchar typedef, depending on compilation configuration, either defaults char or wchar. //standard template library supports both ascii (with std::string) , wide character sets (with std::wstring). //all need typedef string either std::string or std::wstring depending on compilation configuration. //to maintain flexibility can utilize next code: #ifndef unicode typedef std::string string; #else typedef std::wstring string; #endif //now may utilize string in code , allow compiler handle nasty parts. string have constructors lets convert tchar std::string or std::wstring. class instancedata { public: instancedata(tchar* strin) : strmessage(strin)//constructor { //check passed in string string outmsg(l"thisisatest: instancedataconstructor: ");//l wide character string literal outmsg += strmessage;//concatenate message const wchar_t* finalmsg = outmsg.c_str();//prepare outputting outputdebugstringw(finalmsg);//print message //prepare tchar dynamic array. deep copy. chararrayptr = new tchar[strmessage.size() +1]; chararrayptr[strmessage.size()] = 0;//null terminate std::memcpy(chararrayptr, strmessage.data(), strmessage.size());//copy characters array pointed passed in tchar*. outputdebugstringw(chararrayptr);//print copied message check } ~instancedata()//destructor { delete[] chararrayptr; } //getter tchar* getmessage() const { homecoming chararrayptr; } private: tchar* chararrayptr; string strmessage;//is used conveniently ascertain length of passed in underlying tchar array. }; #endif//header guard

please pay attending next lines in code:

// prepare tchar dynamic array. deep copy. chararrayptr = new tchar[strmessage.size() + 1]; chararrayptr[strmessage.size()] = 0; // null terminate // re-create characters array pointed passed in tchar*. std::memcpy(chararrayptr, strmessage.data(), strmessage.size());

the 3rd argument pass memcpy() count of bytes copy. if string simple ascii string stored in std::string, count of bytes same of count of ascii characters.

but, if string wchar_t unicode utf-16 string, each wchar_t occupies 2 bytes in visual c++ (with gcc things different, windows win32/c++ code compiled vc++, let's focus on vc++). so, have scale size count memcpy(), considering proper size of wchar_t, e.g.:

memcpy(chararrayptr, strmessage.data(), strmessage.size() * sizeof(tchar));

so, if compile in unicode (utf-16) mode, tchar expanded wchar_t, , sizeof(wchar_t) 2, content of original string should deep-copied.

as alternative, unicode utf-16 strings in vc++ may utilize wmemcpy(), considers wchar_t "unit of copy". so, in case, don't have scale size factor sizeof(wchar_t).

as side note, in constructor have:

instancedata(tchar* strin) : strmessage(strin)//constructor

since strin input string parameter, consider passing const pointer, i.e.:

instancedata(const tchar* strin)

c++ arrays unicode deep-copy tchar

activerecord - Rails 4 query a reference via n:n relation -



activerecord - Rails 4 query a reference via n:n relation -

following structure

production belongs_to :offer has_many :production_positions has_many :products, through: :production_positions product has_many :production_positions has_many :productions, through: :production_positions productionposition belongs_to :production belongs_to :product

now want offers contains product_id 1. how did have query database?

to productions quite easy:

production.includes(:products).where("products.id" => 1)

but how offers referenced?

offer.includes(:production).includes(:products).where("products.id" => 1)

the line above produces next error: association named 'products' not found on offer

add has_many :products, through: :production in offer class , seek following:

offer.select('offers.*').joins(:products).where('products.id = ?', 1)

i assumed had has_one :production in offer class. add together scope perform query:

class offer < activerecord::base has_one :production has_many :products, through: :production scope :with_product_id, ->(id) select('offers.*'). joins(:products). where('products.id = ?', id) end end

example (offers product 1):

offer.with_product_id(1)

activerecord ruby-on-rails-4

java - Selenium chromedriver.exe -



java - Selenium chromedriver.exe -

as part of project setup, have 2 projects 1 libraries , other selenium. have browser setup in libraries project /src/main/resource having chromedriver.exe selenium project has pagefactory classes , project has dependency on library. when running project on slave getting next error message:

java.lang.illegalstateexception: driver executable not exist: c:\jenkins_slave10\workspace\test-demos\file:\c:\users\svc-hudson\.m2\repository\com\bskyb\automation\crm\libraries\1.1-snapshot\libraries-1.1-snapshot.jar!\chromedriver\windows\chromedriver.exe @ com.google.common.base.preconditions.checkstate(preconditions.java:177) @ org.openqa.selenium.remote.service.driverservice.checkexecutable(driverservice.java:117) @ org.openqa.selenium.remote.service.driverservice.findexecutable(driverservice.java:112) @ org.openqa.selenium.chrome.chromedriverservice.createdefaultservice(chromedriverservice.java:89) @ org.openqa.selenium.chrome.chromedriver.(chromedriver.java:149) @ com.abc.automation.crm.actions.browsersetup.openbrowserchrome(browsersetup.java:38) @ com.abc.automation.crm.actions.search.setup(search.java:111) @ com.abc.automation.crm.actions.search.directorynumber(search.java:35) @ com.abc.automation.crm.stepdefs.demo.i_search_for_directory_number(demo.java:34)

did seek setting scheme property specify chromedriver.exe location?

either start selenium server

-dwebdriver.chrome.driver=c:\path\to\your\chromedriver.exe

or

set scheme property in code:

system.setproperty("webdriver.chrome.driver", "c:/path/to/your/chromedriver.exe");

java maven selenium

c# - How to retain selected HTML5 radio button value when you navigate through a DataPager? -



c# - How to retain selected HTML5 radio button value when you navigate through a DataPager? -

i'm trying create online questionnaire , front-end of website

<table> <tbody> <asp:listview id="lvquestion" runat="server" onpagepropertieschanged="lvquestion_onpagepropertieschanged" onpagepropertieschanging="lvquestion_pagepropertieschanging"> <layouttemplate> <ul> <asp:placeholder id="itemplaceholder" runat="server" /> </ul> </layouttemplate> <itemtemplate> <tr runat="server"> <td><%# eval("thequestion") %></td> </tr> <tr> <td><input type="radio" name="choice" value="<%# eval("choice1") %>" /><%# eval("choice1") %></td> <td><input type="radio" name="choice" value="<%# eval("choice2") %>" /><%# eval("choice2") %></td> <td><input type="radio" name="choice" value="<%# eval("choice3") %>" /><%# eval("choice3") %></td> <td><input type="radio" name="choice" value="<%# eval("choice4") %>" /><%# eval("choice4") %></td> </tr> </itemtemplate> <emptydatatemplate> no info </emptydatatemplate> </asp:listview> </tbody> </table> <asp:datapager id="lvdatapager1" runat="server" pagedcontrolid="lvquestion" pagesize="1"> <fields> <asp:numericpagerfield buttontype="link" /> </fields> </asp:datapager>

i have displayed questions , choices(using html5 radio buttons). however, when user navigates question #1 question #2, selected reply in question #1 lost datapager. needed selected answers saved in order collect answers using single submit button.

you can utilize runat='server' providing id controls

<input type="radio" name="choice" value="<%# eval("choice1") %>" id="rdch1" runat="server" /> <input type="radio" name="choice" value="<%# eval("choice1") %>" id="rdch2" runat="server" /> <input type="radio" name="choice" value="<%# eval("choice1") %>" id="rdch3" runat="server" />

on code behind can these values by

string selvalues=rdch1.value.tostring();

you have find radio buttons within listview on itemdatabound

protected void listview_itemdatabound(object sender, listviewitemeventargs e) { if (e.item.itemtype == listviewitemtype.dataitem) { system.web.ui.htmlcontrols.htmlinputradiobutton = (system.web.ui.htmlcontrols.htmlinputradiobutton)e.item.findcontrol("rdch1"); }

c# asp.net radio-button listviewitem datapager

javascript - Avoid form resubmission if page reloads -



javascript - Avoid form resubmission if page reloads -

i submitting form, contains username , password, if have entered wrong username , password gives error message "invalid username or password". if refreshing page using browsers reload button or using f5,it asks resubmit form,if pressed on go on 1 time again showing same error message,that means taking previous details is.

how avoid this?

i want hide error message if refresh page.

try this:

function submitcheck(){ if(condition==true) { homecoming true; } else { homecoming false; } }

when status fails homecoming false. stop form submitting.

javascript jquery html

python - when i run the program nothing happens -



python - when i run the program nothing happens -

def file(): username_file = open("username_file.txt", "r") username_file.close() username_file = open ("username_file.txt", "a") firstname = input("firstname:") lastname = input("lastname:") fullname = (firstname + lastname) username_file.write(str(fullname)) username_file.close()

when seek run programme nil happens, know why?

your programme working perfectly. defines function file() , exits.

if want call function, think putting next line @ bottom:

file()

by way of example, programme may appear not much:

def print42(): print 42

but this 1 calls function useful work:

def print42(): print 42 print42()

so, if just:

add file() line bottom of file, starting in first column; make sure you're using python3 (or alter input raw_input python2); and actually have username_file.txt file beforehand, avoid exception while opening read;

then work fine (though names hard against each other, paxdiablo rather pax diablo).

python

javascript - ng-view load a new separate page in angular -



javascript - ng-view load a new separate page in angular -

i'm trying phone call rest api, does login process, in angular.

i have successfully, integrated angular rest calls. 1 time login successful, want code move new page.

in successful handler, i'm doing this:

$location.path("/home")

and have route provide this:

$routeprovider.when('/home',{ templateurl: 'templates/test.html', controller: 'homecontroller' })

and in view have html tag this:

<div ng-view></div>

things working fine expected. want ng-view load finish new page, rather template. login page, need move new page.

is possible so?

thanks in advance.

if donot want open html ng-view set location.href = url or window.location = url or utilize angular way $window.location=url;

javascript angularjs

In between not working in Oracle -



In between not working in Oracle -

hello trying fetch date using in between function in oracle it's not working have below mentioned info in oracle table

i using below mentioned query filter dates , it's give me error both menioned in image

plz help me out this

it seems trying convert date value date to_date(...) function. type of column receivedtime looks date, seek not utilize to_date function column, following:

select * use_news clientid=159 , receivedtime between to_date('04/05/2012', 'mm/dd/yyyy') , to_date('11/14/2014', 'mm/dd/yyyy') ;

oracle

java - Libgdx body position and shaperenderer position not the same -



java - Libgdx body position and shaperenderer position not the same -

i'm new libgdx in general. have ball bouncing world , experimenting it. before had fixed photographic camera position such:

http://prntscr.com/567hvo

after have putted next line in render method photographic camera keeps next player (which circle) :

camera.position.set(player.getposition().x, player.getposition().y, 0);

the player body type.

so when follow player, shape renderer acts weird now. @ happens:

http://prntscr.com/567i9a

even though referring same x , y position of player photographic camera , shape renderer, not in same position.

here code:

public class game extends applicationadapter { world world = new world(new vector2(0, -9.8f), true); box2ddebugrenderer debugrenderer; orthographiccamera camera; static final int ppm = 100; static float height,width; body player; rayhandler handler; pointlight l1; shaperenderer shaperenderer; @override public void create() { shaperenderer = new shaperenderer(); height = gdx.graphics.getheight(); width = gdx.graphics.getwidth(); //set photographic camera photographic camera = new orthographiccamera(); camera.settoortho(false, (width)/ppm/2, (height)/ppm/2); camera.update(); //ground body bodydef groundbodydef =new bodydef(); groundbodydef.position.set(new vector2(width/ppm/2/2, 0)); body groundbody = world.createbody(groundbodydef); polygonshape groundbox = new polygonshape(); groundbox.setasbox((width/ppm/2/2), 0.1f); groundbody.createfixture(groundbox, 0.0f); //wall left bodydef wallleftdef = new bodydef(); wallleftdef.position.set(0, 0f); body wallleftbody = world.createbody(wallleftdef); polygonshape wallleft = new polygonshape(); wallleft.setasbox(width/ppm/20/2, height/ppm/2); wallleftbody.createfixture(wallleft,0.0f); //wall right bodydef wallrightdef = new bodydef(); wallrightdef.position.set((width/ppm)/2, 0f); body wallrightbody = world.createbody(wallrightdef); polygonshape wallright = new polygonshape(); wallright.setasbox(width/ppm/20/2, height/ppm/2); wallrightbody.createfixture(wallright,0.0f); //dynamic body bodydef bodydef = new bodydef(); bodydef.type = bodytype.dynamicbody; bodydef.position.set((width/ppm)/2/2, (height / ppm)/2/2); player = world.createbody(bodydef); circleshape dynamiccircle = new circleshape(); dynamiccircle.setradius(5f/ppm); fixturedef fixturedef = new fixturedef(); fixturedef.shape = dynamiccircle; fixturedef.density = 0.4f; fixturedef.friction = 0.2f; fixturedef.restitution = 0.6f; player.createfixture(fixturedef); debugrenderer = new box2ddebugrenderer(); //lighting handler = new rayhandler(world); handler.setcombinedmatrix(camera.combined); pointlight l1 = new pointlight(handler,5000,color.cyan,width/ppm/2,width/ppm/2/2/2,height/ppm/2/2); new pointlight(handler,5000,color.purple,width/ppm/2,width/ppm/2/1.5f,height/ppm/2/2); shaperenderer.setprojectionmatrix(camera.combined); } public void update() { if(gdx.input.iskeyjustpressed(keys.up)) { player.applyforcetocenter(0, 0.75f, true); } if(gdx.input.iskeyjustpressed(keys.right)) { player.applyforcetocenter(0.5f, 0f, true); } if(gdx.input.iskeyjustpressed(keys.left)) { player.applyforcetocenter(-0.5f, 0f, true); } } @override public void dispose() { } @override public void render() { gdx.gl.glclear(gl20.gl_color_buffer_bit); debugrenderer.render(world, camera.combined); world.step(1/60f, 6, 2); handler.updateandrender(); shaperenderer.begin(shapetype.filled); shaperenderer.setcolor(1, 1, 1, 1); shaperenderer.circle(player.getposition().x, player.getposition().y, 5f/ppm, 100); shaperenderer.end(); camera.position.set(player.getposition().x, player.getposition().y, 0); camera.update(); update(); } @override public void resize(int width, int height) { } @override public void pause() { } @override public void resume() { }

}

you setting shaperenderers projectionmatrix 1 time not updating when render.

you should put

shaperenderer.setprojectionmatrix(camera.combined);

to render method right before

shaperenderer.begin(shapetype.filled);

java camera libgdx shape-rendering

String-based linked list in C produces segmentation fault -



String-based linked list in C produces segmentation fault -

---------- #include <stdio.h> #include <stdlib.h> #include <string.h> struct node { char *val; struct node *next; }; void add_to_list(struct node **, char *); void list_all_elements(struct node *); int main (int argc, char **argv) { char *val; struct node *head = null; { scanf("%s",val); add_to_list(&head, val); } while(val[0] != '\\'); list_all_elements(head); } void add_to_list(struct node **head, char *val) { //this produces segfault struct node *temp = malloc(sizeof *temp); //edit - fixed per comments temp->val = malloc(strlen(val) + 1); strcpy(temp->val, val); temp->next = null; if(head!=null) temp->next = *head; *head = temp; } void list_all_elements(struct node *head) { while(head!=null) { printf("%s\n",head->val); head = head->next; } }

so compiled implement linked list. now, reason malloc'ing produces segmentation fault.

to sure, replaced char * char [] , code runs fine. malloc faulting due or there trivial error can't seem find?

you did not allocate memory pointed variable val , going read string.

char *val; //... { scanf("%s",val); add_to_list(&head, val); }

variable val not initialized programme has undefined behaviour.

and function add_to_list invalid. illustration sizeof(val) has same value equal size of pointer char. not yield size of string pointed pointer. instead of operator sizeof shall utilize function strlen

the function written like

void add_to_list( struct node **head, const char *val ) { struct node *temp = malloc( sizeof *temp ); size_t n = strlen( val ); temp->val = malloc( n + 1 ); strcpy( temp->val, val ); temp->next = *head; *head = temp; }

c string pointers linked-list

ios - BundleId is not the same as AppId -



ios - BundleId is not the same as AppId -

i'm trying submit first app app store , stuck trying create archive in xcode 6 - appid of format com.xxxxxxx.prefix bundleid missing com i.e. xxxxxxx.prefix.

i error

no matching provisioning profiles found

and statement appid not match bundle identifier. (the error message says xcode can prepare issue never does.)

there lots of answers around can't figure out how create bundle identifier match appid.

thanks help - i've been stuck ages on this.

sorted out person's answer. (thanks jon schneider)

the bundleid in info.plist file must = bundleid on itunes connect website @ apps>[your app]>more>about app.

that's it!

ios xcode

allegro cl - Common-Lisp Code was working fine, now "Error: Attempt to take the value of the unbound variable `*OPPONENT*'." -



allegro cl - Common-Lisp Code was working fine, now "Error: Attempt to take the value of the unbound variable `*OPPONENT*'." -

i'm baffled. i'm playing around tic-tac-toe game found in ch 10 of mutual lisp: gentle introduction symbolic computation https://www.cs.cmu.edu/~dst/lispbook/book.pdf . worked in ide, saved , compiled+loaded it. ran several games no problem. so, copied known-working file , started tweaking. again, no problems -- working fine. now, however, when run (play-one-game) next error:

error: effort take value of unbound variable '*opponent**'

i error in both original , copy. closed allegrocl , restarted computer, problem persisted after reboot. updated programme , ran ./update.sh in it's app directory.

finally, decided re-create illustration right pdf in brand-new file in different directory, , same problem. don't know changed, it's got me plussed least.

(defun make-board () (list 'board 0 0 0 0 0 0 0 0 0)) (defun convert-to-letter (v) (cond ((equal v 1) "o") ((equal v 10) "x") (t " "))) (defun print-row (x y z) (format t "~& ~a | ~a | ~a" (convert-to-letter x) (convert-to-letter y) (convert-to-letter z))) (defun print-board (board) (format t "~%") (print-row (nth 1 board) (nth 2 board) (nth 3 board)) (format t "~& -----------") (print-row (nth 4 board) (nth 5 board) (nth 6 board)) (format t "~& -----------") (print-row (nth 7 board) (nth 8 board) (nth 9 board)) (format t "~%~%")) (defun make-move (player pos board) (setf (nth pos board) player) board) (setf *triplets* '((1 2 3) (4 5 6) (7 8 9) ;horizontal triplets. (1 4 7) (2 5 8) (3 6 9) ;vertical triplets. (1 5 9) (3 5 7))) ;diagonal triplets. (defun sum-triplet (board triplet) (+ (nth (first triplet) board) (nth (second triplet) board) (nth (third triplet) board))) (defun compute-sums (board) (mapcar #'(lambda (triplet) (sum-triplet board triplet)) *triplets*)) (defun winner-p (board) (let ((sums (compute-sums board))) (or (member (* 3 *computer*) sums) (member (* 3 *opponent*) sums)))) (defun play-one-game () (if (y-or-n-p "would go first? ") (opponent-move (make-board)) (computer-move (make-board)))) (defun opponent-move (board) (let* ((pos (read-a-legal-move board)) (new-board (make-move *opponent* pos board))) (print-board new-board) (cond ((winner-p new-board) (format t "~&you win!")) ((board-full-p new-board) (format t "~&tie game.")) (t (computer-move new-board))))) (defun read-a-legal-move (board) (format t "~&your move: ") (let ((pos (read))) (cond ((not (and (integerp pos) (<= 1 pos 9))) (format t "~&invalid input.") (read-a-legal-move board)) ((not (zerop (nth pos board))) (format t "~&that space occupied.") (read-a-legal-move board)) (t pos)))) (defun board-full-p (board) (not (member 0 board))) (defun computer-move (board) (let* ((best-move (choose-best-move board)) (pos (first best-move)) (strategy (second best-move)) (new-board (make-move *computer* pos board))) (format t "~&my move: ~s" pos) (format t "~&my strategy: ~a~%" strategy) (print-board new-board) (cond ((winner-p new-board) (format t "~&i win!")) ((board-full-p new-board) (format t "~&tie game.")) (t (opponent-move new-board))))) (defun random-move-strategy (board) (list (pick-random-empty-position board) "random move")) (defun pick-random-empty-position (board) (let ((pos (+ 1 (random 9)))) (if (zerop (nth pos board)) pos (pick-random-empty-position board)))) (defun make-three-in-a-row (board) (let ((pos (win-or-block board (* 2 *computer*)))) (and pos (list pos "make 3 in row")))) (defun block-opponent-win (board) (let ((pos (win-or-block board (* 2 *opponent*)))) (and pos (list pos "block opponent")))) (defun win-or-block (board target-sum) (let ((triplet (find-if #'(lambda (trip) (equal (sum-triplet board trip) target-sum)) *triplets*))) (when triplet (find-empty-position board triplet)))) (defun find-empty-position (board squares) (find-if #'(lambda (pos) (zerop (nth pos board))) squares)) (defun choose-best-move (board) ;second version. (or (make-three-in-a-row board) (block-opponent-win board) (random-move-strategy board)))

if you're next instructions book, tells invoke

(setf *computer* 10) (setf *opponent* 1)

apparently didn't include in code listing.

in general -- if error unbound, obvious thing look code should binding value.

common-lisp allegro-cl

php - CakePhp Config.timezone gives me wrong time -



php - CakePhp Config.timezone gives me wrong time -

if utilize in core.php

configure::write('config.timezone', 'europe/paris');

time displayed 2 hr less

date_default_timezone_set('europe/paris');

should set else in core.php ?

thanks.

you should check comment above configuration value:

config.timezone available in can set users' timezone string. if method of caketime class called $timezone parameter null , config.timezone set, value of config.timezone used. feature allows set users' timezone 1 time instead of passing each time in function calls.

the config.timezone configuration value applies caketime utility class, wich utilize value in case no timezone explicitly beingness passed it.

in order configure timezone used built-in php functions you'll have utilize date_default_timezone_set().

see also

http://book.cakephp.org/2.0/en/appendices/2-2-migration-guide.html#configure http://book.cakephp.org/2.0/en/core-utility-libraries/time.html

php cakephp cakephp-2.5

mysql - Combine two rows in select query having same id's -



mysql - Combine two rows in select query having same id's -

i have query

select `sys_forms`.`formid`, `sys_forms`.`formname`, `sys_forms`.`formcipath`, `sys_forms_in_groups`.`ismenulink`, `sys_forms_in_groups`.`groupid` (`sys_forms`) inner bring together `sys_forms_in_groups` on `sys_forms_in_groups`.`formid` = `sys_forms`.`formid` `groupid` = 1 union select `sys_forms`.`formid`, `sys_forms`.`formname`, `sys_forms`.`formcipath`, `sys_forms_in_groups`.`ismenulink`, `sys_forms_in_groups`.`groupid` (`sys_forms`) inner bring together `sys_forms_in_groups` on `sys_forms_in_groups`.`formid` = `sys_forms`.`formid` `groupid` = 2

it returning me below data.

as can see, there 2 identical formid.

what want if id's same rows should merged groupid different both identical formid's.

so want them bring together in csv format result be

formid formname - - groupid ------------------------------------------------- 48 formsin groups - - 1,2

the specified result can returned query this:

class="lang-sql prettyprint-override">select f.formid , f.formname , f.formcipath , max(g.ismenulink) ismenulink , group_concat(distinct g.groupid order g.groupid) groupids `sys_forms` f bring together `sys_forms_in_groups` g on g.formid = f.formid , g.groupid in (1,2) grouping f.formid

the group_concat aggregate combine multiple values comma separated list. (a different delimiter can specified, default comma.)

we utilize max aggregate around ismenulink column non-null value in place of null.

mysql sql

How can i rotate the particular view landscape or portrait programatically in android? -



How can i rotate the particular view landscape or portrait programatically in android? -

how can rotate particular view in landscape or portrait mode in dynamically in android. using method

setrequestedorientation (activityinfo.screen_orientation_landscape);

but total layout going landscapmode .but want particular view in landscape mode. so,please tell me known .advance all

following code used display activity landscape mode

<activity android:screenorientation="landscape" android:configchanges="orientation|keyboardhidden" android:name="youractivty"/>

change according need

android android-layout screen-orientation

postgresql - Rails Active Record multiple associations -



postgresql - Rails Active Record multiple associations -

i have rails app using postgres , active record, , can't fathom efficient associations between models.

i have model called article. article needs have format , 2/3 genres.

i need articles able listed format i.e. http://myapp.com/format/format-id/article-id

i need articles listed genre, so: myapp.com/genre/genre-name/article-id

i thinking genres , formats models has_many_and_belongs_to associations articles. each article has multiple genres, , 1 format, each genre has multiple articles.

i know should simple, can't find efficient route of making happen.

there's old railscasts episode goes through 2 ways many-to-many associations rails - should watch it: http://railscasts.com/episodes/47-two-many-to-many. it's old still relevant.

so, you've got articles, formats, , genres. since each article have 1 format, don't need has_and_belongs_to_many relationship there. article belongs_to format, , format has_many articles.

each row in articles table have format_id field indicate format belongs to.

the relationship between genres , articles many-to-many, bit trickier. @ database level, requires 'join table'. bring together table called articles_genres, , each row represents 1 genre 1 particular article has. so, it'd have genre_id column, , article_id column.

in terms of rails, there 2 ways this:

give articles_genres table it's own model. in case might want give table different name, indicate it's model in it's own right, not bring together table. phone call genreizations or don't give articles_genres table it's own model, , allow rails handle all.

i prefer first way - sense more in control, , leaves things more flexible future. but, either work. railscasts episode linked describes both ways.

if go first way, models you'll have:

class article < activerecord::base has_many :genreizations has_many :genres, through: :genreizations belongs_to :format end class format < activerecord::base has_many :articles end class genreization < activerecord::base belongs_to :article belongs_to :genre end class genre < activerecord::base has_many :genreizations has_many :articles, through: :genreizations end

and in sec way, models you'll have:

class article < activerecord::base has_and_belongs_to_many :genres belongs_to :format end class format < activerecord::base has_many :articles end class genre < activerecord::base has_and_belongs_to_many :articles end

ruby-on-rails postgresql activerecord associations

python - Load Tick Data in YYYYMMDD HHTTSSLLL format -



python - Load Tick Data in YYYYMMDD HHTTSSLLL format -

i trying read time series given .csv file using pandas. info describes high frequency exchange rates , of next form

time,bid,ask 20120401 170041033,1.204070,1.204190 20120401 170200097,1.204080,1.204200

where time interpret yyyymmdd hhmmsslll (and l = milliseconds). seek using next piece of code

parse = lambda x: datetime.strptime(x, '%y%m%d %h%t%s%l') ts = pd.read_csv('./tick.csv', index_col = 'time', parse_dates = 'time', date_parser = parse)

which yields error message:

'd' bad directive in format '%y%m%d %h%t%s%l'

does know error message comes from? not know why abbreviation of d 'day' should incorrect.

python pandas time-series time-format

eclipse - Android Fragment Content Lost -



eclipse - Android Fragment Content Lost -

i have problem on android eclipse fragments in viewpager. when home activity starts show actionbar tabs , first fragment on screen. when swipe next fragment , first fragment, first fragment contents still on screen. on other hand if swipe 2 times right , go first fragment, contents lost , blank screen shown. codes below. how retain each fragment content either shown or visible ? help appreciated. thanx in advance.

homeactivity.java

public class homeactivity extends fragmentactivity implements tablistener { private string[] menuitems = null; private actionbar bar = null; private viewpager viewpager = null; private tabsadapter tabsadapter = null; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_home); viewpager = (viewpager) findviewbyid(r.id.viewpager); viewpager.setpagemargin(10); menuitems = getresources().getstringarray(r.array.menutitles); bar = getactionbar(); bar.setnavigationmode(actionbar.navigation_mode_tabs); tabsadapter = new tabsadapter(this, viewpager); (int = 0; < menuitems.length; i++) { switch (i) { case 0: tabsadapter.addtab(bar.newtab().settext(menuitems[i]), newsfeedactivity.class, null); break; case 1: tabsadapter.addtab(bar.newtab().settext(menuitems[i]), notificationactivity.class, null); break; case 2: tabsadapter.addtab(bar.newtab().settext(menuitems[i]), newsfeedactivity.class, null); break; case 3: tabsadapter.addtab(bar.newtab().settext(menuitems[i]), notificationactivity.class, null); break; case 4: tabsadapter.addtab(bar.newtab().settext(menuitems[i]), newsfeedactivity.class, null); break; default: break; } } if (savedinstancestate != null) { bar.setselectednavigationitem(savedinstancestate.getint("tab", 0)); } } @override protected void onsaveinstancestate(bundle outstate) { super.onsaveinstancestate(outstate); outstate.putint("tab", getactionbar().getselectednavigationindex()); } @override protected void onrestoreinstancestate(bundle savedinstancestate) { super.onrestoreinstancestate(savedinstancestate); // restore selected tab int saved = savedinstancestate.getint("tab", 0); if (saved != getactionbar().getselectednavigationindex()) getactionbar().setselectednavigationitem(saved); } @override public void ontabselected(tab tab, fragmenttransaction ft) { } @override public void ontabunselected(tab tab, fragmenttransaction ft) { } @override public void ontabreselected(tab tab, fragmenttransaction ft) { } public static class tabsadapter extends fragmentpageradapter implements actionbar.tablistener, viewpager.onpagechangelistener { private final context mcontext; private final actionbar mactionbar; private final viewpager mviewpager; private final arraylist<tabinfo> mtabs = new arraylist<tabinfo>(); static final class tabinfo { private final class<?> clss; private final bundle args; tabinfo(class<?> _class, bundle _args) { clss = _class; args = _args; } } public tabsadapter(fragmentactivity activity, viewpager pager) { super(activity.getsupportfragmentmanager()); mcontext = activity; mactionbar = activity.getactionbar(); mviewpager = pager; mviewpager.setadapter(this); mviewpager.setonpagechangelistener(this); } public void addtab(actionbar.tab tab, class<?> clss, bundle args) { tabinfo info = new tabinfo(clss, args); tab.settag(info); tab.settablistener(this); mtabs.add(info); mactionbar.addtab(tab); notifydatasetchanged(); } @override public void onpagescrollstatechanged(int state) { } @override public void onpagescrolled(int position, float positionoffset, int positionoffsetpixels) { } @override public void onpageselected(int position) { mactionbar.setselectednavigationitem(position); } @override public void ontabreselected(tab tab, fragmenttransaction ft) { toast.maketext(mcontext, "reselected!", toast.length_short).show(); object tag = tab.gettag(); (int = 0; < mtabs.size(); i++) { if (mtabs.get(i) == tag) { mviewpager.setcurrentitem(i); } } } @override public void ontabselected(tab tab, fragmenttransaction ft) { toast.maketext(mcontext, "gokay!", toast.length_short).show(); object tag = tab.gettag(); (int = 0; < mtabs.size(); i++) { if (mtabs.get(i) == tag) { mviewpager.setcurrentitem(i); } } } @override public void ontabunselected(tab tab, fragmenttransaction ft) { } @override public fragment getitem(int position) { tabinfo info = mtabs.get(position); homecoming fragment.instantiate(mcontext, info.clss.getname(), info.args); } @override public int getcount() { homecoming mtabs.size(); } }

}

newsfeedactivity.java

public class newsfeedactivity extends fragment { static final string url = "http://api.androidhive.info/pizza/?format=xml"; // xml node keys static final string key_item = "item"; // parent node static final string key_id = "id"; static final string key_name = "name"; static final string key_cost = "cost"; static final string key_desc = "description"; private arraylist<string> xmllist = null; private xmlparser parser = null; private string xml = ""; private document doc = null; private nodelist nl = null; private view view = null; private element e = null; private listview listnewsfeed = null; private static bundle args = null; private static newsfeedactivity newsfeed = null; private arrayadapter<string> adapter = null; public static newsfeedactivity newinstance(int page, string title) { newsfeed = new newsfeedactivity(); args = new bundle(); args.putint("page", page); args.putstring("newsfeed", title); newsfeed.setarguments(args); homecoming newsfeed; } @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); } @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view = inflater.inflate(r.layout.activity_news_feed, container, false); if (getactivity().getactionbar().getselectedtab().getposition() == 0) { new newsfeeder().execute(""); } homecoming view; } private class newsfeeder extends asynctask<string, string, string> { private progressdialog mprogressdialog = null; @override protected void onpreexecute() { super.onpreexecute(); mprogressdialog = new progressdialog(getactivity()); mprogressdialog.setmessage("haber kaynağı yenileniyor.."); mprogressdialog.setcancelable(false); mprogressdialog.setprogressstyle(progressdialog.style_spinner); mprogressdialog.show(); } @override protected string doinbackground(string... params) { xmllist = new arraylist<string>(); seek { parser = new xmlparser(); xml = parser.getxmlfromurl(url); // getting xml log.i("gokay", xml); doc = parser.getdomelement(xml); // getting dom element nl = doc.getelementsbytagname(key_item); homecoming null; } grab (exception e) { e.printstacktrace(); system.out.println(e.getmessage()); log.e("gokay", e.getmessage()); homecoming null; } } @override protected void onpostexecute(string result) { super.onpostexecute(result); mprogressdialog.dismiss(); (int = 0; < nl.getlength(); i++) { e = (element) nl.item(i); xmllist.add(parser.getvalue(e, key_id)); xmllist.add(parser.getvalue(e, key_name)); xmllist.add("rs." + parser.getvalue(e, key_cost)); xmllist.add(parser.getvalue(e, key_desc)); } listnewsfeed = (listview) view.findviewbyid(r.id.listview1); adapter = new arrayadapter<string>(getactivity(), android.r.layout.simple_list_item_1, xmllist); listnewsfeed.setadapter(adapter); // onfoodmenuitemsdbaddfinished(); } }

}

try using

setretaininstance(true);

in oncreate() fragment

android eclipse android-fragments android-viewpager

visual c++ - How to cin data to store in a struct defined in another header file? -



visual c++ - How to cin data to store in a struct defined in another header file? -

i working on homework , stuck @ place. helpful if help me this. using visual c++.

this header file class.

#ifndef caller_h #define caller_h #include <string> #include <time.h> #include "nodedata.h" using namespace std; class caller { private: int phone_number; void setphonenumber(){ int min = 300000; int max = 800000; phone_number = min + rand()%(max-min+1); } string callers_name; string message; }; #endif

i trying store string of name , message above header file getting error. have searched on google , 1 possible solution: "cin >> caller.callers_name;" still getting error. same "cin >> caller.message;".

int _tmain(int argc, _tchar* argv[]) { queuelist l; caller * caller = null; int choice; const int columnsize = 3; string columnnames[columnsize]; cout <<"\n\t\tanz phone call center simulation\n"; cout <<"\n\tpress 1 create phone call caller.\n"; cout <<"\tpress 2 receive phone call consultant.\n"; cout <<"\tpress 3 print callers.\n\tchoice: "; cin >>choice; if (choice == 1){ cout <<"\n\tplease leave name , message.\n"; cout <<"\tenter name: "; cin >> caller.callers_name; cout <<"\n\tmessage: "; cin >> caller.message; }else if (choice == 2){ } .............. system("pause"); homecoming 0; }

visual-c++