Posts

Showing posts from February, 2011

arrays - Create "object" in freemarker only (no JAVA etc)? -

after reading freemarker documentation , googling don't see how can build test object (like associated, multilevel array) in freemarker only. so like: <#assign seq=["a","b","c"]> but in more depth - (pseudo): aa ab ac ad b ba bb bc c ca cb cc cd ce is possible in freemarker (as front-end dev waiting back-end guys finish need work on , not use bare arrays)? tnx that's not multi-level array, because each nested array has name ("a", "b", "c"). closest can think of is: <#assign foo = { "a": ["aa", "ab", "ac", "ad"], "b": ["ba", "bb", "bc"], "c": ["ca", "cb", "cc", "cd", "ce"] }> but there have utilized ftl hash literals keep key order. without that: <#assign foo = [ {"name" : "

android - the List<> being empty after filling it in for loop -

i want details db, , put them in list. - inside loop can see list gets details (list size increases , values in list true. - after loop ends, check list , find size want, fields values null!! list variable defined outside function (i.e it's class field). see: loop start cursors value put value in list check list value : value ok. loop end. check list value : value null. here code: list<bundle> friends = new arraylist<bundle>(); public list<bundle> getallfriends() { sqlitedatabase db = this.getwritabledatabase(); string check="select * friends"; cursor c = null; string name =""; string id =""; string onlinestt =""; string photourl =""; string friendsince =""; bundle det=new bundle(); if(db!=null) c=db.rawquery(check,null); if(c!=null) if(c.isbeforefirst()&&c.getcount()>0) // if there result/s { c.moveto

c++ - Optimise byte operations CUDA -

i relatively new cuda , trying write kernel calculates sum of absolute differences between query vector , large database of vectors. elements of both must 8 bit unsigned ints. i've based kernel off nvidias sample parallel reduction kernel, i've read thread . i getting 5gb/s not better fast cpu , not come close theoretical bandwidth of ddr5 gt640 of 80gb/s. my data set consists of 1024 bytes query vector, 100,000 x 1024 bytes database i have 100,000 blocks of 128 threads, if each block accesses same 1024 byte query_vector, going cause worse performance? since every block accessing same memory location. blocksize , shared memory both set 128 , 128*sizeof(int), 128 #define'd threads_per_block template<uint blocksize> __global__ void reduction_sum_abs( byte* query_vector, byte* db_vector, uint32_t* result ) { extern __shared__ uint sum[]; uint db_linear_index = (blockidx.y*griddim.x) + blockidx.x ; uint = threadidx.x; sum[threadidx.x] = 0

c++ - Can inline lambda initializer capture 'this' pointer? -

can inline member initialization lambda capture , use this pointer? struct a{ int = 42; int b = [this](){ return this->a * 4; }(); }; is valid c++11 code (according specification) or gcc extension? if valid, why have use this-> when referring member a ? is valid c++11 code? no. lambdas in block scope can have capture lists: c++11 5.1.2/9 lambda-expression smallest enclosing scope block scope local lambda expression ; other lambda-expression shall not have capture-list in lambda-introducer . so seems gcc extension. (as noted in comments, open issue , might become standard 1 day.) why have use this-> while referring member a? you don't, @ least version of gcc i'm using: http://ideone.com/k857vc .

netlogo - Finding "types" (reporter/command, and different contexts) of Procedures -

i trying extract, , sort, list of procedures in model. want procedures can run in observer context, , commands, not reporters. workspaces have .getprocedures():map<string, procedure> method , accessing procedure objects that. this leads me 2 related questions: 1. there way me find out if procedure object reporter or command? netlogo desktop version seems able make distinction, think answer might yes. , 2. there way me find out context of procedure is, i.e. whether patch/turtle/link procedure or observer procedure? http://ccl.northwestern.edu/netlogo/docs/scaladoc/org/nlogo/nvm/procedure.html shows procedure has syntax method returning api.syntax object. methods need there, namely ret (which syntax.voidtype or syntax.wildcardtype according whether command or reporter procedure) , agentclassstring (which might e.g. "otpl"). oh see first constructor parameter procedure type tyype (the y because type keyword in scala), first part of question, equa

xcode - iOS : 'MyViewController' does not conform to protocol 'UITableViewDataSource' -

i new ios swift development. used work previous xcode 6 beta . i have downloaded xcode 6.0.1 , can not work xcode version: 6.0.1 i still getting "' myviewcontroller ' not confirm protocol ' uitableviewdatasource ' " when try run example. can please me? have gone through other issues on site , added required functions " uitableviewdatasource "; import uikit import foundation class myviewcontroller: uiviewcontroller, uitableviewdelegate, uitableviewdatasource { var array1:[string] = ["one","two","three","four"] var array2:[string] = ["ios","android","java","c++","swift"] let sectioncount = 2 var mytableview:uitableview! // init(nibname nibnameornil: string?, bundle nibbundleornil: nsbundle?) { // var rect = cgrectmake(0, 0, 220, 320) // mytableview = uitableview(frame: rect, style: uitableviewstyle.

cordova - XMLHTTPRequest completes but throws error message under PhoneGap and IOS 8 "Connection Failed" -

anyone seen "connection failed" message phonegap application running under new ios 8 while making xmlhttprequest takes longer 10ms? have app works fine under ios 7 caveat in xcode can see thread warning messages @ least not throw dialog every call user has close continue while has updated ui behind popup dialog. thread warning: ['notification'] took '31.723145' ms. plugin should use background thread. not sure if there can done, i'm using standard xmlhttprequest async call.

git rebase emergency sandbox commit without affecting another commit thats broken on stage -

this may partially unique scenario here, want rebase, , feel might break "stage" repo branch. note, im developer, no worries other developers having these checkouts. we have ticket 201, , have emergency ticket 407. 201 , 407(in order) have been commited, merged stage(branch), pushed stage. both of these tickets failed pass qa on stage, both need fixes. 407 became emergency fix. 201 wait until 407 has made way production. had go sandbox(branch) , fix it. fixed, , ready commit. 201 needs wait. 201 commited before 407, , shows on both sandbox logs , stage logs. im afraid if rebase out 201 on sandbox temporarily (not sure if best way) finalize 407 fix, when go merge push stage unbeknownst happen , push(or merge) complain unbeknownst errors because of 201 (which rebased out on sandbox) getting in way on stage. is there way rebase out (ticket 201) make way 407 go through stage? happen 201 on stage? if understand scenario correctly, have 2 feature bran

audio - Double sound android -

package project.kalmas; import android.app.activity; import android.content.intent; import android.media.mediaplayer; import android.os.bundle; import android.view.view; public class 1 extends activity { public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.one); } public void onclick2(view view) { intent i=new intent("project.two"); startactivity(i); } public void onclick3(view view) { mediaplayer mp= mediaplayer.create(this,r.raw.one); if(mp.isplaying()){ mp.stop(); } else { mp.start(); } } } when click button play sound again click button stop wont stop , play sound again results in double sound playing @ 1 time.please help you creating new mediaplayer every click, instead of keeping reference first one. mediaplayer playing sound different mediaplayer calling isplaying() o

class - Java Program (Coin Flip simulation) -

this code fliprace program initiates race between 2 coins. goal globally declared variable. whichever coin reaches goal number of heads fastest wins. below code coin class. my problem if put goal = 3 , whichever coin gets 3 heads fastest wins, works ok. when set goal = 4 , still works ok. weird starts happening once put goal > 4. put goal = 7, still final result comes when 1 coin has registered 4 heads not 7. // fliprace.java package nisarg; public class fliprace { public static void main(string[] args){ final int goal = 6; int count1=0,count2=0; coin mycoin1 = new coin(); coin mycoin2 = new coin(); while(count1 < goal && count2 < goal){ mycoin1.flip(); mycoin2.flip(); system.out.print("coin1 : " +mycoin1 +"\t"); system.out.println("coin2 :"+mycoin2); count1 = (mycoin1.isheads())? count1+1 : 0; count2 = (mycoin

mysql - SQL Aggregation with SUM, GROUP BY and JOIN (many-to-many) -

here's example table layout: table_a: table_b: table_a_b: id | | b | c id | name a_id | b_id --------------------- --------- ----------- 1 | true | x | 1 | 1 | 1 2 | true | z | null 2 | b 1 | 2 3 | false | x | null 3 | c 2 | 2 4 | true | y | q 4 | 1 5 | false | null | null 4 | 2 5 | 1 possible values: table_a.a: true, false table_a.b: x, y, z table_a.c: a, b, c, ... arbitrary table_b.name: a, b, c, ... arbitrary what want achieve: select rows table_a sum(where = true), sum(where = false), sum(where b = 'x'), sum(where b = 'y'), sum(where b = 'z'), sum(where b null), , sums distinct table_a.c values. , sums table_a_b relations. the result example table above should like: atrue | afalse | bx | | bz | bnull | ca | cq | cnull | namea |

python - Is threading.local() a safe way to store variables for a single request in Google AppEngine? -

i have google appengine app want set global variable request only. can this? in request_vars.py # request_vars.py global_vars = threading.local() in another.py # another.py request_vars import global_vars get_time(): return global_vars.time_start in main.py # main.py import request_vars import global_vars global_vars.time_start = datetime.datetime.now() time_start = another.get_time() questions: considering multithreading, concurrent requests, building on google appengine, , hundreds (even thousands) of requests per second, value of time_start equal value set in global_vars.time_start in main.py per request? safe use multithreading/threadsafe enabled? yes, using threading.local excellent method set per-request global. request handled 1 thread, on 1 instance in google cloud. thread local value unique thread. take account thread can reused future requests, , reset value @ start of request.

c++ - Eclipse (or maybe windows is to blame?) won't print unless I fflush(stdout) -

i installed eclipse , mingw on sister's computer running windows 7. while testing see if set properly, noticed won't print anything: #include<stdio.h> int main() { int x; printf("hello world!\n"); printf("enter number... \n"); scanf("%d", &x); printf("you entered %d", x); return 0; } instead, waits input, , print whole thing @ once. here's how looks: 345 hello world! enter number... entered 345 it after added call fflush(stdout) after printf("enter number... \n"); eclipse printed in right order, meaning, code: #include<stdio.h> int main() { int x; printf("hello world!\n"); printf("enter number... \n"); fflush(stdout); scanf("%d", &x); printf("you entered %d", x); return 0; } works expected. worth mentioning opened separate c++ project , tried same thing: #include<iostream> int

node.js - nodejs async request stop working but no mistake -

var request = require('request'); var async = require('async'); require('http').globalagent.maxsockets = 30; var count = 0; var urlarr = ['url1','url2'.......] // ten thousand links request async.eachlimit(urlarr, 30, iterator, function(err) { console.log('complete'); }); function iterator(url,callback) { request(url, function(error, response, body) { console.log(count++); if (!error && response.statuscode === 200) { return callback(null); } else{ return callback(null); } }); } the code above stop working after few minutes, no error happen, process hoding , not exit, what's problem it?

html - Overlaying text on top of an object -

i have youtube video on website. know if there way lay out text on top of video give specific title. also how same on left side of video? using bootstrap well. you can use z-index or position in-order this. <div class="container"> <iframe width="560" height="315" src="//www.youtube.com/embed/yxvoqjewqoq" frameborder="0" allowfullscreen></iframe> <div class="my-text"> text</div> </div> css body { background: #efefea } .container { width: 600px; margin: 0 auto; padding: 10px; position: relative; } iframe { marign: 0 auto; } .my-text { position: absolute; color: #fff; padding: 10px 0px; text-align: center; font-size: 50px; background: rgba(0,0,0, 0.5); top: 20px; left: 0; right: 0; } http://jsfiddle.net/websiddu/dy4exbcp/1/

php - Hide Restler method from swagger-ui -

using restler 3.0.0-rc6, internally packages swagger-ui, have api method defined so: <?php namespace v1: class postgresql { public function fetcharray($sql, $args = null) { and of classes include via restler's addapiclass extend postgresql class. means when swagger runs, every single api shows fetcharray function. i'd have method not appear in swagger documentation it's not part of api. other 'things' on website use class though can't change modifier public. what's proper syntax hide method swagger-ui's webpage? there 2 ways achieve this, one mark fetcharray method private @access private comment. remove fetcharray api urls while keeping fetcharray still accessible php problem in case don't want modify postgresql part of framework maintained composer. instead of directly extending base class use intermediary class adds comment , extend class shown below class base { public function fetcharray(){

html - Being Flexbox element as flexbox container too -

// excuse beginner's english hello! can implement follow construction: <div class="flex-container-1"> <div class="flex-element-1 flex-container-2"> <div class="flex-element-2">...</div> <div class="flex-element-2">...</div> </div> <div class="flex-element-1 flex-container-2"> <div class="flex-element-2">...</div> <div class="flex-element-2">...</div> </div> </div> my simple attempt: .flex-container-1, .flex-container-2 { display: flex; } .flex-element-1, .flex-element-2 { flex: auto; } ... not correct. making more flatten not way me, because need grouping container. have ideas? thanks! i don't know want do, in example use display: flex on container. flex box has more possibilities, , can read them here: http://css-tricks.com/snippets/css/a-gu

asp.net mvc 5 - Keep ViewModel list populated from HTTPGet to HTTPPost ActionResult -

in mvc5 internet application, how can keep contents of viewmodel list , between httpget request , httppost request. i have done searching, not sure term search for. here situation: i have viewmodel , has following list populated in httpget actionresult : public list<string> azureblobfullfilenames { get; set; } in httppost actionresult , list null. how can still have list populated values in httppost actionresult ? i have added following code after @html.antiforgerytoken() view line of code: @html.hiddenfor(model => model.azureblobfullfilenames) however, list still null in httppost actionresult . can please have code? thanks in advance generate control element in collection using for loop. for(int = 0; < model.azureblobfullfilenames.count; i++) { @html.hiddenfor(m => m.azureblobfullfilenames[i]) }

sml - A curry function that executes another function n times -

i'm solving old exam practice sml. 1 task found interesting was: write function repeat executes function signature 'a -> 'a. i assumed requested function curry function , used o -operator: fun repeat (1, f: 'a->'a) = f | repeat (n, f: 'a->'a) = f o repeat (n-1, f); however, o operator not formally introduced in out course, , wonder how write without it? not less verbose, in way, explicit, after, less verbose, explanations. a curried function function getting single argument. if expression has more arguments, there many nested functions. first outer level function gets argument, , made of inner level function may it‑self made of inner function, , on. of inner level function may returned, not innermost, explained later (this kind of “partial evaluation”). inner function “specialized” arguments (formally, arguments bound in closure) of outer functions. we know there @ least function argument f , integer argument counter . th

multithreading - Multi-Threading in Ruby -

i have tcpserver made in ruby, server seems work, can see 2 or more clients can connect , served server, but, sometime stuck (as in need wait other client disconnect or unresponsive), after "pass_ok" bit, when connecting 1 client don't see issue. here code: def self.main_server begin server = tcpserver.open(@port) rescue exception => e corelogging.syslog_error("cant start server: #{e}") end @main_pid = process.pid # main loop thread.abort_on_exception = true while true thread.fork(server.accept) |client| @client = client sock_domain, remote_port, remote_hostname, remote_ip = @client.peeraddr # info on incoming connection corelogging.syslog_error("got new connection #{@client.peeraddr[3]} handeled thread: #{thread.current}") # log incoming connection @client.puts "please enter password: " # password testing (later config file or db) action = @cl

c# - DDD, Best way to compose complex conditions for column selection of domain entities -

i'm using entityframework , linq sql , , generic repository , , specification pattern perform linq sql db query selections , using automapper entity dto mapper. the problem : i have set of complex business rules affects of select queries i'm performing in application ( these rules affect on column values in scenarios , affect on query result structure in scenarios ) and confused how switch polymorphism direction based on different specifications in different queries.

ibm mobilefirst - How to Check whether the Client is logged in for Particular Realm or not in worklight 6.2 using Client Side WL API? -

1.) have tried wl.client.isuserauthenticated(realm) not working. 2.) tired refreshing relams wl.client.updateuserinfo (options) in function function wlcommoninit() and tried refreshing outside of wlcommoninit() function. 3.) tried retrieve logged in users details client side these also: a ) wl.client.getusername(realm) b ) wl.client.getloginname(realm) c ) wl.client.isuserauthenticated(realm) but not able boolean value true wl.client.isuserauthenticated(realm) , active details of user logged in particular realm. would please let me know proper details or methods active users details without using wl.server.getactiveuser(realm) server side. i wanted how in client side. regards, sheikh mohammed shamnoon =====comment i able user have set using "wl.server.setactiveuser(realm, useridentity);".i don't have problem in getting logged in user set in server end,i retrieving different adapter using " wl.server.getactiveuser("singlestepauthreal

