Posts

Showing posts from May, 2014

AngularJS passing lastTime to a service to display only recent posts -

i not sure if going right way want achieve twitter feed effect. i have statuses page, on first page load statuses , after display updates on page. i have service calls api: emp.services.socialservice = ['$http', '$q', function ($http, $q) { var deferred = $q.defer(); $http.get('/api/feed').then(function (data) { deferred.resolve(data); }); this.getstatuses = function () { return deferred.promise; }; return { getstatuses: this.getstatuses }; }]; and controller: emp.controllers.statusescontroller = ['socialservice', '$scope', '$interval', function(socialservice, $scope, $interval) { $scope.statuses = []; $scope.lasttime = 0; $scope.refreshstatuses = function() { var statuses = socialservice.getstatuses(); statuses.then(function(data) { $scope.statuses = data.data; for(id in $scope.statuses) { ite

sql - instr() function SQLITE for Android? -

i wanna following on existing sqlite database on android kind built colomns: id --- rule --- path --- someotherdata a rule e.g. contains part of filename (either trivial stuff "mypicture" or filetype "jpg"). want is, want write query, gets rules, contain part of inputstring. have tried following example: string value = "somepicturefilename.jpg" my statement: "select distinct * " + table_rules + " instr('"+ value + "',rule)!=0 order " + key_id+ " desc;" the statement in java "value" should inserted in statement. however, not work. not familiar sql nor sqlite, have tip= ;) thanks. edit: i've tried charindex, didn't work either. edit: more detailed example. following database given. id --- rule --- 1 "jpg" 2 "ponies" 3 "gif" 4 "pdf" now user enters filename. let's "poniesasunicorns.jpg". "ponies

android - Copy Files and directories with su command on rooted device -

similar questions asked here, can´t figure out, have do. not duplicate, because solutions on many threads here not looking or doesn´t work me. want copy files , directories folder inside /data/ folder. so, made lot of search on , googled hours. threads found not clear enough , don´t let me want. found blogs, doesn´help me. http://su.chainfire.eu/ http://forum.xda-developers.com/showthread.php?t=1694251 what have tried i able copy directory sd /data/ directory without need su command , works java code. first question: root permission not neccessary copying /data/ folder sd card? next step have done is, execute su command this: process pp = runtime.getruntime().exec("su cat "+origindir+" > "+targetdir); where orgindir path on sd card file , targetdir folder inside /data/ directory strings , example: /data/test/testfile.txt the problem here is, can copy file, has 0 bytes. doing wrong? what want i want copy file sd card /data/ directory

Ruby implementation of Secret Santa -

the problem stated follows: there list of persons, each having first name , last name. people having same last name belong same family. aim chose secret santa each person such secret santa ofcourse not same person, nor belong same family. i've taken liberty of assigning santa same family if there no other choice. i have following code achieve , passing tests - i'm not confident if code produces correct results in cases. in case algorithm not correct i'll appreciate if can explain why algorithm fails, review of code quite helpful. the main method in code assign_angels, , have tried return self of methods following east oriented code this problem taken ruby quiz: secret santa i'm using equalizer module equality checking equalizer require 'set' require 'equalizer' class people include equalizer.new(:people) def initialize personlist = [] @people = array(personlist).to_set end def add person @people.add person self

Android getIntent() can't find my String -

i have usual intent 1 activity other , give second activity path file needed. activity one: private void onfileclick(int position) { file file =new file(folder+ "/"+ getlistadapter().getitem(position).tostring()); intent = new intent(this, (activity two).class); log.e("given file",file.tostring()); i.putextra(file.tostring(), key); startactivity(i); } activity two: @override protected void oncreate(bundle savedinstancestate) { intent = getintent(); string filepath = i.getstringextra((activity one).key); //returns null file parsefile = new file(filepath); //nullpointerexeption } have initialized intent wrong?

Swift - Populate core data from premade sqlite file -

not same question here . i have premade sqlite file has 3 columns: chapter, versenumber , versetext. core data entity has same name attributes. how populate core data database sqlite file? core data can not read arbitrary sqlite files. have convert file core data database manually. format core data uses read / write sqlite proprietary. you have use sqlite directly read data. i'd suggest using fmdb reading data. put data core data store, should follow guidelines of efficiently importing data .

c - Comparing char* with char -

i working on program name of file input in command line. need check if input given character "-" , work file according result, not quite sure how it. method have tried, seemed logically make sense, of checking if argv[1] == "-"; always returns zero, when write "-" in command input. can do? you need write strcmp(argv[1],"a")==0; in example, compared 2 pointers , not 2 strings. when compiling, compiler declares "a" somewhere in memory , subsitute in compile time memory address. since argv[1] can't sit on same byte (temporary) "a" , result false. need iterate on 2 strings , iterativly compare each character. strcmp compares 2 strings , return 0 if equale in exact manner. for more info on strcmp : http://www.cplusplus.com/reference/cstring/strcmp/ in order handle multiple characters, can place few if-else's : if (strcmp(argv[1],"-")==0){ minus_character_handling_function(); } else

java - Below code runs successfully, so does it mean we can start thread twice? -

below code runs successfully, mean can start thread twice? public class enu extends thread { static int count = 0; public void run(){ system.out.println("running count "+count++); } public static void main(string[] args) { enu obj = new enu(); obj.run(); obj.start(); } } output - running count 0 running count 1 no, started new thread once, when called obj.start() . obj.run() executes run method in current thread. doesn't create new thread, , can call many times like. on other hand, calling obj.start() more once not possible.

Android Edittext in a Adapter not receiving focus -

i have edittext other view inside linearlayout. using layout listview item. have instead of listview using vertical linearlayout add these items because listview not able handle focus properly. wheni click on 1 of edittext , click on other receives focus cursor disappears. trying implement cart sort of thing. add follwing line listview android:descendantfocusability="beforedescendants" and add following line activty manifest android:windowsoftinputmode="adjustpan"

ruby - Rails associations has_many through instead of HABTM -

i'm new rails , activerecord , i'm trying find correct way model data. i building application let's swim instructors put class plan shows skills teaching class , activities use teach each skill. plan can contain many skills , each skill can have many activities associated it. on plan form there widget skill-activity combination. in it, user should able select skill dropdown , selected skill select multiple activities list. widget can repeat number of times on form. my current model: class plan has_many :plan_activities end class planactivities belongs_to :plan belongs_to :skill has_and_belongs_to_many :activities end class skill end class activity end is model correct? problem accepts_nested_attribtues_for not work habtm associations. i've read can replace has_many through:, mean adding yet join model picture. seems little ugly. there better way this? edit: my skills , activities in list form , should able include same skill and/or activity

node.js - "Cannot read property of undefined" NodeJS -

this nodejs/express/mongoose application. https://gist.github.com/nosille/e114ed3cb52ed88650c1 this template register.jade file that's supposed receive firstname property user object main application. suspect there might wrong header order, properties of user object aren't sent before template rendered.

php - Getting rid of foreach loop to return a single record -

this should simple, me beginner, still struggling various view display calls. borrowed foreach loop part of software, , working correctly. returns values each record on page. however, want current record. so, need rid of foreach loop can't figure out how convert foreach loop current record. thanks help. <?php echo $this->header_part; ?> <div id="defaultcontainerwrapper" class="maxwidth"> <?php foreach($this->challengenames $k=>$challengename) { ?> <header> <h1> <div class="list"> <span>welcome </span><?php echo $challengename['partnername']; ?><span>'s beat waste challenge!</span> </div> </h1> </header> <?php } ?> </div> <?php echo $this->footer_part; ?> this function controller: public function yourchallengeac

What's the simplest way to print a Java array? -

in java, arrays don't override tostring() , if try print 1 directly, weird output including memory location: int[] intarray = new int[] {1, 2, 3, 4, 5}; system.out.println(intarray); // prints '[i@3343c8b3' but we'd want more [1, 2, 3, 4, 5] . what's simplest way of doing that? here example inputs , outputs: // array of primitives: int[] intarray = new int[] {1, 2, 3, 4, 5}; //output: [1, 2, 3, 4, 5] // array of object references: string[] strarray = new string[] {"john", "mary", "bob"}; //output: [john, mary, bob] since java 5 can use arrays.tostring(arr) or arrays.deeptostring(arr) arrays within arrays. note object[] version calls .tostring() on each object in array. output decorated in exact way you're asking. examples: simple array: string[] array = new string[] {"john", "mary", "bob"}; system.out.println(arrays.tostring(array)); output: [john, mary, bob] nest

jquery - How i can make this code work without of click on the button? -

http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_animation2 how can make code work without of click on button example when want go 1 page other page writing in box start getting bigger ?? use same code , without click handler $(document).ready(function(){ // block executed after dom loaded var div = $("div"); div.animate({left: '100px'}, "slow"); div.animate({fontsize: '3em'}, "slow"); }); or.... $(document).ready(function(){ settimeout( function startanimation(){ // block executed 1/2 second after dom loaded var div = $("div"); div.animate({left: '100px'}, "slow"); div.animate({fontsize: '3em'}, "slow"); } , 500) // time in milliseconds , half second }); use timeout wait couple seconds before execution

java - Encog SVM wont train -

Image
i trying train svm classify 2 spiral data. my input 3 column csv file, first 2 columns (x, y)-coordinates of point on spiral (not normalised) , third column spiral (class) point belongs to. i first normalise csv file first 2 columns between 0 , 1 (third column remains unchanged). then create , train svm follows csvneuraldataset trainingset = new csvneuraldataser(normalisecsv("/path/to/data/file"), 2, 1, false); svm svm = new svm(2, false); final svmsearchtrain train = new svmsearchtrain(svm, trainingset); int epoch = 0; { train.iteration(); system.out.println("epoch $: " + epoch + " error: " + train.geterror()); epoch++; } while(train.geterror() > 0.01); train.finishtraining(); however, do...while loop ends being infinite loop training error around 0.4 , never changes. the data set contains around 200 samples , there 2 classes (0 , 1). can tell me why failing? edit: here pastebin link 10% of training data. best rega

Python/C#, Reading File into Byte Array - Not Quite the Same Result -

i'm attempting read file , process in both c# , ironpython, i'm running slight problem. when read file in either language, byte array that's almost identical, not quite. for instance, array has 1552 bytes. they're same except 1 thing. time value "10" appears in python implementation, value "13" appears in c# implementation. aside that, other bytes same. here's i'm doing bytes: python: f = open('c:\myfile.blah') contents = f.read() bytes = bytearray(contents, 'cp1252') c#: var bytes = file.readallbytes(@"c:\myfile.blah"); perhaps i'm choosing wrong encoding? though wouldn't think so, since python implementation behaves expect , processes file successfully. any idea what's going on here? (i don't know python) looks need pass 'rb' flag: open('c:\myfile.blah', 'rb') reference : on windows, 'b' appended mode opens file in binary mode

objective c - iOS - Swapping View Controller's in a Container View and persisting the data -

i have container view swaps child view controllers. upon swapping view controllers though lose data controller had when deallocated memory. how can swap child view controllers , keep data same way tab bar controller swaps them without losing deallocating data memory? you should have outer (root) viewcontroller persists, , owns containerview , cycling child viewcontrollers. ideally rootviewcontroller (or other object outlives individual child viewcontrollers eg appdelegate) own strong reference model, , childviewcontrollers given weak pointer model life cycle. easier if these childviewcontrollers inherit abstract superclass has weak property point model object, rootviewcontroller can treat children instance of superclass. edit/additional info.... make new subclass of nsobject properties of data want persist. call somethingmodel remove variables/properties data childrenviewcontrollers , give them @property (weak, nonatomic) somethingmodel *modelobject (put in subcl

fish terminal highlights 1 folder and most of it's subfolders -

Image
the title pretty says all. 1 of used used folders in fish terminal became highlighted in yellow. of it's sub folders highlighted in yellow too. not sure happened. it's on mac yosemite fish shell highlighted directories yellow because directory's permissions set everyone can read, write, , execute . essentially fish shell warning directory has least restrictive permissions in case weren't aware. for example, in screenshot: if change permissions directory "oranges" can read+write+execute ( chmod 777 oranges/ ), can see fish shell adds yellow highlight. when change permissions more restrictive ( chmod 775 /oranges ), directory "orange" no longer highlighted. here's good explanation of file permissions , command chmod more detail.

ruby - Validating minutes and seconds in Rails -

i'm trying validate time based attribute called duration 1 of models. attribute, accept along lines of 01:30 valid value. goal have 4 digit time-code (minutes , seconds) colon in between two. both minutes , seconds limit in range 59 , cannot have 00:00 value. regex have doesn't seem work: validates :duration, presence: true, format: {with: /a([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]z/} use negative lookahead (?!00:00) , rest of regex simple minutes/seconds validation. /\a(?!00:00)[0-5][0-9]:[0-5][0-9]\z/ if subject =~ /\a(?!00:00)[0-5][0-9]:[0-5][0-9]\z/ # successful match else # match attempt failed end regex demo

linux - No sound from SuperCollider with Jack2 -

Image
note: similar not same supercollider not audible on headphone , because issue not restricted headphones, , fix question (remapping system:playback_{3,4}) not apply situation i trying use supercollider (on linux), unable hear sound it. jackdbus running, , supercollider able connect no error. here output when (re-)boot supercollider server booting 57110 jackdriver: client name 'supercollider' sc_audiodriver: sample rate = 48000.000000, driver's block size = 1024 jackdriver: connected system:capture_1 supercollider:in_1 jackdriver: connected system:capture_2 supercollider:in_2 jackdriver: connected supercollider:out_1 system:playback_1 jackdriver: connected supercollider:out_2 system:playback_2 supercollider 3 server ready. jackdriver: max output latency 42.7 ms receiving notification messages server localhost shared memory server interface initialized however, when play sound, continue see no errors, hear nothing. playing sound tutorial prints post window synt

angularjs - Error: [$resource:badcfg] Error in resource configuration for action `query`. Expected response to contain an array but got an object -

i new mean stack development , started yesterday. trying data database call using resource linked server side controller. receiving following console error "error: [$resource:badcfg] error in resource configuration action query . expected response contain array got object" angular controller: app. controller('articlectrl', function($scope, $location, $resource){ var articles = $resource('/api/articles'); articles.query(function(result){ console.log(result); }); $scope.addnew = function(){ $location.path("/administrationarea/articles/newarticle"); } }); server.js: articlescontroller = require('./server/controller/article-controller'); app.get('/api/articles', articlescontroller.list); app.post('/api/articles', articlescontroller.create); server side controller: var article = require('../models/articlemodel'); module.expor

Arduino Java SerialEvent not being called -

i following simple example found here (example one) , have arduino connected raspberry pi , read data arduino on pi in java. the issue serialevent method never called, implies no data coming in. however, when open serial monitor can see data being read correctly. the correct serial port being used well. here java code. //this class: // - starts communication arduino. // - reads data coming in arduino , // converts data in useful form. // - closes communication arduino. //code builds upon great example: //http://www.csc.kth.se/utbildning/kth/kurser/dh2400/interak06/serialwork.java //the addition being conversion incoming characters numbers. //load libraries import java.io.*; import java.util.toomanylistenersexception; //load rxtx library import gnu.io.*; class arduinocomm implements serialporteventlistener { //used in process of converting read in characters- //-first in string , number. string rawstr=""; //declare serial port variable s

javascript - Deprecation warning: moment construction falls back to js Date -

i attempting convert datetime 150423160509 //this utc datetime to following format: 2015-04-24 00:05:09 //local timezone by using moment.js var moment = require('moment-timezone'); var = moment.tz('150423160509', "asia/taipei"); console.log( a.format("yyyy-mm-dd h:m:s") ); but gives me error deprecation warning: moment construction falls js date. discouraged , removed in upcoming major release you need tell moment how parse date format, this: var parseddate = moment.utc("150423160509", "yymmddhhmmss"); var = parseddate.tz("asia/taipei"); // i'm assuming meant hh:mm:ss here console.log( a.format("yyyy-mm-dd hh:mm:ss") );

Testing Android App using greendao with Mockito -

i new android testing , trying write unit tests (running on local jvm) using mockito in android studio. my ide setup (gradle scripts) done far. dependencies { compile filetree(include: ['*.jar'], dir: 'libs') // unit testing dependencies. testcompile 'junit:junit:4.12' testcompile 'org.mockito:mockito-core:1.10.19' } in app using greendao orm have no abstraction of layer yet (planned future). when try test parts of application code using database related classes (like sqliteopenhelper , sqlitedatabase setting database, sqlitestatement compiling statements, etc.) test exits exception, example sqliteopenhelper not mocked . is @ possible write unit tests in scenario mocking database (without investing time abstract database layer)? the problem right context initializing database layer. using robolectric can use runtimeenvironment.application context object in test environment, initializing database layer unit tests r

jquery - Getting Mobile Menu to stay open when clicking submenu - Slicknav -

i'm using slicknav: http://slicknav.com/ i have behavior right not quite. want menu close whenever clicks outside of it, got, except enforced that, menu closes when try open submenu. need whole menu stays open when clicking submenu, , closes when clicks outside of menu (anywhere else on page). ideas? <ul id="menu"> <li><a href="">link</a></li> <li><a href="">link</a></li> <li> <a href="">submenu</a> <ul> <li><a href="">submenu link</a></li> <li><a href="">submenu link</a></li> <li><a href="">submenu link</a></li> </ul> </li> <li><a href="">link</a></li> <li><a href="">link</a></li> </ul> <script src="slicknav.js"></script> <script type="

java - JavaFX MediaPlayer - Music stops after 10 seconds -

here's code, title says music stops after 10ish seconds, played file in vlc or other programs, lasts more 5 minutes. public void music(){ string bip = "src/data/fjordmusic.mp3"; media hit = new media(paths.get(bip).touri().tostring()); mediaplayer mediaplayer = new mediaplayer(hit); mediaplayer.play(); } your question asked , answered here: mediaplayer stop playing after 5 seconds it seems garbage collector ereases mediaplayer instance after finishing method. put declaration of mediaplayer above method , should work. mediaplayer mediaplayer public void music(){ string bip = "src/data/fjordmusic.mp3"; media hit = new media(paths.get(bip).touri().tostring()); mediaplayer = new mediaplayer(hit); mediaplayer.play(); } (i'm not able post comments, i'm forced write answer.)

Is there a way to generate the R.java file in Android Studio? -

i have saved android project long time ago , must work on it. i've created new project in android studio , i've imported java , xml files inside r.java file missing. i guess didn't save original. can recover somehow or generate it? r.java quite different in android studio in eclipse. since old project, i'm assuming eclipse. in eclipse, r.java included in source tree. however, in android studio, hidden away. another stack overflow answer : 1. build this has complete output of make process i.e. classes.dex, compiled classes , resources, etc. in android studio gui, few folders shown. important part your r.java found here under build/source/<flavor>/r/<build type(optional)>/<package>/r.java you shouldn't need manually interact r.java @ all. can re-generated source code. thus, won't have problems -- r.java auto-generated , well. if isn't, try rebuild of project.

model - curve fitting with lmfit python -

i new python , trying fit data using lmfit. following on lmfit tutorial here: http://lmfit.github.io/lmfit-py/parameters.html , code (based on code explained in above link): import numpy np import lmfit import matplotlib.pyplot plt numpy import exp, sqrt, pi lmfit import minimize,parameters,parameter,report_fit data=np.genfromtxt('test.txt',delimiter=',') x=data[:,][:,0] y=data[:,][:,1] def fcn2fit(params,x,y): """model decaying sine wave, subtract data""" s1=params['s1'].value t0=params['t0'].value t1=params['t1'].value s2=params['s2'].value t2=params['t2'].value model = 1-(1-s1)*exp(-(x-t0)/t1)+s2*(1-exp(-(x-t0)/t2) return model - y params = parameters() params.add('s1', value=0.85, min=0.8, max=0.9) params.add('t0', value=0.05, min=0.01, max=0.1) params.add('t1', value=0.2, min=0.1, max=0.3) params.add('s2', value=0

java - Disable XML Entity resolving in JDOM / DOM -

i writing java application postprocessing of xml files. these xml files come rdf-export of semantic mediawiki, have rdf/xml syntax. my problem following: when read xml file, entities in file resolved value specified in doctype. example in doctype have <!doctype rdf:rdf[ <!entity wiki 'http://example.org/smartgrid/index.php/special:uriresolver/'> .. ]> and in root element <rdf:rdf xmlns:wiki="&wiki;" .. > this means <swivt:subject rdf:about="&wiki;main_page"> becomes <swivt:subject rdf:about="http://example.org/smartgrid/index.php/special:uriresolver/main_page"> i have tried using jdom , standard java dom. code think relevant here standard dom: documentbuilderfactory factory = documentbuilderfactory.newinstance(); factory.setexpandentityreferences(false); factory.setfeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); and jdom sax

javascript - Face not visible after changing wireframe to false -

Image
i trying draw house, created faces. had meshbasicmaterial 's wireframe set true while making it, when wanted add textures it, got errors. troubleshooting that, changed wireframe false , see wrong. 3 of faces not getting drawn. wireframe set false : and when true : i have tried drawing missing faces wireframe set true, , see them getting drawn. when change parameter false, doesn't draw face. my code below: <!doctype html> <head> <title>textures</title> <meta charset="utf-8" /> </head> <body style="font-family:georgia;"> <script src="http://www.erobo.net/scripts/javascript/33/scripts/three.min.js"></script> <div style="width: 580px; height:580px; margin: 0 auto; font-family:georgia;"> <h2><i>textures</i></h2> <b>my name</b> [ <text style="font-family:lucida console; font-size:14px&

How to keep android process alive -

how apps swiftkey, locker master manages keep process alive after has been removed stack? they don't use sticky notification. update:- need keep process alive. in case service active process gets killed. they have 1 or more unbound background service . to kill services can go settings -> apps -> running. however services may restarted @ time other apps or system sending system wide message (intent). in cases restarted by time events boot complete other apps other intents in swiftkey case, started android os when needs show keyboard. edit: can specify service runs in remote process adding service definition in androidmanifest android:process="process_name_here" however there no such thing service cannot killed , can run forever. android os may start killing service if running low on resources or service running long period of time. overcome this, can make forground running service, needs show notification. can killed task managers

python - GNU Health - Timezone Errors -

after few days of search , trying use pytz , other tools, unable find solution. when user creates medication print-out list in gnu health error given: ====== error======================= traceback (most recent call last): file "/trytond/protocols/jsonrpc.py", line 150, in _marshaled_dispatch response['result'] = dispatch_method(method, params) file "/trytond/protocols/jsonrpc.py", line 179, in _dispatch res = dispatch(*args) file "/trytond/protocols/dispatcher.py", line 161, in dispatch result = rpc.result(meth(*c_args, **c_kwargs)) file "/trytond/report/report.py", line 144, in execute type, data = cls.parse(action_report, records, data, {}) file "/trytond/modules/health/report/health_report.py", line 62, in parse localcontext['print_date'] = get_print_date() file "/trytond/modules/health/report/health_report.py", line 42, in get_print_date return date

php - Making a join with Eloquent based on a list of ids -

i have set 2 eloquent models belongstomany relation in both directions. works fine need make more detailed query within relationship. keep things simple, let's tables have following columns: wigs: - id - name - type heads: - id - name heads_wigs: - head_id - wig_id now need fetch series of wigs given type within list of given head id 's. have is: a wig type an array head id 's i using eloquent outside of laravel want start building orm query on model. like: wig::where( 'type', $type )-> ... //here code make join on head id's this understanding of sql lacks suppose should not hard achieve. update: to rephrase in sentence: get wigs type=wig_type have belongstomany relationship heads [1,2,3,5,6,8,9] . want end collection of wigs performing single query. you this head::wherein('id', $head_id_array)->load(['wig' => function($query) use ($wig_type) { $query->where('type', $wig_type)

node.js - Creating a Nodejs local reverse shell over Ajax? -

i'm attempting make small node executable has ability open local shell , send , receive commands http server. seems simple enough logically best practice in implementing this? open command line using node api listen commands server url /xmlrpc-urlhere/ when command received via ajax or webrtc? execute in command line post command line response user this shell administrative purposes. i can't think of way of doing this, i've checked npm , seem there basic command line modules node js nothing has functionality. the npm modules commander , request ought trick. started, here's simple command line tool issues search google , dumps raw html console. eg: ./search.js puppies #!/usr/bin/env node var program = require('commander'); var request = require('request'); var search; program .version('0.0.1') .arguments('<query>') .action(function(query) { search = query; }); program.parse

json - Error in groovy script -

show msg me groovy.lang.missingmethodexception: no signature of method: java.io.file.write() applicable argument types: (java.lang.integer, java.lang.string) values: [62, utf-8] possible solutions: write(java.lang.string, java.lang.string), write(java.lang.string), wait(), size(), canwrite(), wait(long) and code is import groovy.json.jsonslurper requestteststepname = "criar/login usuario 1" responsecontent = testrunner.testcase.getteststepbyname(requestteststepname).getpropertyvalue("response") response = new jsonslurper().parsetext(responsecontent) userid = response.userid new file( "c:/tc/json/userid_h24_userid.txt" ).write(userid, "utf-8") the answer staring @ helpful error message.. you need wrap 62 userid string: new file( "c:/tc/json/userid_h24_userid.txt" ).write("$userid", "utf-8")

php - Laravel 5 return JSON or View depends if ajax or not -

i know if there magic method use scenario : if call page via ajax request controller returns json object, otherwise returns view, i'm trying on controllers without changin each method. for example know can : if (request::ajax()) return compact($object1, $object2); else return view('template', compact($object, $object2)); but have lot of controllers/methods, , prefer change basic behavior instead of spending time change of them. idea ? the easiest way make method shared between of controllers. example: this controller class other controllers extend: <?php namespace app\http\controllers; use illuminate\routing\controller basecontroller; abstract class controller extends basecontroller { protected function makeresponse($template, $objects = []) { if (\request::ajax()) { return json_encode($objects); } return view($template, $objects); } } and 1 of controllers extending it: <?php namespace a

.htaccess - Clean urls with apache htaccess -

how can convert url http://example.com/vpage/page.php?number=1&status=completed into clean http://example.com/1/completed so in php page can echo variables 1 , completed. thanks try in root/.htaccess rewriteengine on rewritebase / rewritecond %{request_filename} !-d rewritecond %{request_filename} !-f rewriterule ^([0-9]+)/([a-za-z0]+)/?$ /vpage/page.php?number=$1&status=$2 [qsa,nc,l]

html5 - How to resolve the following HTML error? -

i have following lines in django template file:-cart.html:- <td class="right"> <form method="post" action="." class="cart"> <label for="quantity">quantity:</label> <input type="text" name="quantity" value="{{ item.quantity }}" id="quantity" size="2" class="quantity" maxlength="5" /> <input type="hidden" name="item_id" value="{{ item.id }}" /> </td> <td> <input type="submit" name="submit" value="update" /> </form> </td> at first closing tag of td i.e first </td> ,i following error: element form not closed.please me rectify error. html tags must structured in directly hierarchic manner . closing tag opened inside closed elements incorrect , produce errors , issues. enclose form in

ruby on rails - Turbolinks 3 and render a partial -

i'm excited turbolinks3(it allows render partial , not reload body) can read more here: https://github.com/rails/turbolinks/blob/master/changelog.md it's amazing i've problem: in browsers doesn't support pushstate(example ie8/9), don't know how manage behavior. give me error on ie8: could not set innerhtml property. invalid target element operation. my controller code is: def create @post = post.find(params[:post_id]) if @post.comments.create(comment_params) render '_comment', change: [:comments, :super_test], layout: false, :locals => { comment: @post.comments.last } else render json:'error' end end a 'solution' do: redirect_to @post, change: [:comments, :super_test] but problem reply lot of data don't need!(and response time bigger) reallt want find solution. how can resolve problem ? i've thought 2 solution: 1) use history.js / modernizr polyfill pushstate on old browsers bu

java - Reading values from user in C# -

this code works fine, if user enters numbers in separate lines i.e. 10 12 result : 22 however, when try input there error. 10 12 now, know console.readline() reads entire line, , space isn't int , error. however, when used code in c, there scanf function, specifying datatype expect user, run both cases. also, think java's scanner.nextint() have not allowed such troubles. there simple way ask c# read data separated spaces, or lines in same manner? reason why never used c# in coding competitions. don't understand how solve problem. using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; namespace test { class program { static void main(string[] args) { int result=0,a, b; = int.parse(console.readline()); b = int.parse(console.readline()); result = + b; console.writeline("the result {0}", result); console.readkey(); } } }

cocoa - Unexpected NSTextField background color, should be transparent -

Image
update: i've added sample project testing, see @ bottom of post. original question: i've got nswindow , change background when other parameters change. the window background gradient i'm drawing overriding drawrect in subclass of window's view. class mainwindowview: nsview { override func drawrect(dirtyrect: nsrect) { var rect = dirtyrect let gradient = nsgradient(startingcolor: backgroundcolor, endingcolor: darkerbackgroundcolor) gradient.drawinrect(rect, relativecenterposition: nspoint(x: 0, y: 0)) super.drawrect(rect) } } and i've got 2 nstextfield s on window. the nstextfield s both set drawsbackground = false in awakefromnib , set borderless in ib. i'm not using nsattributedstring s here, changing stringvalue of nstextfields, , of course textcolor . everything working... except sometimes , text fields have unexpected dark semi-transparent background. (it's hard see on screens it

php - How do I add values to class objects then put them in an array? -

i'm trying embed queries variables in class. like so: class foobar{ public $bar; } $result = array(); $db = mysqli_connect("127.0.0.1", "foo", "foo", "farm"); $sql = "select * `lot`;"; $result = mysqli_query($db, $sql); while($row = mysqli_fetch_assoc($result)){ $foo = new foobar; $foo->$bar = $row["cow"]; array_push($result, $foo); } but when print array using print_r($result) , i'm getting output: array( ) i hoping see objects stored in array. where did go wrong? should doing? you're reusing $result variable. it's an array reuse mysqli resource. also $foo->$bar should $foo->bar . class foobar{ public $bar; } $result = array(); $db = mysqli_connect("127.0.0.1", "foo", "foo", "farm"); $sql = "select * `lot`;"; $query_result = mysqli_query

java - Find a string in a specific table -

i'm working oracle database, i'm wondering if there way find rows contains value in column. example let's consider table: weather city state high low phoenix arizona 105 90 tucson arizona 101 92 flagstaff arizona 88 69 san diego california 77 60 albuquerque new mexico 80 72 basically (i know it's not possible), this: select * weather * '%f%' and give me rows flagstaff arizona 88 69 san diego california 77 60 i on java side, querying rows resultset dynamically search given value in column , add row. problem table contains millions of rows , guess more efficient on database side, fetch wanted rows network. is possible on sql side directly? you can use view all_tab_columns search columns in given table: declare v_table_name varchar2(30) := 'dual'; v_search_string varchar2(100) := 'x'; v

c++ - CMake cross compile -

i'm having problem cmake cross compiler project. my cross compiler did not find used libraries. setup cross compiler tutorial cross compiler . now need libs installed on raspberrypi. have snychronised /lib , /usr direcotry pi computer in /opt/cross/rasp. toolchain file: # 1 important set(cmake_system_name linux) #this 1 not set(cmake_system_version 1) # specify cross compiler set(cmake_c_compiler /opt/cross/x-tools/arm-unknown-linux-gnueabi/bin/arm-unknown-linux-gnueabi-gcc) set(cmake_cxx_compiler /opt/cross/x-tools/arm-unknown-linux-gnueabi/bin/arm-unknown-linux-gnueabi-g++) # target environment set(cmake_find_root_path /opt/cross/rasp) # search programs in build host directories set(cmake_find_root_path_mode_program never) # libraries , headers in target directories set(cmake_find_root_path_mode_library only) set(cmake_find_root_path_mode_include only) but when try compile program following linking error: /opt/cross/x-tools/arm-unknown-linux-gnueabi/lib/gcc/arm-

c - GCC optimization of iterative functions -

i have following code fibonacci both recursive , iterative versions: #include <stdio.h> typedef long long int; long long recursive (long long i) { if (i == 0) return 0; if (i == 1) return 1; return recursive (i-1) + recursive (i-2); } long long iterative (long long i) { int counter = i-1; int fib1 = 0; int fib2 = 0; // first iteration fib1 = 0; fib2 = 1; while (counter > 0) { int temp1 = fib1; int temp2 = fib2; fib1 = fib2; fib2 = temp1 + temp2; counter--; } } int main (int argc, char **argv) { printf("result: %lli\n", iterative(10)); return 0; } i tried compiling gcc -o2 optimization see if recursion perform better iteration, noticed interesting occurrence: when compiled -o2 , iterative function outputs 0 while if it's compiled without flag, outputs proper number. gcc -o2 fibonacci.c -o fib && ./fib : result: 0 gcc fibonacci.c -o fib &a

c# - Is String culture info important for comparison if the user will never modify those strings -

when comparing hard-coded strings user see not modify/change, culture info important. i assume not, want safe. example: static void main() { string hardstring = "iamhardcodei"; string hardstring2 = "iamhardcodei"; //compare hardstring , hardstring2, ignoring case, //and stuff based on result } the general recommendation string comparisons when "programmatic strings" (i.e. specified not usable or editable user directly the: stringcomparison.ordinal[ignorecase] . see post (of duplicate): which best use -- stringcomparison.ordinalignorecase or stringcomparison.invariantcultureignorecase?

char - Reversing a word : C++ -

i want reverse char string in c++. wrote code: #include <iostream> #include <string.h> using namespace std; int main(){ char word[80] = "polymorphism"; char rev[80]; int i, j; int l; l = strlen(word); for(i = 0, j = l; < l-1; i++, j--){ word[j] = rev[i]; } cout << rev << endl; return 0; } in terminal shows characters this: 83???uh??? ... your character array rev not 0 terminated. and istead of write rev writing word.:) word[j] = rev[i]; the loop wrong due condition i < l-1; there must be i < l; the program can following way #include <iostream> #include <cstring> int main() { char word[80] = "polymorphism"; char rev[80]; size_t n = std::strlen( word ); size_t = 0; ( ; < n; i++ ) rev[i] = word[n - - 1]; rev[i] = '\0'; std::cout << word << std::endl; std::cout << rev << s

android - Having problems with inserting data into sqlite as new details are replacing all other rows with the newly entered details -

im having problems sqlite database, part of application have save users favourite deals inserting them sqlite database. happens new row created details of new favorited deal updates existing rows same details of newly added deal. i've looked on many sites cannot seem fix it. please me? below databasehelper class: public class databasehelper extends sqliteopenhelper{ // database version private static final int database_version = 1; // database name private static final string database_name = "unilife"; // login table name private static final string table_login = "login"; // login table columns names private static final string key_id = "id"; private static final string key_name = "name"; private static final string key_email = "email"; private static final string key_username = "username"; private static final string key_user_id = "userid"; public