Tuesday 15 April 2014

c# - Creating an object array with a different type from an existing object array in Javascript -



c# - Creating an object array with a different type from an existing object array in Javascript -

using lambdas , linq in c#, can create new collection type based on collection different type. instance:

var array = new list<foo> { new foo { name = "john", age = "21", title = "mr." } }; // can utilize select function create collection different type var modifiedarray = array.select(foo => new bar { title = foo.title });

i wondering if there improve way in javascript. have:

var array = [{name: 'john', age: '21', title: 'mr.'}]; var modifiedarray = []; array.foreach(function(foo){ modifiedarray.push({title: foo.title}); });

yes. can utilize array.prototype.map

var modifiedarray = array.map(function(x){ homecoming {title: x.title} });

javascript c# arrays

angularjs - Refreshing $translate after language changed -



angularjs - Refreshing $translate after language changed -

i have problem refreshing $translate property. initially, set "eng". function takes "de" , set it. when retrieve parameter 'hey' still value english. not why.

$rootscope.changelanguage = function(languagekey) { $translate.uses(); //eng $tanslate('hey'); // property eng $translate.uses(languagekey); $translate.uses(); //de $translate('hey'); // property eng !!! };

$rootscope.changelanguage = function(languagekey) { $translate.uses(); //eng $tanslate('hey'); // property eng $translate.uses(languagekey).then(function(data){ $scope.text = $tanslate('hey'); }); //de };

angularjs angular-translate

sql - Join 3 tables in Symfony2 -



sql - Join 3 tables in Symfony2 -

i have problem query in symfony2, have 3 entites (they simplified bit):

class grouping { /** * @var integer * * @orm\column(name="id", type="integer") * @orm\id * @orm\generatedvalue(strategy="auto") */ protected $id; /** * @var string * * @orm\column(name="name", type="string", length=255) */ protected $name; /** @orm\onetomany(targetentity="groupmember", mappedby="family") */ protected $groupmembers; class groupmember { /** * @var integer * * @orm\column(name="id", type="integer") * @orm\id * @orm\generatedvalue(strategy="auto") */ protected $id; /** * @orm\column(name="group_member_type", type="integer") */ protected $groupmembertype; /** * @orm\manytoone(targetentity="group", inversedby="groupmembers") * @orm\joincolumn(name="group_id", referencedcolumnname="id", nullable=false) */ protected $group; /** * @orm\manytoone(targetentity="test\userbundle\entity\user", inversedby="memberships") * @orm\joincolumn(name="user_id", referencedcolumnname="id", nullable=false) */ protected $user;

user -> standard fosuserbundle user

i want create query returns groups current user grouping member. tell me how that?

here try:

select g (group g inner bring together groupmember gm on g.id=gm.group_id) inner bring together fos_user u on gm.user_id = u.id u.id = 6

but returns

unknown column 'g' in 'field list'

using query builder, assuming you've fetched user , stored in $userobject , bundle name bundlename:

$groups = $this->getdoctrine()->getmanager()->createquerybuilder() ->select('g') ->from('bundlename:group', 'g') ->innerjoin('g.groupmembers', 'gm') ->innerjoin('gm.user', 'u') ->where('u = :user') ->setparameter('user', $userobject) ->getquery() ->getresult();

you need create sure relational mappings correct.

/** @orm\onetomany(targetentity="groupmember", mappedby="family") */ protected $groupmembers;

should be

/** @orm\onetomany(targetentity="groupmember", mappedby="group") */ protected $groupmembers;

sql symfony2 doctrine2

web services - how to work with soap webservice in android -



web services - how to work with soap webservice in android -

i'm new user in android. want work soap webservice. found illustration don't work me :-(

it's url of webservice : http://parsnerkh.com/webservice/server.wsdl?

and methode name : cats

and output : cat1,cat2,...

it's test webservice php : http://parsnerkh.com/webservice/test-cats.php

please help me.

i utilize code :

import android.os.asynctask; import android.os.bundle; import android.app.activity; import org.ksoap2.soapenvelope; import org.ksoap2.serialization.propertyinfo; import org.ksoap2.serialization.soapobject; import org.ksoap2.serialization.soapprimitive; import org.ksoap2.serialization.soapserializationenvelope; import org.ksoap2.transport.httptransportse; import com.example.webserviceactivity.r; import android.util.log; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.edittext; import android.widget.textview; public class mainactivity extends activity { private final string namespace = "urn:appstore"; private final string url = "http://parsnerkh.com/webservice/helloserverwsdl.php"; private final string soap_action = "action:urn:appstore/appstoreporttype/catsrequest"; private final string method_name = "cats"; private string tag = "pgguru"; private static string celcius; private static string fahren; button b; textview tv; edittext et; public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); //celcius edit command et = (edittext) findviewbyid(r.id.edittext1); //fahrenheit text command tv = (textview) findviewbyid(r.id.tv_result); //button trigger web service invocation b = (button) findviewbyid(r.id.button1); //button click listener b.setonclicklistener(new onclicklistener() { public void onclick(view v) { //check if celcius text command not empty if (et.gettext().length() != 0 && et.gettext().tostring() != "") { //get text command value celcius = et.gettext().tostring(); //create instance asynccallws asynccallws task = new asynccallws(); //call execute task.execute(); //if text command empty } else { tv.settext("please come in celcius"); } } }); } public void getfahrenheit(string celsius) { //create request soapobject request = new soapobject(namespace, method_name); //property holds input parameters /*propertyinfo celsiuspi = new propertyinfo(); //set name celsiuspi.setname("celsius"); //set value celsiuspi.setvalue(celsius); //set datatype celsiuspi.settype(double.class); //add property request object request.addproperty(celsiuspi);*/ //create envelope soapserializationenvelope envelope = new soapserializationenvelope( soapenvelope.ver11); envelope.dotnet = true; //set output soap object envelope.setoutputsoapobject(request); //create http phone call object httptransportse androidhttptransport = new httptransportse(url); seek { //invole web service androidhttptransport.call(soap_action, envelope); //get response soapprimitive response = (soapprimitive) envelope.getresponse(); //assign fahren static variable fahren = response.tostring(); } grab (exception e) { log.e("ads","ad"); e.printstacktrace(); } } private class asynccallws extends asynctask<string, void, void> { @override protected void doinbackground(string... params) { log.i(tag, "doinbackground"); getfahrenheit(celcius); homecoming null; } @override protected void onpostexecute(void result) { log.i(tag, "onpostexecute"); tv.settext(fahren + "° f"); } @override protected void onpreexecute() { log.i(tag, "onpreexecute"); tv.settext("calculating..."); } @override protected void onprogressupdate(void... values) { log.i(tag, "onprogressupdate"); } }

and recive error :

10-08 22:09:24.536: w/system.err(21468): org.xmlpull.v1.xmlpullparserexception: expected: end_tag {http://schemas.xmlsoap.org/soap/envelope/}body (position:end_tag </{http://schemas.xmlsoap.org/soap/envelope/}soap-env:fault>@2:209 in java.io.inputstreamreader@418ea258) 10-08 22:09:24.546: w/system.err(21468): @ org.kxml2.io.kxmlparser.require(kxmlparser.java:2046) 10-08 22:09:24.546: w/system.err(21468): @ org.ksoap2.soapenvelope.parse(soapenvelope.java:138) 10-08 22:09:24.546: w/system.err(21468): @ org.ksoap2.transport.transport.parseresponse(transport.java:63) 10-08 22:09:24.556: w/system.err(21468): @ org.ksoap2.transport.httptransportse.call(httptransportse.java:100) 10-08 22:09:24.556: w/system.err(21468): @ com.prgguru.android.mainactivity.getfahrenheit(mainactivity.java:85) 10-08 22:09:24.556: w/system.err(21468): @ com.prgguru.android.mainactivity$asynccallws.doinbackground(mainactivity.java:101) 10-08 22:09:24.556: w/system.err(21468): @ com.prgguru.android.mainactivity$asynccallws.doinbackground(mainactivity.java:1) 10-08 22:09:24.556: w/system.err(21468): @ android.os.asynctask$2.call(asynctask.java:287) 10-08 22:09:24.556: w/system.err(21468): @ java.util.concurrent.futuretask.run(futuretask.java:234) 10-08 22:09:24.556: w/system.err(21468): @ android.os.asynctask$serialexecutor$1.run(asynctask.java:230) 10-08 22:09:24.556: w/system.err(21468): @ java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor.java:1080) 10-08 22:09:24.556: w/system.err(21468): @ java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:573) 10-08 22:09:24.556: w/system.err(21468): @ java.lang.thread.run(thread.java:856)

use ksoap library consume soap webservice in android. follow below tutorial, has nice illustration consume soap service using ksoap lib. http://code.tutsplus.com/tutorials/consuming-web-services-with-ksoap--mobile-21242

android web-services soap wsdl

Javascript - how do i do a array group and count it, like in MySQL group by given column id? -



Javascript - how do i do a array group and count it, like in MySQL group by given column id? -

i have big array bellow, need grouping first column , count total of channel existence.

for example:

var original_db = [ ["channel1", "online"], ["channel2", "offline"], ["channel3", "online"], ["channel1", "online"], ["lot more"].... ]

expected result original result need be:

var custom_db = [ ["channel1", 2], ["channel2", 0], ["channel3", 1] ]

edit:

for(var key in original_db) { var i; (i = 0; < original_db.length; += 1) { if (original_db[i][0] === original_db[key][0]) { original_db.splice(i, 1); return; } } } console.log(original_db);

use object properties first elements maintain count:

var counts = {}; (var = 0; < original.length; i++) { var key = original[i][0]; if (counts[key]) { counts[key]++; } else { counts[key] = 1; } }

you can turn final array, although i'm not sure why prefer on counts object:

final = []; (var key in counts){ final.push([key, counts[key]]); }

javascript multidimensional-array duplicates

c - Does this code ungetch() '\n'? -



c - Does this code ungetch() '\n'? -

i searched everywhere, cannot find reply this! i'm working on exercise k&r c books function phone call getop. when input illustration 123, code checks each element of input, , stops when not digit. in illustration '\n'; ungetch( '\n' )?

int getop(char s[]) { int i, c; while ((s[0] = c = getch()) == ' ' || c == '\t') ; s[1] = '\0'; if (!isdigit(c) && c != '.') homecoming c; /* not number */ = 0; if (isdigit(c)) /*collect integer part*/ while (isdigit(s[++i] = c = getch())) ; if (c == '.') /*collect fraction part*/ while (isdigit(s[++i] = c = getch())) ; s[i] = '\0'; if (c != eof) ungetch(c); homecoming number; }

ungetch function:

void ungetch(int c) { if(bufp < maxbuf) { printf("ungetch has been called\n"); buf[bufp++] = c; } else printf("the buffer full\n"); }

i thought eof window ctrl+z , , '\n' else...?

iso/iec 9899, programming languages — c:

eof ... expands integer constant expression, type int , negative value, returned several functions indicate end-of-file, is, no more input stream

ctrl-z on windows input key combination causes no more characters returned, not character equivalent of ctrl-z (0x1a).

\n (new line) moves active position initial position of next line.

as original question: since negative value eof different (unsigned char) value, yes, code ungetch() '\n'.

c

javascript - Bootstrap 3 after navbar collapse, toggle wont reopen nav -



javascript - Bootstrap 3 after navbar collapse, toggle wont reopen nav -

i trying solve issue when clicked on navbar menu item in mobile view navbar remained expanded. didn't work me menu item pointing div id. read here of solution add together below href tag.

data-toggle="collapse" data-target=".navbar-collapse"

this did not work me work using javascript prepare found on github https://github.com/twbs/bootstrap/issues/12852

$(document).on('click','.navbar-collapse.in',function(e) { if( $(e.target).is('a') ) { $(this).collapse('hide'); } });

now problem after navbar hidden not open sec time.

anyone else have problem or solution?

change collapse parameter hide toggle.

$(this).collapse('toggle');

see more @ bootstrap docs.

javascript jquery twitter-bootstrap

CakePHP Database connection "Mysql" is missing, or could not be created. core.php and bootstrap.php -



CakePHP Database connection "Mysql" is missing, or could not be created. core.php and bootstrap.php -

i have looked answers before posted question, , seems problem in core.php or bootstrap.php file. i've seen said need alter prefixes or that, don't understand should alter them to. can help me please? here error page:

database connection "mysql" missing, or not created. error: internal error has occurred.

stack trace core/cake/model/datasource/dbosource.php line 260 → mysql->connect() core/cake/model/connectionmanager.php line 105 → dbosource->__construct(array) core/cake/model/model.php line 3476 → connectionmanager::getdatasource(string) core/cake/model/model.php line 1126 → model->setdatasource(string) core/cake/model/model.php line 3498 → model->setsource(string) core/cake/model/model.php line 1355 → model->getdatasource() core/cake/view/helper/formhelper.php line 207 → model->schema() core/cake/view/helper/formhelper.php line 459 → formhelper->_introspectmodel(string, string) app/view/layouts/default.ctp line 85 → formhelper->create(string, array) core/cake/view/view.php line 935 → include(string) core/cake/view/view.php line 897 → view->_evaluate(string, array) core/cake/view/view.php line 529 → view->_render(string) core/cake/view/view.php line 474 → view->renderlayout(string, string) core/cake/controller/controller.php line 952 → view->render(string, null) app/controller/pagescontroller.php line 69 → controller->render(string) [internal function] → pagescontroller->display(string) core/cake/controller/controller.php line 490 → reflectionmethod->invokeargs(pagescontroller, array) core/cake/routing/dispatcher.php line 185 → controller->invokeaction(cakerequest) core/cake/routing/dispatcher.php line 160 → dispatcher->_invoke(pagescontroller, cakerequest, cakeresponse) app/webroot/index.php line 108 → dispatcher->dispatch(cakerequest, cakeresponse)

have proper connection between site , database? reason can think of issue. check you're configuration settings in database.php file

php mysql cakephp cakephp-2.0

sap - How to use the result of SQL aggregate in IF statement -



sap - How to use the result of SQL aggregate in IF statement -

i trying script procedure in hana, , have requirement compare week id's of 2 tables. if week id1 > week id2, have insert new records table has id2. tried below logic, did not work.

here, logic within if not executing, though

var1 varchar(2); var2 varchar(2); begin select max(fiscal_wk) var1 "xxx"."outlook_facts"; select max(fiscal_wk) var2 "xxx"."outlook"; if :var2 > :var1 select max(outlookid) test "xxx"."outlook_facts"; end if; end;

i pretty new this, please help.

in code illustration don't assign values :var1 or :var2, both variables remain empty.

try

select max(fiscal_wk) var1 :var1 "xxx"."outlook_facts"; select max(fiscal_wk) var2 :var2 "xxx"."outlook"; if :var2 > :var1 select max(outlookid) test "xxx"."outlook_facts"; end if;

you could, pack in single sql statement. that's take :)

sap hana

python - Filtering by foreign key in dropdown -



python - Filtering by foreign key in dropdown -

i'm using django-filters.

my auto model has manufacturer foreign key . want filter cars dropdown populated manufacturers in database.

class car(models.model): slug = models.slugfield(unique=true) name = models.charfield(max_length=256) cost = models.decimalfield(max_digits=10,decimal_places=5) manufacturer = models.foreignkey(manufacturer)

my filter blank text field, can come in manufacturer name , submit filter way. dropdown much more suitable, haven't been able find way this. here filter model now:

class carfilter(django_filters.filterset): manufacturer = django_filters.charfilter(name="manufacturer__name") class meta: model = auto fields = ['name', 'manufacturer']

just don't define manufacturer filter field at all , django-filter utilize default filter field (which drop down). should working:

class carfilter(django_filters.filterset): class meta: model = auto fields = ['name', 'manufacturer']

python django filter django-filter

ios - Instantiate view with XIB -



ios - Instantiate view with XIB -

i have xib created next guide (how create custom ios view class , instantiate multiple copies of (in ib)?) have question:

how can instantiate if code?

so should write in viewdidload instead of

self.myview = [[myview alloc] initwithframe:self.view.bounds];

i know how instantiate storyboard, have no thought how code. thanks!

you have add together -loadnibnamed method following:

add next code your_view init method:

nsarray *subviewarray = [[nsbundle mainbundle] loadnibnamed:@"your_nib_name" owner:self options:nil]; uiview *mainview = [subviewarray objectatindex:0]; [self addsubview:mainview];

refer these 2 questions here:

adding custom subview (created in xib) view controller's view - doing wrong

ios: custom view xib

edit:

in viewcontroller.m file

#import customview.h <--- //import your_customview.h file - (void)viewdidload { [super viewdidload]; customview *customview = [[customview alloc]init]; [self.view addsubview:customview]; }

ios objective-c

hadoop.hdfs_clusters.default.webhdfs_url Error in Hue -



hadoop.hdfs_clusters.default.webhdfs_url Error in Hue -

can help me i'm getting error in hue.

current value: http://localhost:50070/webhdfs/v1 failed create temporary file "/tmp/hue_config_validation.15785472045199379485"

fyi, i'm using cloudera manager 5.1.3 , hue 3.6.

ok solve own problem. cause of error namenode in safe mode.

this command create namenode leave safemode.

sudo -u hdfs hdfs dfsadmin -safemode leave

for more info why namenode safe mode.

https://hadoop.apache.org/docs/r2.5.1/hadoop-project-dist/hadoop-hdfs/hdfsuserguide.html#safemode

hadoop hue

javascript - Are these statements functionally equivalent? -



javascript - Are these statements functionally equivalent? -

as far can tell function same, wanted create sure. utilize latter statement less code , seems more efficient.

function updaterunningtotals(taxexempt, disctype, discamt){ if (typeof taxexempt === 'undefined') { taxexempt = false; } taxexempt = taxexempt || false; }

i have been using if, have seen latter statement in open source projects. same thing? performance benefit?

edit: taxexempt, in scenario may not passed in.

> if (typeof taxexempt === 'undefined') { taxexempt = false; }

in case, textexempt set false if value undefined.

> taxexempt = taxexempt || false;

in case, taxexempt set false if value coerces false (i.e. toboolean(taxexempt) returns false), e.g. might null, 0, false, nan, '' or undefined.

so no, not functionally equivalent. , choosing sec because it's less code not sound logic. first clearer logic most.

javascript

asp.net mvc - while MVC model value to Javascript get error NaN -



asp.net mvc - while MVC model value to Javascript get error NaN -

i have 2 textbox , 1 hidden input.

class="snippet-code-js lang-js prettyprint-override"> function isnumberkey(evt) { var charcode = (evt.which) ? evt.which : event.keycode if (charcode > 31 && (charcode != 46 && (charcode < 48 || charcode > 57))) homecoming false; homecoming true; } function getreceiveamount(ctr) { var x = $("#sendamount").val(); var y = $("#sendingexchangecommission").val(); alert(x) alert(y) var total = (x * y).tofixed(2); $("#recieveamount").val(total); } class="snippet-code-html lang-html prettyprint-override"> @model turkex.models.fromto @{ viewbag.title = "exchange"; layout = "~/views/layoutpages/sitelayout.cshtml"; } @using (html.beginform("exchange", "home", formmethod.post, new { enctype = "multipart/form-data" })) { <input type="hidden" value="@model.sendingexchangecommission" id="sendingexchangecommission" name="sendingexchangecommission"/> <div class="form-group"> <div class="exchange-amount-label"> <label>@turkex.globalization.exchanges.resource.amount</label> </div> <input class="exchange-amount" id="sendamount" name="sendamount" value="@model.gateway.mintransfer" onkeypress="return isnumberkey(event)" onchange="return getreceiveamount(this);" /> </div> <div class="form-group"> <div class="exchange-amount-label"> <label for="exampleinputemail1">@turkex.globalization.exchanges.resource.amount</label> </div> <input class="exchange-amount" id="recieveamount" name="recieveamount" @*value="@model.sendingexchangecommission"*@> </div> <button type="submit" value="exchange" class="exchange-button">@turkex.globalization.exchanges.resource.exchange</button> </div> <div class="clearfix"></div> }

but when come in number textbox 1 (id = sendamount) textbox 2 shows nan

if alter y manualy "10.1" there no problem.

var y = $("#sendingexchangecommission").val();

isnt work?

at first glance, there doesn't seem populating y variable in getreceiveamount():

// value empty/null if sendingexchangecommission empty: var y = $("#sendingexchangecommission").val();

so when seek calculate total here:

var total = (x * y).tofixed(2);

you might calculating numeric value x null (or nan) value, either give 0 or nan result:

// examples show how multiplying unknown // info types can give nan // number * string = nan var total = (1 * "somestring").tofixed(2); // --> nan // number * nan = nan var total = (1 * nan).tofixed(2); // --> nan // number * empty string = 0 var total = (1 * " ").tofixed(2); // --> 0.00 // number * 0 = 0 var total = (1 * 0).tofixed(2); // --> 0.00

so check create sure getting numeric value in y (#sendingexchangecommission) before calculating total. can see example, if y (#sendingexchangecommission) not empty, not numeric value, nan result.

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //

update: want check if value within input field in fact, number. includes number values comma in them. if scheme of writing numbers in country uses comma instead of period separate values (0.0996 vs 0,0996), need scrub out comma, because look result in nan:

// comma in numeric string result in nan var total = (1 * "0,0996").tofixed(2); // --> nan

where look result in 996.0

// give proper number var total = (1 * "0.0996").tofixed(2);

so of import thing consider here, when grabbing values html text .val() , or .value, string returned you, if want perform numeric calculations on string, need sure string value has been converted number. if comma within string, value can't converted number.

lastly, maintain in mind parsefloat() give unusual behavior if feed comma within of numeric values, example, here output of parsefloat("0,0996") vs parsefloat("0.0996"), notice how parsefloat comma gives unusual behavior, but period works expected:

// results in 0 (zero) parsefloat("0,0996") // --> 0 // results in 0.0996 parsefloat("0.0996") // --> 0.0996

so think might simple comma in numeric values throwing off.

hope helps.

javascript asp.net-mvc model-view-controller nan

arrays - Save data even if the app re-opens - Swift Xcode 6 iOS -



arrays - Save data even if the app re-opens - Swift Xcode 6 iOS -

i'm working on app can randomize love couples. fun thing, okey!?!? :d problem, or maybe not problem thing can much improve if thing working. in origin need write in names. , thats takes time... should utilize core date? don't knows core info i'm not sure. love if god come me , wrote total code can remember array if app , phone shuts down. have done in java, simpel in java? great!

//thank, anton

for heavy, complex info structures want utilize core data, https://developer.apple.com/library/mac/documentation/cocoa/conceptual/coredata/articles/cdtechnologyoverview.html#//apple_ref/doc/uid/tp40009296-sw1

but seeing want store array, should nsuserdefaults. nsuserdefaults store given info long app not deleted. want create kind of custom datastorage class this.

@interface datastorage : nsobject <nscoding> @property (nonatomic, strong) nsmutablearray *arraytostore; + (instancetype)sharedinstance; - (void)save; @end

above .h file. can see, follows nscoding protocols. provides access methods allow encode data. utilize save method write info disk.

#import "datastorage.h" @implementation datastorage @synthesize arrayofpeople = _arraytostore; + (datastorage *)sharedinstance { static datastorage *state = nil; if ( !state ) { nsdata *data =[[nsuserdefaults standarduserdefaults] objectforkey:@"datastoragekey"]; if (data) { state = [nskeyedunarchiver unarchiveobjectwithdata:data]; } else { state = [[datastorage alloc] init]; } } homecoming state; } - (id)init{ if (self = [super init]) { if (!_arraytostore) { _arraytostore = [[nsmutablearray alloc] init]; } } homecoming self; } - (instancetype)initwithcoder:(nscoder *)decoder { self = [self init]; if (self) { if ([decoder decodeobjectforkey:@"datastoragearraytostore"]) { _arraytostore = [[decoder decodeobjectforkey:@"datastoragearraytostore"] mutablecopy]; } } homecoming self; } - (void)encodewithcoder:(nscoder *)encoder { [encoder encodeobject:_arraytostore forkey:@"datastoragearraytostore"]; } - (void)save { nsdata *appstatedata = [nskeyedarchiver archiveddatawithrootobject:self]; [[nsuserdefaults standarduserdefaults] setobject:appstatedata forkey:@"datastoragekey"]; [[nsuserdefaults standarduserdefaults] synchronize]; } @end

here .m file, pretty much evaluates see if there saved instance of class, , if not create one. [datastorage sharedinstance]...

when want store data, create class available said file, #import "datastorage.m , use

nsstring *testdata = [nsstring stringwithformat: @"test info string"]; [[datastorage sharedinstance].arraytostore addobject: testdata]; [datastorage sharedinstance] save];

ios arrays xcode swift save

Laravel 4 - URI Parameters in Implicit Controllers -



Laravel 4 - URI Parameters in Implicit Controllers -

how uri parameters in methods within implicit controller?

first, define base of operations route:

route::controller('users', 'usercontroller');

then,

class usercontroller extends basecontroller { public function getindex() { // } public function postprofile() { // } public function anylogin() { // } }

if want pass aditional parameters in uri, http://myapp/users/{param1}/{param2} , how can read param1 , param2 within respectve method? in example, getindex()

if want have url http://myapp/users/{param1}/{param2} need have in controller this:

route::get('users/{param1}/{param2}', 'usercontroller@getindex');

and access it:

class usercontroller extends basecontroller { public function getindex($param1, $param2) { // } }

but hey, can this, routes same:

class usercontroller extends basecontroller { public function getindex() { $param1 = input::get('param1'); $param2 = input::get('param2'); } }

but url like: http://myapp/users?param1=value&param2=value

laravel laravel-4 parameters controller routes

Extracting a value from Json object in C# -



Extracting a value from Json object in C# -

i have json document , trying value analoginput each channel 1 4. have tried code:

jobject originalobject = jobject.parse(testjsonobject); var analoginputtruevalues = originalobject.descendants().oftype<jproperty>().where(p => p.name == "digitalinput").select(x => x.value).toarray();

where testjsonobject json file gets loaded method.

debugging code, value analoginputtruevalues is:

{newtonsoft.json.linq.jtoken[4]} [0]: {13} [1]: {13} [2]: {14} [3]: {14}

,which correct. interested have array or list {"13","13","14","14"}. can not move forwards since can not extract exact values , have them in list or array. when do:

digitalinputtruevalues.getvalue(0) {13} base: {13} hasvalues: false type: string value: "13"

i can't extract value, interested in. how can around kind of problem , extract desired values? object working follows:

{ "module": { "serial": "3", "label": "a", "lat": "b", "long": "c", "channels": [ {"channel": "1", "label": "channel 1", "analoginput": "13", "analoginputraw": "13", "analoginputscale": "raw", "digitalinput": "off"}, {"channel": "2", "label": "channel 2", "analoginput": "13", "analoginputraw": "13", "analoginputscale": "raw", "digitalinput": "on"}, {"channel": "3", "label": "channel 3", "analoginput": "14", "analoginputraw": "14", "analoginputscale": "raw", "digitalinput": "on"}, {"channel": "4", "label": "channel 4", "analoginput": "14", "analoginputraw": "14", "analoginputscale": "raw", "digitalinput": "on"} ], "variables": [ {"1": "0"}, {"2": "0"}, {"3": "1"}, {"4": "0"} ] } }

you need include tostring() in select look after x.value:

jobject originalobject = jobject.parse(json); var analoginputtruevalues = originalobject.descendants() .oftype<jproperty>() .where(p => p.name == "analoginput") .select(x => x.value.tostring()) .toarray();

working example: https://dotnetfiddle.net/tu5mc8

alternative method using strongly-typed classes: https://dotnetfiddle.net/us4bs0

c# json json.net

java - Bigquery.jobs().query returns epoch time 1.295353708E9 for timestamp column -



java - Bigquery.jobs().query returns epoch time 1.295353708E9 for timestamp column -

bigquery.jobs().query().execute returns epoch time timestamp , epoch time includes dot trailing alphanumeric value(1.295353708e9) converting value java timestamp fails;

object v = checknullandgetcolumnvalue(columnindex); long epoch = long.parselong(v.tostring()); string date = new java.text.simpledateformat("mm/dd/yyyy hh:mm:ss").format(new java.util.date (epoch*1000));

the returned value 1.295353708e9 same 1295353708 not sure best way handle bq web ui renders it.

any help highly appreciated!

this should work:

long epoch = double.valueof('1.295353708e9').longvalue(); string date = new simpledateformat("mm/dd/yyyy hh:mm:ss") .format(new date (epoch*1000));

with given illustration value, date string resolves 01/18/2011 21:28:28.

java google-bigquery

php - InnerJoin with Doctrine2 (Symfony2) -



php - InnerJoin with Doctrine2 (Symfony2) -

i new symfony2 (~ 1 week). have manytoone on budgetdata entity joins id of entity budgetdescription. created sql query want replicate doctrine :

class="lang-sql prettyprint-override">select d, e budgetdata d inner bring together budgetdescription e on d.budgetdescription_id = e.id

budgetdata table : id, year, value, budgetdescription_id (fk)

budgetdescription table : id, descriptionname

what tried far :

class="lang-php prettyprint-override"> $em = $this->getdoctrine()->getmanager(); $qb = $em->getrepository('mainbundle:budgetdata'); $qb = $em->createquerybuilder('d'); $dataquery = $qb->select('d, c') ->innerjoin('c.id', 'c', join::on, 'd.budgetdescription_id = c.id') ->getquery(); $dataquery = $dataquery->getarrayresult();

any thought how can sql query in dql ?

thank !

if have relation in budgetdataentity called budgetdescription attribute $budgetdescription, in budgetdatarepository :

public function myinnerjoin() { $qb = $this->createquerybuilder('f') ->select('f','g') ->innerjoin('f.budgetdescription', 'g'); homecoming $qb->getquery()->getarrayresult(); }

and in controller

$repository = $this->getdoctrine()->getmanager()->getrepository('acmebundle:budgetdata'); $result = $repository->myinnerjoin();

that guess

php symfony2 doctrine2

Copying every nth Rows in excel -



Copying every nth Rows in excel -

if have 30 rows, example, , want re-create 1st, 2nd , 3rd, skip five, re-create next 3 , skip 5 1 time again , re-create next 3 rows: how can this? far have formula

=offset(sheet1!$a$1,(row()-1)*5,0)

which gets me 1 cell value entire row copied sheet.

any help great! thanks

here hint: row number modulus 8 in (1,2,3) identifies target row numbers. come in in first column, first row , re-create downwards each column: =if(and(mod(row(sheet1!a1),8) > 0,mod(row(sheet1!a1),8) < 4),sheet1!a1,"")

excel excel-vba optimization excel-formula excel-2003

django - Wrapping fields into additional JSON object -



django - Wrapping fields into additional JSON object -

what way alter construction of json returned django rest framework's default model serialiers?

example -

restaurant object returned drf right now:

{ "id":9, "label":"pizza hut" "like_id:":32, "like_quantity":2 }

more desirable json structure:

{ "id":9, "label":"pizza hut", "social": { "like_id:":32, "like_quantity":2 } }

to create json structure, want few fields default json nested under new field.

if right, want this:

{ "id":9, "label":"pizza hut", "social": { "like_id:":32, "like_quantity":2 } }

to result of request.

you can edit homecoming values within generic view, if using one, eg:

class restaurantviewset(mixins.retrievemodelmixin, viewsets.genericviewset): queryset = restaurant.objects.all() serializer_class = restaurantserializer def retrieve(self, request, pk=none): queryset = restaurant.objects.all() restaurant = get_object_or_404(queryset, pk=pk) serializer = restaurantserializer(user,context={'request': request}) results = { "id":serializer.data['id'], "label":serializer.data['label'], "social": { "like_id:":serializer.data['like_id'], "like_quantity":serializer.data['like_quantity'] } } homecoming response(results)

django django-rest-framework

mongoid3 - Create Tag Cloud with Mongoid Taggable Gem -



mongoid3 - Create Tag Cloud with Mongoid Taggable Gem -

i want create tag cloud can acts-as-taggable-on gem, illustration acts-as-taggable-on gem readme:

<% tag_cloud(@tags, %w(css1 css2 css3 css4)) |tag, css_class| %> <%= link_to tag.name, { :action => :tag, :id => tag.name }, :class => css_class %> <% end %>

the mongoid_taggable gem using different method called tags_with_weight returns array of tags , number of times used dont know how replicate tag cloud based on information.

acts-as-taggable-on mongoid3

gcc - c++ Qt Compile error -



gcc - c++ Qt Compile error -

i trying compile illustration library. have qt installed think have link , dont know how. error:

g++ face_recognition.cpp -o test

in file included face_recognition.cpp:29:0: /usr/local/include/openbr/openbr_plugin.h:22:23: fatal error: qdatastream: no such file or directory #include ^ compilation terminated.

you can't compile qt application straight g++ because application must first go through qt's moc compiler.

if want build qt application cmd-line, create sure define appropriate .pro file specifies qt modules , other 3rd party headers/libraries want might use. instance:

qt += core widgets sources += \ main.cpp

then invoke qmake on command line in same directory .pro file build appropriate makefiles, , execute make build app.

qt gcc g++ openbr

sql - How to migrate mysql database from Ubintu to Windows? -



sql - How to migrate mysql database from Ubintu to Windows? -

i have database need migrate ubuntu windows system. created sql files info gets corrupted. there different approach or solution problem?

yes, works quirks. mysql uses same fileformats across platforms need share info directory. 1 problem info directory need have mysql owner , grouping in ubuntu. , windows case-insensitive , linux case-sensitive maintain names uniform: either whole name lowercase or uppercase not mix them.

in my.ini (in windows it's located somewhere c:\program files\mysql\mysql server 5.1. it's main configuration file mysql) file, should have line:

datadir="c:/programdata/mysql/mysql server 5.1/data/" example

change in both windows , linux ubuntu point 1 single physical folder (on partition file scheme windows recognize). work. file formats identical.

whether boot ubuntu, or windows 7, won't matter, 2 different builds of mysql looking info in same place. 1 time info modified in windows environment, boot ubuntu , info there, modified.

mysql sql database mysqldump rdbms

java - Import PFX file into Existing JKS file (NOT converting from .pfx to .jks) -



java - Import PFX file into Existing JKS file (NOT converting from .pfx to .jks) -

i have java web service , have implemented x.509 using jks files created java keytool.

keytool -genkey -keyalg rsa -sigalg sha1withrsa -validity 730 -alias myservicekey -keypass skpass -storepass sspass -keystore servicekeystore.jks -dname "cn=localhost" keytool -genkey -keyalg rsa -sigalg sha1withrsa -validity 730 -alias myclientkey -keypass ckpass -storepass cspass -keystore clientkeystore.jks -dname "cn=clientuser"

to found trust between client , server import server certs client , client certs server.

import server public key (certs) client.

keytool -export -rfc -keystore clientkeystore.jks -storepass cspass -alias myclientkey -file myclient.cer keytool -import -trustcacerts -keystore servicekeystore.jks -storepass sspass -alias myclientkey -file myclient.cer -noprompt

import client public key(certs) server

keytool -export -rfc -keystore servicekeystore.jks -storepass sspass -alias myservicekey -file myservice.cer keytool -import -trustcacerts -keystore clientkeystore.jks -storepass cspass -alias myservicekey -file myservice.cer -noprompt

both service , client written in java , working fine. have .net client , understanding if give same jave client certificates .net client i.e clientkeystore.jks should work, .net client having issues.

the .net client developer has insisted me utilize .pfx certificate generated, how can import .pfx certificate existing .jks file.

the examples have seen online require me create new .jks file.

thank you.

you can treat file java pkcs12 keystore. can utilize of same keytool commands, except additionally need specify -storetype pkcs12 since default jks. illustration works in jdk 1.6 , higher:

keytool -importkeystore -srckeystore mypfxfile.pfx -srcstoretype pkcs12 -destkeystore clientcert.jks -deststoretype jks

also see this thread. think answers question, if don't mind suggestion, output existing jks file p12 file, give p12 file .net client. solve issue if format issue. can next steps outlined here. if still have issues, should post .net client's exception otherwise cannot help you.

java x509 keytool pfx jks

visual studio online - how opshub support sync between vstf and vso? -



visual studio online - how opshub support sync between vstf and vso? -

i know opshub migration tool used migrating vstf vso, not supporting synchronization between vstf , vso. there way utilize opshub integration manager synchronization between vstf , vso.

yes. opshub integration manager supports bi-directional synchronization between wide variety of systems including team foundation server , visual studio online. can used bi-directional sync between tfs , vso. more info please reach out opshub @ http://www.opshub.com/main/index.php/company/contactus

visual-studio-online opshub

computer science - Complexity of the following algorithm to generate TaxiCab numbers? -



computer science - Complexity of the following algorithm to generate TaxiCab numbers? -

following algorithm generating taxicab numbers using priority queue(pq). vector arbitrary info type allows storage of 2 number , cubed sum. unaware(although don't need know), taxicab number integer can expressed sum of 2 cubes of integers in 2 different ways: a^3+b^3 = c^3+d^3. illustration 1729 = 12^3 + 1^3 = 10^3 + 9^3

for = 1..n pq.insert( vector(i^3+i^3,i,i) ) prev = vector(0, 0, 0) while not pq.empty() curr = pq.deletemin() if prev[0] == curr[0] print curr[0] taxicab number can expressed prev[1]^3 + prev[2]^3 , curr[1]^3 + curr[2]^3 prev = curr if curr[2] < n j = curr[2] + 1 pq.insert( vector(curr[1]^3 + j^3, curr[1], j) )

i know inserting item priority queue o(log n) not sure how relate space , time complexity. can help ?

it's no worst o(n^2 log n), though might possible give tighter bounds it.

this block of code:

if curr[2] < n j = curr[2] + 1 pq.insert( vector(curr[1]^3 + j^3, curr[1], j) )

makes code equivalent, more efficient than:

possibles = empty list = 1..n j in i+1..n possibles.append( vector(i^3 + j^3, i, j) ) sort(possible_numbers) = 1..n prev = possibles[i] curr = possibles[i + 1] if prev[0] == curr[0] print curr[0] taxicab number can expressed prev[1]^3 + prev[2]^3 , curr[1]^3 + curr[2]^3

the size of possibles list o(n^2), making sorting o(n^2 log(n)). sec loop o(n) makes code o(n^2 log n).

algorithm computer-science time-complexity

java - AsyncHttpClient in Runnable -



java - AsyncHttpClient in Runnable -

in app need implement kind of chat. instead of using longpoll connections sending get requests server 1 time every 5 seconds. chat not primary function in app. i'm using handler post runnable, in run method i'm using asynchttpclient. here's code:

chathandler = new handler(); chatrunnable = new runnable() { @override public void run() { final int pos = adapter.getcount(); asynchttpclient client = new asynchttpclient(); client.addheader("x-auth-token", user.getinstance(getapplicationcontext()).gettoken()); client.addheader("clienttype", "android"); seek { client.addheader("clientvesrion", (getpackagemanager().getpackageinfo(getpackagename(), 0)).versionname); } grab (packagemanager.namenotfoundexception e) { e.printstacktrace(); } requestparams params = new requestparams(); params.add("todo_id", todo.getserverid() + ""); params.add("from_id", messages.size() == 0 ? "0" : messages.get(messages.size() - 1).getid() + ""); client.settimeout(5000); client.get(getapplicationcontext(), getstring(r.string.server_path) + getstring(r.string.path_messages_from_id), params, new asynchttpresponsehandler(){ ... }); } }; chathandler.postdelayed(chatrunnable, 5000);

however, crashes @ client.get() next error:

fatal exception: main java.lang.outofmemoryerror: thread creation failed @ java.lang.vmthread.create(native method) @ java.lang.thread.start(thread.java:1050) @ java.util.concurrent.threadpoolexecutor.addworker(threadpoolexecutor.java:913) @ java.util.concurrent.threadpoolexecutor.execute(threadpoolexecutor.java:1295) @ java.util.concurrent.abstractexecutorservice.submit(abstractexecutorservice.java:81) @ com.loopj.android.http.asynchttpclient.sendrequest(asynchttpclient.java:893) @ com.loopj.android.http.asynchttpclient.get(asynchttpclient.java:612) @ ru.dotcapital.controlmanager.chatactivity$1.run(chatactivity.java:115) @ android.os.handler.handlecallback(handler.java:725) @ android.os.handler.dispatchmessage(handler.java:92) @ android.os.looper.loop(looper.java:176) @ android.app.activitythread.main(activitythread.java:5365) @ java.lang.reflect.method.invokenative(native method) @ java.lang.reflect.method.invoke(method.java:511) @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:1102) @ com.android.internal.os.zygoteinit.main(zygoteinit.java:869) @ dalvik.system.nativestart.main(native method)

some referenses @ google says happening when have lots of activities running , not finished, , lots of asynctasks running in 1 time, chatactivity 3rd activity.user phone call , have no asynctasks running in time when error appeared. suggestions?

i can't see broader context code, based on question said doing every 5 seconds, possible doing routine when don't have internet? don't see closing client using close() method. not calling close() not free resources if there no response, , continuous calls fill memory.

java android handler runnable asynchttpclient

multisite - Can i change wordpress plugins path in wp_options -



multisite - Can i change wordpress plugins path in wp_options -

i have multisite installation , want create plugins , uploads directory every site , possible alter site plugin , uploads path wp_options ?

the problem is, multisiteis supposed utilize 1 directory uploads , 1 plugins. thats purpose of it. however, can install plugin plugin organizer. can utilize plugins individually each page. if need own plugins , upload directories suggest create 1 wordpress site each site instead of multisite

wordpress multisite

oracle11g - How to access meta tables of oracle database from postgresql database -



oracle11g - How to access meta tables of oracle database from postgresql database -

my oracle database(11.2) , postgresql database(9.3.5)

my requirement extract info oracle database postgresql database purpose used oracle_fdw(foreign info wrapper concept).

i extracted info of particular schema(oracle db).

i able extract info of normal tables.but not able access meta tables all_tab_columns

i created server , user , provided server details , user mapping details(sys privileges) while accessing time it's giving me error

error: session foreign table "all_tab_columns" cannot authenticated sql state: hv00n detail: ora-12571: tns:packet author failure

postgresql oracle11g postgresql-9.3

angularjs - Angular How to build a directive template when properties via web service are needed -



angularjs - Angular How to build a directive template when properties via web service are needed -

basically need build control, need details web service before can build html. proper way this.

here have @ moment, not sure if right or not, or whether should using controller, should webservice.get() method in link method of directive?

advice/input much appreciated

app.directive('mydirective', ['webservice', '$compile', function (webservice, $compile) { 'use strict'; homecoming { restrict: 'a', link: function (scope, element, attrs) { // info server webservice.get().then(function(columns) { var html = ''; // add together html here // .... // loop through server info (var = 0; < columns.length; i++) { html += '<td>' + columns.name + '</td>; } // build rest of html here // .... // compile html angular utilize html = $compile(html)(scope); // set element html element.html(html); }); } }; }]);

angularjs angularjs-directive

ruby on rails - Is it worth trying to reuse test fixtures as much as possible? -



ruby on rails - Is it worth trying to reuse test fixtures as much as possible? -

i have work rails fixtures on existing project. switching factorygirl or not option.

in fixtures have generic 1 time (records appear in production database) plus fair portion of fixtures testing border cases. in case of blog app latter blog no posts, blog haven't been active while, or blog no follower.

what take on creating separate set of fixture records every border case versus trying reuse existing fixtures much possible? latter include mocking / stubbing calls specific methods (e.g. account.any_instance.expects(:post_limit).returns(1000) mocha) or creating records inconsistent application logic (say, having several users per business relationship when app allows have 1 user per account).

i avoid creating info fixtures uncommon utilize cases. if have few scenarios checked in multiple parts of app create them in fixtures because consider part of test language of app.

for border cases create info in test. either modifying known fixture record, or creating new records meet border case criteria. don't need tools mill girl create reusable factories. (every activerecord model factory.) can create named methods in module , include in test class.

i not mock models outlined. create records in test , test application behaves correctly.

def test_lots_of_posts business relationship = new_account_with_n_posts 100 assert(account.posts > 5) end def new_account_with_n_posts count business relationship = account.create! name: "temp account" count.times |n| account.posts.create! title: "temp post #{n}" end business relationship end

ruby-on-rails testing minitest

javascript - textarea.val() sends original value not edited -



javascript - textarea.val() sends original value not edited -

i have textarea in mvc project

<textarea id="edit-content" name="content" placeholder="text content goes here">@model.content</textarea>

but when seek send json phone call this

<script type="text/javascript"> function save() { var $title = $('#edit-title'), $content = $('#edit-content'), $messageloading = $('#message-edit-loading'), $messageerror = $('#message-edit-error'), $id = $('#edit-id'); updatecomment($id.val(), $title.val(), $content.val()) .done(function (data) { if (data.isvalid()) { $messageerror.html(''); $messageerror.removeclass('hidden'); $messageloading.removeclass('hidden'); $messageloading.html('the text saved'); } else { $messageerror.removeclass('hidden'); $messageerror.html(data.message); } }) .fail(function (xhr, message) { $messageerror.removeclass('hidden'); $messageerror.html('registration failed: ' + message); }) }; </script>

i original value of @model.content instead of new value.

edit

my script.js code

function updatecomment(id, title, content) { homecoming $.get("/chapter/getjson_update", { id: id, title: title, content: content }, 'json'); };

the entire code edit.cshtml

@model academia_unitate.models.chapter @{ viewbag.title = "edit " + model.title; layout = "~/views/shared/_layout.cshtml"; } @html.partial("~/views/shared/_tinymce.cshtml") <div id="edit"> <h1> edit @model.type.name </h1> <div class="" role="form"> <div class="form-group"> <label class="sr-only" for="title">title</label> <input class="form-control" type="text" id="edit-title" placeholder="enter title" value="@model.title" required="required" /> </div> <div class="form-group"> <label class="sr-only" for="content">content</label> <textarea id="edit-content" name="content" placeholder="text content goes here">@model.content</textarea> </div> <button type="submit" class="btn btn-success" id="save-btn" onclick="save()"><span class="glyphicon glyphicon-ok"></span> save</button> <span id="message-edit-loading" class="alert hidden"></span> <span id="message-edit-error" class="alert alert-danger hidden"></span> </div> </div> <input type="hidden" value="@model.id" id="edit-id"/> <script type="text/javascript"> function save() { var $title = $('#edit-title'), $content = $('#edit-content'), $messageloading = $('#message-edit-loading'), $messageerror = $('#message-edit-error'), $id = $('#edit-id'); updatecomment($id.val(), $title.val(), $content.val()) .done(function (data) { if (data.isvalid()) { $messageerror.html(''); $messageerror.removeclass('hidden'); $messageloading.removeclass('hidden'); $messageloading.html('the text saved'); } else { $messageerror.removeclass('hidden'); $messageerror.html(data.message); } }) .fail(function (xhr, message) { $messageerror.removeclass('hidden'); $messageerror.html('registration failed: ' + message); }) }; </script>

you have more 1 on page, either create id attributes unique or target index in jquery.

javascript jquery textarea

nsdate - iOS8 dateformatter not working with Timezone -



nsdate - iOS8 dateformatter not working with Timezone -

date string: fri, 03 oct 2014 21:14:01 est

i can nsdate above string using below code in ios 7:

@"eee, dd mmm yyyy hh:mm:ss z"

while in ios 8 getting nil date , have tried next formats nsdate no luck.

@"eee, dd mmm yyyy hh:mm:ss z" @"eee, dd mmm yyyy hh:mm:ss zzz"

can help me on this?

tushar

this bug in ios 8.0.2. if seek same code on ios 8 works file. file bug study apple can prepare it.

ios8 nsdate nsdateformatter

c# - Check if collection contains element with specific properties -



c# - Check if collection contains element with specific properties -

i have 2 collections different entities. how create them 1 collection unique info (companyname & productname & certid).

what seek : 1st collection iterate in loop , check if 2nd collection contains element same certid, productname , companyname. not sure if create good.

if element doesn't contains, need add together it.

releases.foreach( r => { if (!ratings.all(x => x.certid == r.certid && x.companynamewhenrated == r.companynameonstore && x.productnamewhenrated == r.productnameonstore)) { ratings.tolist().add(new urating { certid = r.certid, productnamewhenrated = r.productnameonstore, companynamewhenrated = r.companynameonstore, ucert = r.ucert, ragerating = r.ucert.uratings .where(u => u.certid == r.certid && u.productnamewhenrated != r.productnameonstore && u.companynamewhenrated != r.companynameonstore) .select(ur => ur.ragerating).first() }); } });

if (!ratings.all(...)) means ratings have match release, not want. utilize if(!ratings.any(...)) means of ratings has match release.

c# linq equals contains

debugging - Is it possible to use gdb and qemu to debug linux user space programs and kernel space simultaneously? -



debugging - Is it possible to use gdb and qemu to debug linux user space programs and kernel space simultaneously? -

so far, gdb + qemu, can step into/over linux kernel source code. possible debug user space programs simultaneously? example, single step programme user space kernel space can observe changes of registers on qemu monitor issuing info registers?

i accomplish using gdb command add-symbol-file add together userspace programs debugging information. must know these programs loading addresses. precise, have launch kernel debugging connecting gdb gdbserver usual; , then, can add together programme debugging information. can utilize .gdbinit script though. read this

debugging linux-kernel gdb qemu

PHP: Sorting MySQL result to multi-dimensional array -



PHP: Sorting MySQL result to multi-dimensional array -

now i'm tryin' sort mysql result multi-dimensional array type line in sql so, that's code:

function gettablevalues($table_name) { // $link = connect_db(); $front_end_query = "select * `".$table_name."` `type` = 'front_end'"; $front_end_query_result = mysql_query($front_end_query); $cur_row = 0; /*while ($line = mysql_fetch_assoc($queryresult)) { $values = $line; $cur_row++; }*/ $front_end = mysql_fetch_assoc($front_end_query_result); $i=0; while ($line = mysql_fetch_assoc($front_end_query_result)){ #if ($line['type'] === 'front_end'){ # $line[$line['type']][$line['name']] = $line['value']; # $line[$line['type']][$line['name']]['desc'] = $line['description']; # $line[$line['type']][$line['name']]['visible_name'] = $line['visible_name']; # $line[$line['type']][$line['name']]['write_roles'] = $line['write_roles']; # $line[$line['type']][$line['name']]['read_roles'] = $line['read_roles']; #} $values['front_end'][$line['name']] = $line; $i++; } homecoming $values; }

and mysql table:

id type write_roles read_roles name value description visible_name 1 front_end 0 title sometitle exampletitle title 2 front_end 0 description somedesc illustration description

and that's want get:

$config[(sometype)][(somename)] = (value of line) $config[(sometype)][(somename)][(someoption)] = (value of option)

e.g.: $config['front_end']['title']['description'] returns exampletitle

how can that?

upd0: tried echo array foreach, , it's returned just 1 row db. doing wrong?

$values = array(); //base array while ($line = mysql_fetch_assoc($front_end_query_result)){ //fetch rows //in base of operations array create new array under 'name' $values[$line['name']] = array(); //for each item in result set, add together new array foreach ($line $key => $value) { $values[$line['name']][$key] = $value; } }

php mysql arrays

algorithm - How to connect 2 shapes with straight lines (like a diagram editor) -



algorithm - How to connect 2 shapes with straight lines (like a diagram editor) -

i have 2 rects , need draw set of lines connect them. straight lines allowed (no diagonal).

initially i've made grid , i've used a* path finding algorithm find way connect 2 points located @ edges of figures.

it works seems little overkill; in fact can avoid obstacles check (the rect of objects) assuming can connect nearest (and visible) edges. can suggest me simpler algorithm it?

algorithm a-star

python - Apply a function to all instances of a class -



python - Apply a function to all instances of a class -

i looking way apply function instances of class. example:

class my_class: def __init__(self, number): self.my_value = number self.double = number * 2 @staticmethod def crunch_all(): # pseudocode starts here instances in my_class: instance.new_value = instance.my_value + 1

so command my_class.crunch_all() should add together new attribute new_value existing instances. guessing have utilize @staticmethod create "global" function.

i know maintain track of instances beingness defined adding my_class.instances.append(number) in __init__ , loop through my_class.instances, had no luck far either. wondering if more generic exists. possible?

register objects class @ initialisation (i.e. __init__) , define class method (i.e. @classmethod) class:

class foo(object): objs = [] # registrar def __init__(self, num): # register new object class foo.objs.append(self) self.my_value = num @classmethod def crunch_all(cls): obj in cls.objs: obj.new_value = obj.my_value + 1

example:

>>> a, b = foo(5), foo(7) >>> foo.crunch_all() >>> a.new_value 6 >>> b.new_value 8

python class

sql - Does order matter in theta join -



sql - Does order matter in theta join -

i got 3 relations

customer (customer_name, city) loan (loan_number, branch_name, amount) borrower (customer_name, loan_number)

find client name, city , loan amounts.

first query:

select c.customer_name, c.city, l.amount borrower b bring together loan l using (loan_number) bring together client c using (customer_name)

second query:

select c.customer_name, c.city, l.amount client c bring together borrower b using (customer_name) bring together loan l using (loan_number)

will 2 queries produce same result?

in inner joins (as opposed outer joins), order of tables not matter.

sql join

javascript - Make a controllers model available to the ApplicationController before it's loaded in Ember -



javascript - Make a controllers model available to the ApplicationController before it's loaded in Ember -

i trying access controller needed applicationcontroller (application needs practice), practicecontroller available after resource has been loaded through it's respective route-url visit. how, can create sure practicecontroller , it's content/model available @ times? specific, need flashcardarray available throughout application , @ times, when practice-route hasn't been visited, loaded yet. help!

here code:

app.router.map(function() { this.resource('signup'); this.resource('login'); this.resource('profile'); this.resource('practice'); this.resource('overview'); }); app.applicationroute = ember.route.extend({ model: function () { homecoming this.store.find('user'); } }); app.loginroute = ember.route.extend({ controllername: 'application', model: function () {} }); app.practiceroute = ember.route.extend({ model: function () { homecoming this.store.find('flashcards'); } }); //applicationcontroller app.applicationcontroller = ember.objectcontroller.extend({ needs: ['practice'], flashcardarray: ember.computed.alias('controllers.practice.flashcardarray'), currentuser: ember.computed.alias('model'), isloggedin: false } }); //practicecontroller app.practicecontroller = ember.objectcontroller.extend({ needs: ['application'], flashcardarray: ember.computed.alias('model'), currentuser: ember.computed.alias('controllers.application.currentuser') } }); // practice template feeded outlet of application template <script type="text/x-handlebars" id="practice"> <div class="content-padded"> {{#each object in flashcardarray}} <div class="card_wrapper"> <p><h1>{{{object.num_reference}}}</h1><p> <p>pinyin: {{{object.mandarin}}}</p> <p>def: {{object.definition}}</p> {{/each}} </div> </script>

i think if have info need throughout application, regardless of user's active route, need homecoming applicationroute:

app.applicationroute = ember.route.extend({ model: function () { homecoming { user: this.store.find('user'), flashcards: this.store.find('flashcards') }; } });

javascript ember.js

python - Django: Getting single element from related manager -



python - Django: Getting single element from related manager -

i have app user can "vote" on "post". in ui (template) i'd indicate whether user has voted. require doing (which doesn't work). there legal way in template (without re-writing views)?

i'm trying users have voted on post. doesn't work or create sense really, can communicate i'm trying achieve:

{% if user in post.post_votes.all.the_user %}

relevant parts of model:

class post(models.model): content = models.textfield(blank=false) class vote(models.model): the_user = models.foreignkey(user, related_name="post_votes") the_post = models.foreignkey("post", related_name="post_votes")

thanks!

you need pass user queryset filter. there no way built-in template syntax. should create own.

# app.templatetags.app_tags django import template register = template.library() @register.filter def has_voted(user, post): homecoming post.votes.filter(the_user=user).exists() # template {% load app_tags %} {% if user|has_voted:post %} <b>already voted</b> {% endif %}

alternativly, can loop on queryset of votes that's not idea.

python django django-models django-templates django-views

javascript - How can I select an element from inside a Marionette event handler? -



javascript - How can I select an element from inside a Marionette event handler? -

edit: added more code

i'm listening event on model this: (this view)

var view = marionette.itemview.extend({ tagname: 'tr', template: viewtemplate, modelevents: { "change:highscore": "highchange" }, highchange: function (model) { var elem = this.$('.send'); console.log(elem); elem.hide(); this.render(); } });

and template:

<td class="cusername">{{username}}</td> <td class="highscore"> <div class="box"> <button class="send"></button> <span>send</span> </button> </div>

(this within marionette.itemview.extend({...}); ) when model changes highscore want send element hidden when above nil changes. console.log(elem) gives me element object[div.send] right element, doesn't hidden.

does have lifecycle of marionette? how can alter element hidden result of event on model?

do have more 1 element 'send' class within view context? if so, may need disambiguate relative target element. if understand relationship between target of event , element want manipulate, can access way:

highchange: function (e) { var elem = $(e.target).find('.send'); // if .send kid element var elem = $(e.target).closest('.send'); // if .send parent element }

javascript html dom backbone.js marionette

java - Unable to add maven dependency -



java - Unable to add maven dependency -

when right click on project maven add together dependencies. showing error. artifact id cannot empty. had rebuild index. don't know set in artifact id , grouping id. want add together hibernate libraries.

put in pom.xml in section dependencies:

<dependency> <groupid>org.hibernate</groupid> <artifactid>hibernate-core</artifactid> <version>4.3.6.final</version> </dependency>

from maven documentation:

the minimum requirement pom following:

project root modelversion - should set 4.0.0 groupid - id of project's group. artifactid - id of artifact (project) version - version of artifact under specified group

java hibernate maven java-ee pom.xml

postgresql - Buffering multiple linestrings -



postgresql - Buffering multiple linestrings -

i'm pretty new postgresql, there might pretty simple reply question, @ to the lowest degree hope so.

i have imported table thousands of single linestrings represent main roads of country. i'd buffer every single 1 of them , intersect results polygon (basically circle, thing is, position of circle dynamic, depending on preferences of user).

however, don't know how buffer linestrings @ once. works fine when buffer , intersect 1 linestring, it's kinda crucial buffer of them. , importing roads multilinestring spit doesn't work @ all.

so ... how create happen? hints? i'd appreciate help.

the best approach add together column represents buffers of roads , add together spatial index, ie,

alter table roads add together column road_buffer geometry(polygon, srid); update table roads set road_buffer = st_buffer(roads, distance); create index ix_spatial_road_buffer on roads using gist(road_buffer);

where polygon , srid indicate type , spatial reference id of column. can omit this, although practice utilize specific type , srid. utilize addgeometrycolumn same end.

you can run query against buffered roads, fast, indexed, homecoming actual roads, eg,

select road_id, road roads st_intersects(road_buffer, circle);

now, if wanted other way, without having pre-buffered linestring, somthing like,

select road_id, road, road_buffer (select st_buffer(road, dist) road_buffer, road, road_id roads st_intersects(st_expand(st_envelope(road), dist), circle) ) road_buff st_intersects(road_buffer, circle);

the trick here compute buffer in subquery, linestrings/roads envelope (ie, minimum bounding rectangle) intersects circle -- much faster calculation buffering linestrings. note, also, utilize of st_expand, same amount buffer distance, expands mbr , ensures don't miss potential candidates. did quick test on half 1000000 random lines, , approach much faster (10x) checking circle intersections against buffer of points.

postgresql gis postgis

ios - What are the Best Practices for Cache And Syncing in iPhone -



ios - What are the Best Practices for Cache And Syncing in iPhone -

i looking way cache info on client side, , sync info server info on basis of time stamp, worried way go whether utilize coredata or sqlite.

i know coredata not rdbms , takes in memory finish object space, on other side sqlite much powerful,

what best selection coredata or sqlite.

further in future version (that expected) if server info base of operations undergo changes column added table or deleted reason or updated, how can plan accomplish scalability.

any thoughts much appreciated..

thanks

i've preffered sqlite guess they're both equivalent each other. sqlite much more simple (from experience, junior-level) when need utilize it, stuff fmdb (git it!).

i've been told sqlite > coredata (if wanna create simple). , happen sense same way after having used both. though on other hand, if you're not using fmdb, sqlite painful code with.

scalability? you'd need update app , tables, that's same both choices. again, kinda sense completly sentiment based when sqlite feels easier , more comfortable play with. wether using sql or updating db.

now wanna emphasize before downvoted : it's how sense , not simple fact agrees on. wait more answers. i've used coredata in 2 or 3 different projects, i've used sqlite in way more, maybe i'm used one.

ios objective-c iphone sqlite core-data

java - Order objects based on ordering of member variables without comparator -



java - Order objects based on ordering of member variables without comparator -

say have object

person private int age; private string name;

and want sort them automatically using arrays.sort() such low ages come before high ages.

a mutual way comparator, many useful utility functions out there, there cleaner way this?

make class implement comparable.

java sorting

Rails - how to start up a local server (thin) with a specific git branch -



Rails - how to start up a local server (thin) with a specific git branch -

i have rails 3.2.16 app multiple git branches (for testing features). utilize thin spin server in development. if have branch called "dev" instance , i'm checked out branch in git. default thinwill pickup whatever in app directory , serve up. if wanted serve in master branch. there way serve master branch in lean (or in rails s can work app in branch in browser?

so have multiple branches, want test app in browser using branch. how can that?

locally switch branch want

git checkout master

and

rails server

bring app branch

you can

git checkout dev

or

git checkout master

at point in order run

rails server

for branch

you don't need restart server simple applications.

"by default lean pickup whatever in app directory..." - yes branch checked out.

so ever branch on same 1 used in rails server looking @ , editing files locally. if switch branch, both code , server looking @ files exist in branch.

ruby-on-rails ruby-on-rails-3 git github branch

json - SAPUI5 VizContainer - remove preset chart options (sap.viz.ui5.VizContainer) -



json - SAPUI5 VizContainer - remove preset chart options (sap.viz.ui5.VizContainer) -

i using vizcontainer visualize info in sapui5 (vizcontainer-link demo page)

i got 2 questions:

how cut down preset charting options (e.g. not want offer kind of heatmaps , additionally not want offer kind of scatter plots) - did not find alternative configure this... (answered) how configure x-axis correctly? (see illustration below)

x-axis configuration link illustration on sapui5 demo kit page, inserts sec dimension dataset, think in dynamic scenario quite difficult. info has 1 dimension month (in month have different y-axis-values), works fine.

var info = [[ {"name":"country","type":"dimension"}, {"name":"quater","type":"dimension"}, {"name":"profit","type":"measure"}, {"name":"revenue","type":"measure"}], ["country1","q1" 141.25, 35], ["country1","q2", 41, 25], ["country2", "q1", 133.82, 45], ["country2", "q2", 33.82, 89], ];

my data, works offering "complete timeframe" x-axis. ojson[i].title contains month name (e.g. "10/2014")

var info = [ [ {"name":"complete timeframe","type":"dimension"}, {"name":"month1","type":"measure"}, {"name":"month2","type":"measure"}, ], [ ojson[0].title, ojson[0].month1, ojson[0].month2], [ ojson[1].title, ojson[1].month1, ojson[1].month2], [ ojson[2].title, ojson[2].month1, ojson[2].month2], ];

what want accomplish beingness able have multiple x-axis dimensions based on months (e.g. in vizcontainer offer "complete timeframe" single values such "08/2014", "09/2014" ... possible? experience it?

answer on question 1: if there improve solutions, please allow me know!! did not know how accomplish in way

$("#content").find(".viz-controls-switchbar-switcher-container").children(':nth-child(4)').hide(); $("#content").find(".viz-controls-switchbar-switcher-container").children(':nth-child(5)').hide();

json configuration sapui5 graph-visualization

python - Find item in list by type -



python - Find item in list by type -

i have list can contain several elements of different types. need check if in list there 1 or more elements of specific type , index.

l = [1, 2, 3, myobj, 4, 5]

i can accomplish goal iterate on list , check type of each element:

for i, v in enumerate(l): if type(v) == mytype: homecoming

is there more pythonic way accomplish same result?

you can utilize next , generator expression:

return next(i i, v in enumerate(l) if isinstance(v, mytype)):

the advantage of solution is lazy current one: check many items necessary.

also, used isinstance(v, mytype) instead of type(v) == mytype because preferred method of typechecking in python. see pep 0008.

finally, should noted solution raise stopiteration exception if desired item not found. can grab try/except, or can specify default value return:

return next((i i, v in enumerate(l) if isinstance(v, mytype)), none):

in case, none returned if nil found.

python list search types

ios - Cordova iPhone 6 / 6+ Splashscreen images -



ios - Cordova iPhone 6 / 6+ Splashscreen images -

maybe it's simple question: can found splashscreenimages iphone 6 , iphone 6+?

everytime build project, can't find images iphones. still not available on cordova , have created myself, or overlook sth?

i have these images in folder, there feature upscaling them?

i hope can help me!

thanks in advance

cordova platform add together ios@master --usegit

fixed problem , installed thinks need incl. new splashscreens

ios iphone cordova

javascript - Clicking jQuery toggle link moves div content down until scrolling. How do I fix? -



javascript - Clicking jQuery toggle link moves div content down until scrolling. How do I fix? -

as title says, have link @ top of page switches 1 div using jquery toggle. whenever click link since adding floated divs display graphs on right side of page, moves content downwards until scroll mouse. how prepare this? here relevant code:

here css:

<style> div#percents { margin: 0; top: 0; } div#nvalues { margin: 0; top: 0; } div#one { top: 0; float:left; width:50%; overflow:hidden; } div#two { top: 0; float:left; width:50%; overflow:hidden; } </style>

here code:

echo '<div id="percents">'; echo '<div id="one">'; echo '<b><a onclick="togglenvalues();" alt="show n values" style="text-decoration: underline;color: blue;">click show numbers</a></b><br /><br />'; $tw3 = new tablewriter('retention_retreat_vw', 'value', false, false); $tw3->setcolumns('cohort_year', array('cohort_year', array('2006', '2007', '2008','2009', '2010', '2011', '2012'))); $tw3->setcategory('var_name'); $tw3->setpercents(array(1,2,3,4,5,6,7,'averages')); $tw3->writecolumntable('cohort_year', '(ret_1 / cohort * 100)', array('cohort_type', 'first-time freshman'), false, 'averages', 'side', 'one-year first-time freshmen retention rates', false, 'var_name = "overall" - desc', 'var_name-asc', false, 'value-asc'); echo '<p class="citation">notes: efc=expected family contribution. part categories mutually exclusive.</p>'; echo '<p class="citation">includes both full-time , part-time first-time freshman.</p>'; echo '<p class="citation">n/a values represent info not yet available or because cohort in question has no students.</p>'; echo '<p class="citation">only students persist in same major had @ entry counted beingness retained in declared majors category.</p>'; echo '<p class="citation">those did not pass remediation automatically dis-enrolled (co policy) , not retained.</p><br><br>'; echo '</div>'; echo '<div id="two">'; echo '<br><br><br><br><img src="./img/testimage.jpg" />'; echo '<br><br><br><br><img src="./img/testimage2.jpg" />'; echo '<br><br><br><br><img src="./img/testimage3.jpg" />'; echo '</div></div><br style="clear:both"/>'; echo '<div id="nvalues">'; echo '<div id="one">'; echo '<b><a onclick="togglenvalues();" alt="show n values" style="text-decoration: underline;color: blue;">click show percents</a></b><br /><br />'; $tw3 = new tablewriter('retention_retreat_vw', 'value', false, false); $tw3->setcolumns('cohort_year', array('cohort_year', array('2006', '2007', '2008','2009', '2010', '2011', '2012'))); $tw3->setcategory('var_name'); $tw3->writecolumntable('cohort_year', '(ret_1)', array('cohort_type', 'first-time freshman'), false, 'averages', 'side', 'one-year first-time freshmen retention rates', false, 'var_name = "overall" - desc', 'var_name-asc', false, 'value-asc'); echo '<p class="citation">notes: efc=expected family contribution. part categories mutually exclusive.</p>'; echo '<p class="citation">n/a values represent info not yet available or because cohort in question has no students.</p>'; echo '<p class="citation">only students persist in same major had @ entry counted beingness retained in declared majors category.</p>'; echo '<p class="citation">note: includes both full-time , part-time first-time freshman.</p>'; echo '<p class="citation">those did not pass remediation automatically dis-enrolled (co policy) , not retained.</p><br><br>'; echo '</div>'; echo '<div id="two">'; echo '<br><br><br><br><img src="./img/testimage.jpg" />'; echo '<br><br><br><br><img src="./img/testimage2.jpg" />'; echo '<br><br><br><br><img src="./img/testimage3.jpg" />'; echo '</div></div><br style="clear:both"/>';

javascript jquery html css toggle

java - error compiling java7 project with maven (heroku) -



java - error compiling java7 project with maven (heroku) -

i'm trying upload on heroku simple servlet maven. locally servlet working fine when use:

git force heroku master

i "build failure" error message:

[error] failed execute goal org.apache.maven.plugins:maven-compiler-plugin: 3.1:compile (default-compile) on project helloservlet: fatal error compiling: invalid target release: 1.7 -> [help 1]

i changed java 1.7 in scheme variables, maven running java 1.7, javac version 1.7?

am missing here?

edit: java_home , error screenshot

by default heroku apps run on openjdk 6.you have add together additional properties create app utilize open jdk 7 on heroku.

refer : https://devcenter.heroku.com/articles/add-java-version-to-an-existing-maven-app

java git maven heroku

javascript - jQuery UI Datepicker getDate returns today's date on invalid date -



javascript - jQuery UI Datepicker getDate returns today's date on invalid date -

when using jquery ui's date-picker, if phone call getdate while text in text box not valid date, getdate returns today's date.

example

how can distinguish between today's date , invalid date when retrieving date?

looks normal behaviour widget. here's function includes back upwards invalid date checking:

/* gets current value * @return date result or null if no date nowadays * @throws if entered value invalid */ function getdate(datepicker) { datepicker = $(datepicker); var format = datepicker.datepicker("option", "dateformat"), text = datepicker.val(), settings = datepicker.datepicker("option", "settings"); homecoming $.datepicker.parsedate(format, text, settings); }

javascript jquery jquery-ui jquery-ui-datepicker

Laravel 4.2: not able to log out user -



Laravel 4.2: not able to log out user -

i trying logout user:

public function getsignout() { auth::logout(); homecoming redirect::to('/'); }

however, when hits route:

route::get('/', function() { if(auth::check()){ homecoming 'logged in'; }else { homecoming 'not logged in'; } });

it returns user still logged in. problem , in advance helping prepare problem.

laravel

mysql sort group by total and name not working -



mysql sort group by total and name not working -

i have php programme outputs names corresponding events attended , number of times each event attended on period of time. illustration of output

name | run | swim | bike | total john 3 2 5 10

mysql query this:

$sql = 'select e.name leader, sum(case when c.catid = 26 1 else null end) "swim", sum(case when c.catid = 25 1 else null end) "bike", sum(case when c.catid = 24 1 else null end) "run", count("swim"+"bike"+"run") total events e left bring together event_categories c on c.uid = e.uid (date(e.event_start) between "'.$from_date.'" , "'.$to_date.'") grouping leader rollup;';

this works well, however, if want sort info "total" in descending order no output if replace lastly grouping line following:

grouping total desc, leader rollup;';

so listing names have highest totals lowest, , people same totals listed in alphabetical order. doing wrong?

as mentioned in comments, order by , rollup can not used together. states here (http://dev.mysql.com/doc/refman/5.0/en/group-by-modifiers.html) half way downwards page. around this, you'll have order in query original query acts subquery:

select * ( select e.name leader, sum(case when c.catid = 26 1 else null end) "swim", sum(case when c.catid = 25 1 else null end) "bike", sum(case when c.catid = 24 1 else null end) "run", count("swim"+"bike"+"run") total events e left bring together event_categories c on c.uid = e.uid (date(e.event_start) between "'.$from_date.'" , "'.$to_date.'") grouping leader rollup ) rolldup order total desc

original (wrong) answer:

you not set sorts in group by clause. set them in order by clause:

$sql = 'select e.name leader, sum(case when c.catid = 26 1 else null end) "swim", sum(case when c.catid = 25 1 else null end) "bike", sum(case when c.catid = 24 1 else null end) "run", count("swim"+"bike"+"run") total events e left bring together event_categories c on c.uid = e.uid (date(e.event_start) between "'.$from_date.'" , "'.$to_date.'") grouping leader rollup order total desc;';

mysql

php - Can JS files be included in PHPUnit tests? -



php - Can JS files be included in PHPUnit tests? -

i working on creating multilingual test cases. accomplish have utilize js files used application. there way load files phpunit scripts?

not exclusively sure trying achieve, assuming want take existing js file , execute it's contents in selenium. can utilize file_get_contents() function.

$script = file_get_contents('/path/to/your/script.js'); $this->execute(['script' => $script, 'args' => []]);

php selenium phpunit

sapui5 - UI5: Add Tree to IconTabFilter Content -



sapui5 - UI5: Add Tree to IconTabFilter Content -

i have icon tab filter upon user selecting it, show tree.

the logic of how handle user selection of icon provided here

handle icontab selection

the problem have js create tree node not working. logic below: -

var omodel = new sap.ui.model.json.jsonmodel({ "idocs1" : [ { "docnum" : "00063463", "mestyp" : "matmas", "status" : "53", "sndprn" : "extsys1", "direct" : "inbound", "message" : "material 00002342 created", "messages" : [ { "message" : "material 00002342 created" } ], "segments" : [ { "segment" : "e1maram", "fields" : [ { "fieldname" : "matnr" } ] } ] } ] }); sap.ui.getcore().setmodel(omodel); var tgtpath = "/idocs1/0/segments"; var otree = new sap.ui.commons.tree("tree"); otree.bindaggregation("nodes", tgtpath, function( sid, ocontext) { var treepath = ocontext.getpath(); var bindtextname = ''; if (treepath.indexof("fields") !== -1) { bindtextname = "fieldname"; } else { bindtextname = "segment"; } alert("here = " + ocontext + " ---- " + bindtextname); homecoming new sap.ui.commons.treenode() .bindproperty("text", bindtextname); }); var mybutton = new sap.ui.commons.button("btn"); mybutton.settext("hello world!"); mybutton .placeat("idviewroot--idviewdetail--toolbar-content"); otree .placeat("idviewroot--idviewdetail--toolbar-content");

this logic in method, invoked when user selects specific icontab.

i have button in place ensure add together icontab content (when tree logic commented out).

i have noticed if seek , create 2 buttons of same id, above code (i.e method) invoked twice.

if enable tree logic, method beingness called twice, getting errors duplicate tree node.

any help much appreciated.

thanks

martin

is there reason why add together content later? can add together specific content each icontab shown when user clicks on it. should solve problem.

if not convenient case, think should set content either on icontabbar or icontabfilter after clicking on icontab , not putting in content.

sapui5

vb.net - zLib decompress from string not file to DeflateStream -



vb.net - zLib decompress from string not file to DeflateStream -

i've been trying 2 weeks uncompress user-defined txxx string mp3 id2,3 file.

000000b0789c6330377433d63534d575f3f737b570343767b02929ca2c4b2d4bcd2b29b6b301d376367989b9a976c519f9e50ace1989452536fa60019b924c20696800017a10ca461f2c6aa30fd58a61427e5e72aa42228a114666e6f88cd047721100d5923799

thanks dr. adler correct answer when converted values string.

i have tried both ms deflatestream , gzipstream no success.

every illustration see uses stream file. not using file, have above zlib code in both array or string variable.

gzipstream gives me 'no magic number' , deflatestream gives me 'block length not match complement'.

i read post: http://george.chiramattel.com/blog/2007/09/deflatestream-block-length-does-not-match.html

tried removing bytes head, no luck. (i read trazillions of articles sending string deflatestream 1 time again 'no luck'!

i have above string, how send deflatestream? i'd post 2 hundred different code examples tried silly.

the funny thing is, built webaudio cue marker editor in less 2 weeks , lastly thing have (my programme must marker positions programme has worst sound editor known man (they embedded them in mp3 (bad) reason). hence, wrote own alter sound cue marker save hours of frustration @ work. however, i'm not getting much sleep lately.

help me sleep, please.

you can utilize memorystream instead of filestream both streams:

imports system.io imports system.io.compression imports system.text module module1 function hexstringtobytes(s string) byte() if (s.length , 1) = 1 throw new argumentexception("string odd number of characters in length - must even.") end if dim bb new list(of byte) = 0 s.length - 1 step 2 bb.add(convert.tobyte(s.substring(i, 2), 16)) next homecoming bb.toarray() end function sub main() dim s = "000000b0789c6330377433d63534d575f3f737b570343767b02929ca2c4b2d4bcd2b29b6b301d376367989b9a976c519f9e50ace1989452536fa60019b924c20696800017a10ca461f2c6aa30fd58a61427e5e72aa42228a114666e6f88cd047721100d5923799" dim result string = "" ' trim off leading 0 bytes , skip 3 bytes 0xb0 0x78 0x9c dim buffer = hexstringtobytes(s).skipwhile(function(b) b = 0).skip(3).toarray() using ms new memorystream(buffer) using decompressedmemorystream new memorystream using decompressionstream new deflatestream(ms, compressionmode.decompress) decompressionstream.copyto(decompressedmemorystream) result = encoding.default.getstring((decompressedmemorystream.toarray())) end using end using end using console.writeline(result) console.readline() end sub end module

outputs:

71f3-15-foo58a77 <trivevents><event><name>show chart</name><time>10000000.000000</time></event><event><name>show 1 time a</name><time>26700000.000000</time></event></trivevents>

(there leading 0 byte.)

p.s. looks bit unusual there 71f3-15-foo58a77 letter os instead of zeros.

p.p.s. if compressed info base64 string instead of hex string, pack more info same space.

vb.net zlib deflatestream