unix - Bash Script to run against all .log files -

i have bash script called (log2csv). while in current directory can type in terminal: log2csv *.log this run script on every .log file in current directory. alternatively can run against single .log file with log2csv test1.log instead of typing log2csv *.log , can have *.log included in script? can type log2csv in directory , runs. know can alias that, rather have script it. here bash script running: #!/bin/bash path base=$(basename "$path") noext="${base/.log}" [ -e "${noext}.csv" ] && continue /users/joshuacarter/bin/read_scalepack.pl "$path" > "${noext}.csv" done change: for path to: for path in *.log or, perhaps better: names=( "$@" ) if [ "${#names}" = 0 ] names=( *.log ) fi path in "${names[@]}" and can consider whether set options such shopt -s nullglob well. uses shell arrays handle names blanks etc in them. uses command

java - LinkedIn - how to pass query parameter -

is there anyway pass query parameter through linked log in process. trying add query parameter linked in remove , return state , code parameters. there anyway can this? i'm using "state" parameter this. can put there want.

sql - Performance tuning of this query? -

i have below query support employee pagination sorted employee name select rownumalias ,employee.employeeid ,employee.name ( select row_number() on ( order employee.name asc ) rownumalias ,employeeid ,name employee ) employeedata inner join employee on employee.employeeid = employeedata.employeeid rownumalias between ? , ? where parameter rownumalias can integer number between 1 , 100 this query taking around 7 seconds on sql server database having 1 million records. is there way can minimize query execution time ? you can try this: select * ( select (select row_number() on (order e2.name asc) employee e2 employee.employeeid = e2.employeeid) rownumalias, ,employee.employeeid ,employee.name employee ) e3 e3.rownumalias between ? , ?

shell - .Sh script to install java at a specific location -

i using following command install java 8 in ubuntu 32 bit matchine.i using .sh file run these commands- sudo add-apt-repository ppa:webupd8team/java sudo apt-get update sudo apt-get install oracle-java8-set-default read -t 10 it's working fine facing 2 problems it set default location in environment variable of java(i want install in specific direcory home/abc/ , set enviornment variable according that) i want pause script 10 seconds @ end check console. i want check either enviornment variable set or not using comamnd in .sh file export path=$path:$(pwd)/linux_32/software/jdk1.8.0_20/bin and when open terminal , check java -version it not show me why check there problem java installation. each time .sh terminal closed it appears trying run java -version after script modified path environment variable not persist beyond script. they're running in different shells. validate, run printenv path , you'll notice jdk path not appended. you t

ios - Prefix.pch ReactiveCocoa/RACEXTScope.h file not found error -

Image
as mentioned in title, have reactivecocoa/racextscope.h file not found error in prefix.pch file. the following pod file platform :ios, "7.1" pod 'parse-ios-sdk', '~> 1.2' pod 'reactivecocoa', '~> 2.3' pod 'reactiveviewmodel', '~> 0.2' pod 'parse-racextensions', '~> 0.0' pod 'ckcalendar', '~> 1.0' pod 'sdwebimage', '~> 3.6' as can see images, file exists. there not interface declaration in file. matter? i'm using xcode 6.0.1 can give me suggestion? i had same problem. at top of podfile write line: link_with ['projectname', 'projectnametests'] install pod, , @ project build setting->other linker flags, add $(inherited) . that happened because tests couldn't find pods.

java - Type IQuery does not take parameters Error in org.eclipse.equinox.p2.query and org.eclipse.equinox.p2.metadata -

i using eclipse equinox dependencies in implementation , when try compile in java 7 following error. java 6 it's working perfectly. import org.eclipse.equinox.p2.metadata.*; import org.eclipse.equinox.p2.query.iquery; public void checkinstallableunits(){ iquery<iinstallableunit> query = null; } i using following dependency: <dependency> <groupid>org.eclipse.equinox</groupid> <artifactid>org.eclipse.equinox.p2.metadata</artifactid> <version>2.1.0.v20110510</version> </dependency> this has compiling against classfiles built undocumented javac option "-target jsr14". such class files work fine javac 1.6 recognized generics information. javac 1.7 not , sees classes "raw" view. either need keep using javac 1.6 or updated jar files not compiled "-target jsr14".

excel - Ending a macro when autofilter has no matches -

i have macro set filter data year, quarter, mobile (yes / no) end goal being creates schedule document show in q1 - q4 each year subset of data. the issue having once has filtered first 2 variables, if there no matches third (value match ü) negates , copies raw data sheet if no filters applied. sheets("changelog").select activesheet.range("$a$2:$ap$2040").autofilter field:=36, criteria1:="4" activesheet.range("$a$2:$ap$2040").autofilter field:=35, criteria1:="2020" activesheet.range("$a$2:$ap$2040").autofilter field:=15, criteria1:="ü" range("a3:a2041").select selection.copy sheets("!pipeline_template").select range("n77").select selection.pastespecial paste:=xlpastevalues, operation:=xlnone, skipblanks _ :=false, transpose:=false it continues various filter criteria follow same pattern. ideally want end sub if can't find "ü" any appreciated :) mark

linux - find command to prune only files starting with dot(filter files that start with dot) -

the following find command filters files , directories starting dot symbol. find $pwd \( -name '.*' -prune \) -o -print where adding "-type f" condition not filter files starting dot. find $pwd \( -name '.*' -type f -prune \) -o -print # not work how prune files starting dot edit 1: clarification on "does not work" the command lists file starting dot operator. later found symbolic link file(which not start dot). tried using -l (follow symbolic links) option below still listed symbolic link file starting dot. find -l $pwd \( -name '.*' -type f -prune \) -o -print you seem bit confused meaning of "prune": -prune means do not descend subdirectory , not make sense -type f .

Numerical integration Legendre Polynomials MATLAB -

the legendre polynomials implemented in matlab vectors, associated legendre polynomials evaluated @ particular point x. thus, don't know how can use these functions inside integral. question is: how can evaluate (numerically calcualted(!)) integral -1 1 on n-th legendre polynomial in matlab? edit: received answer not want: want use implementation of legendre polynomials in matlab cause other suggestions may highly unstable. n=3 % degree of legendre polynomial step=0.1 % integration step trapz(legendre(n,-1:step:1)')*step this should want

php - How to remove an entity? -

this first time using symfony framework. trying learn doctrine. have created , entity class. have created entity called product. since there wrong deleted entity folder , trying create 1 again. framework not allowing me so. saying entity class exists. how remove previous entity class? you must clear doctrine cache: php app/console doctrine:cache:clear-metadata php app/console doctrine:cache:clear-query php app/console doctrine:cache:clear-result

objective c - Parse - Push notification not working in iOS 8 -

i registering push parse following code: #if __iphone_os_version_max_allowed >= 80000 if ([application respondstoselector:@selector(registerusernotificationsettings:)]) { uiusernotificationtype usernotificationtypes = (uiusernotificationtypealert | uiusernotificationtypebadge | uiusernotificationtypesound); uiusernotificationsettings *settings = [uiusernotificationsettings settingsfortypes:usernotificationtypes categories:nil]; [[uiapplication sharedapplication] registerusernotificationsettings:settings]; [[uiapplication sharedapplication] registerforremotenotifications]; } else #endif { [[uiapplication sharedapplication] registerforremotenotificationtypes:(uiremotenotificationtypebadge | uiremotenotificationtyp

ios - Swipe Image And Have Filter Overlay Along Swipe -

for few days i've been diligently researching how swiping between images filters working. there post has exact same issue: swipe between filtered images basically need swipe between filtered images happens in snapchat, filter progressively overlaid swipe occurs this: https://www.youtube.com/watch?v=j75d7khf6im but answer did not give example code , efforts have been no avail. i have tried following: 1) first tried creating 2 images. 2nd 1 image filtered , first original image. wanted apply alpha mask @ 100% image 2 , 0% image 1. user swipes reduce alpha mask on image 2 , increase image mask image 1. when try follow example code came across run issue. cgimage nil (because original image not created cgimage data , i'm not sure how cgimage data) cgrect rect = cgrectmake(0, 0, 500, 500); cgimageref imageref = cgimagecreatewithimageinrect(_picture.image.cgimage, rect); uiimage*result = [uiimage imagewithcgimage:imageref]; _picture.image = result; cgima

database - On existing record skip otherwise insert data Laravel Eloquent -

i have following table structure seed dynamically api public function up() { schema::create('reports', function(blueprint $table) { $table->engine = 'innodb'; $table->increments('id'); $table->integer('program_id')->unique(); $table->date('date'); . . . $table->timestamps(); }); on each api request array of data , try save theme in table above. if program_id exist ignore records , save new one. i've been looking around not find best way validate specific value in retrieved array sqlstate[23000]: integrity constraint violation: 1062 duplicate entry '528027827' key 'reports_program_id_unique the way save records // $datas field datas api foreach ($datas $data) { $report = \td\reports\reports\reports::firstorcreate($data); } how skip insert on existing program_id , insert new ones? you can use firstorcreate() :

wordpress - First vagrant up fails -

i'm trying vvv , running in order work on wordpress site, , while following "first vagrant up" instructions installation fails. can find terminal output below. just note, vagrant up command below run sudo, same result when running without. https://github.com/varying-vagrant-vagrants/vvv/tree/master#the-first-vagrant-up my installation fails @ step 8 doug@unemac06261 vagrant-local$ sudo vagrant bringing machine 'default' 'virtualbox' provider... ==> default: importing base box 'ubuntu/trusty64'... ==> default: matching mac address nat networking... ==> default: checking if box 'ubuntu/trusty64' date... ==> default: setting name of vm: vagrant-local_default_1411438722704_61758 ==> default: clearing set forwarded ports... ==> default: clearing set network interfaces... ==> default: preparing network interfaces based on configuration... default: adapter 1: nat default: adapter 2: hostonly ==> defaul

plugins - How to update a drop down list of a pull down button in the Eclipse toolbar? -

i have added drop down list dynamically pull down button in eclipse toolbar, following instructions: programmatically add options pulldown button in eclipse now, need update drop down list. idea remove old list , add new list pull down button. tried methods: removecontributionfactory(abstractcontributionfactory factory) , dispose() of imenuservice, none of them works. give me tips of how achieve goal? here code used: (1) in class a, invoke method add drop down list pull down button (command) class { public static contextswitchcontributionfactory contextfactory = new contextswitchcontributionfactory("menu:"+"switchcontext", null); public static imenuservice menuservice = (imenuservice)platformui.getworkbench().getservice(imenuservice.class); ... method () { ... contextswitchcontributionfactory.updatecontextmenu(menuservice, contextfactory, "switchcontext"); ... } (2) definition of contextswitchcontributionfactory: public class

ruby on rails - Calling json.txt files and handling action view controller -

new ror , making sample project learn how js works in rails app using little trivia game . in case want it, relevant code here trivia app. now in ror app, css loads fine because added trivia.css.scss file /stylesheets javascript file because calling both: <%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %> <%= javascript_include_tag "application", "data-turbolinks-track" => true %> so far, good. in line 347 of trivia.js though, call 2 json.txt files used populate test questions: // here add pairs "category_name" , file json quizzes associated each category var files_json = {'general':'general_json.txt', 'animals':'animals_json.txt'}; // calls method creates list categories trivia added in json obtrivia.setcateg(files_json, 'json'); those 2 files test questions not loading, app not recognize quiz files

java - Filter list according to Current date android -

i have arraylist<customobject> contains entries. each entry has date associated it. currently, date stored string. eg "2014-09-23t12:45:00" i want filter list refined list containing entries done today. iam using pattern achieve this. iam receiving null list after filtering. here code:-- public class articlefilter implements predicate<statusresponse> { private final pattern pattern; public articlefilter(final string regex) { pattern = pattern.compile(regex); } @override public boolean apply(final statusresponse input) { string datestring = input.getstarttime(); datestring = datestring.split("t")[0]; // getting date return pattern.matcher(datestring).find(); } } main.java calendar currentdate = calendar.getinstance(); //get current date simpledateformat formatter= new simpledateformat("yyyy/mm/dd"); //format per requirement string daten

regex - capture optional substring -

i'm trying match these lines: x=1 b c y=5 bb aa x=2 aa ccc d x=3 ccc y=9 d ee ff the 'y=x' substring optional. may present in line or not. want capture x=x in group 1, , y=x in optional group 2. i'm using regular expression: ^(x=[0-9]+?).+?(y=[0-9]+?)?.+?$ the whole line matched, i'm capturing first group. second group never captured if optional substring exists. problem between x= , y= lot of different words (with '=' character too). any ideas how capture optional group 2? actual example: http://regex101.com/r/rd4so4/1 updated here's more efficient , cleaner option (that doesn't require alternation): ^(x=[0-9]+)(?:.+?(y=[0-9]+))?.+?$ demo note removed lazy repetition [0-9] since shouldn't have issues matching many characters anyways. explanation the original expression wasn't working because regular expression match left right (and since using lazy repetition, assume understand concept regex "gr

javascript - Get first and fifth business day for each month -

any example of code or function tell if indicative date 1st or 5th business day of current month. business days monday - friday example. passing current date of format yyyy-mm-dd function or code return true if current date corresponds 1st or 5th business day. my interest piqued question. this no means perfect, did ok in quick tests. should invoke getnthbusinessday(5, 9, 2014) 5th working day of sept 2014. in case returns text friday etc, etc var days = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]; function getnthbusinessday(n, month, year) { var worked = 0; (var = 1; <= 31; i++) { var testdate = new date(year, month - 1, i); var day = testdate.getday(); if (day > 0 && day < 6) { if (++worked == n) { return days[day]; } } } }