Posts

Showing posts from June, 2014

c - Why does this code using fork() work? -

i've code executes code depending of if active process parent or child process in infinite loop: pid_t childpid; childpid=fork(); while (1) { if (childpid >=0) { if (childpid==0) { [do child process stuff] } else { [do parent process stuff] } } else { printf("\n fork failed, quitting!!!!!\n"); return 1; } } code simple there's 1 big thing on me don't understand how happens although have guess: if not taking consideration we're creating 2 processes looks childpid being reasigned don't think makes sense. so guess, fork creates childpid each process, returning 0 parent process , pid child process, though syntax makes me think should return 1 result , assign chilpid. is guess correct or there other thing involved? thank you. so guess, fork creates childpid each process, returning 0 parent process , pid child pr

java - android - viewpager OutOfMemoryError -

i have problem. want image url json , setting viewpager. tried drawable folder, large images causing problems. if image small, not have problem. how can large images? benefited article : enter link description here galleryactivity @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_gallery); viewpager viewpager = (viewpager)findviewbyid(r.id.viewpa); galleryadapter ga = new galleryadapter(this); viewpager.setadapter(ga); } gallery adapter (extending pageradapter) context context; private int[] galimages = new int[] { r.drawable.one, r.drawable.two, r.drawable.three }; galleryadapter(context context){ this.context=context; } @override public int getcount() { return galimages.length; } @override public boolean isviewfromobject(view view, object object) { return view == ((imageview) object); } @override public object instantiateitem(viewgr

How to avoid prepending .self when using eval in a reference class in R? -

i need use eval call reference class method. below toy example: myclass <- setrefclass("myclass", fields = c("my_field"), methods = list( initialize = function(){ my_field <<- 3 }, hello = function(){ "hello" }, run = function(user_defined_text){ eval(parse(text = user_defined_text)) } ) ) p <- myclass$new() p$run("hello()") # error: not find function "hello" - doesn't work p$run(".self$hello()") # "hello" - works p$run("hello()") # "hello" - works?! p <- myclass$new() p$run("my_field") # 3 - no need add .self i guess eval(parse(text = paste0(".self$", user_defined_text))) , don't understand: why .self needed eval methods, not fields? why .self no longer needed after has been used once? 'why' questions challenging answer;

ios - Objective-c: How to add borders to a UIView with auto layout -

how add border specific color , thickness uiview when using auto layout in objective-c ? this function add border specific color , thickness border of uiview - (void)addborder:(uiview *)view toedge:(uirectedge)edge withcolor:(uicolor *)color withthickness:(float)thickness{ uiview *border = [uiview new]; border.backgroundcolor = color; [border setautoresizingmask:uiviewautoresizingflexiblewidth | uiviewautoresizingflexiblebottommargin]; switch (edge) { case uirectedgetop: border.frame = cgrectmake(0, 0, view.frame.size.width, thickness); break; case uirectedgebottom: border.frame = cgrectmake(0, view.frame.size.height - thickness, view.frame.size.width, thickness); break; case uirectedgeleft: border.frame = cgrectmake(0, 0, thickness, view.frame.size.height); break; case uirectedgeright: border.frame = cgrectmake(view.frame.size.width - thick

jquery - Resorting the active bootstrap tab when stacked -

Image
for new bootstrap website i'm working on, sorting active tab when nav-tab stacks, selected tab connected tab-pane. while works, feels hack me. there better way accomplish preserves original tab order? html markup: <div id="tab-bundle" class="container-fluid"> @html.hiddenfor(model => model.selectedbundle) <ul class="nav nav-tabs" id="coveragetabs"> <li><a href="#minimum">@languagedb.me.minimum</a></li> <li><a href="#better">@languagedb.me.better</a></li> <li><a href="#best">@languagedb.me.best</a></li> <li><a href="#custom">@languagedb.me.custom</a></li> </ul> <div class="tab-content"> <div class="tab-pane active bg-info" id="ajaxpanel"> @html.partial("selectedb

Is there a way I can update my Meteor app without wiping my MongoDB on the production server? -

i'm installing ssl certificate , need run mupx setup , mupx deploy work. however, doing , deploying app wipe mongodb on production server , users lose of accounts. nightmare. i run mupx deploy after making fixed meteor app update app. however, when installing ssl certificate (according mup documentation) have run mupx setup work. is there way can without wiping user database on deployment server?

web services - Host web UI with executable application? -

this may stupid question have spent 5 hours doing research on web , found nothing clarify doubts. in few words have been asked possible employer develop executable application part of "technical test". supposedly they're measuring expertise working wcf. given 2 days develop such app , information following: deliverable:                 - executable that                                 * when app ran, should host wcf service (service) web ui (ui) accessible web browsers.                                 * through ui, user should able add or delete messages stored in database (db).                                 * ui should display current list of messages stored in db.                                 * if changes made db, changes should show in ui without need reload page.                 - of project source code.                 additional notes: use of existing libraries allowed long r

Mathjax 2.6 - Font Size in Hidden Elements -

<style> .s1{font-size:12px} </style> <div class="s1"> $\dfrac{1}{2}$ </div> the above code works fine , mathjax (version 2.6) renders correctly. math getting scaled down expected. suppose above div loaded style "display:none" , math displayed when clicking link changing display block. in case, math not scaled down. i see many have faced same issue. github page explains issue in detail. problem happens because browser not compute sizes of sub-elements if style "display:none". mathjax processes in seperate hidden elements. the solution suggested make use of "position: absolute; top: 0, left:0; width:0, height:0, overflow: hidden; visibility: hidden;" another approach reprocess math in such divs but, there better approach address problem, possibly forcing browser calculate size of display:none elements or other means?

python - Upload PySpark RDD into BigQuery -

i download table bq pyspark rdd below. how upload again? dgsconfig = { 'project_id': "project_id", 'bucket': "bucket_id" } dbqconfig = { 'gs_config': dgsconfig, 'project_id': "project_id", 'dataset_id': "dataset_id", 'table_id': "table_id" } osc = instantiate_pyspark() rdddata, lsheadings = get_table_cloud(osc, dbqconfig) #rdddata has list-of-lists type format def instantiate_pyspark(): """instantiate pyspark rdd stuff""" import pyspark osc = pyspark.sparkcontext() ohadoopconf = osc._jsc.hadoopconfiguration() ohadoopconf.get("fs.gs.system.bucket") return osc def get_table_cloud(osc, dbqconfig): """get table bigquery via google cloud storage config format: dgsconfig = {'project_id': '', 'bucket': ''} dbqconfig = {

accessibility - How can I add JAWS-compatible HTML form labels to month and day dropdowns in jQuery UI 1.10.4 datepicker -

we using jquery 1.10.4 datepicker month , year dropdowns. unfortunately, these dropdowns not have html labels attached, need screenreader requirements. have been trying find workaround not involve editing jquery code directly (which take 2 minutes) don't forget next time upgrade our jquery version. lack of labels accessibility (a11y) issue, essential our site. the html field looks this: <label for="dateofbirth">birth date (mm/dd/yyyy) </label> <input type="text" id="dateofbirth" name="dateofbirth" value="" class="datepick form-control form-text required hasdatepicker"> the setup datepicker looks this: function setupcalendarmonthyearlabels() { if ($("select.ui-datepicker-month").attr('id') != 'ui-datepicker-month-select') { $("select.ui-datepicker-month").attr('id', 'ui-datepicker-month-select'); } if ($("select.

java - How to pass a function that calls a two dimensional array as a parameter? -

char board[][]=printboard(board); printboard(board); public char[][] printboard (char [][] test){ char[][] game = { {'_','1','2','3'}, {'1','_', '_', '_'}, {'2','_', '_', '_'}, {'3','_', '_', '_'} }; return game; } hi, wondering how call printboard function? nothing in printboard highlighted in red think problem not calling correctly. help.i'm trying put board in it's own function , call using 2d array variable board[][]. i'm trying make tic tac toe game. when run doesn't print board. you never call print method, allocate array. below example of how it: char board[][] = { {'_','1','2','3'}, {'1','_', '_', '_'}, {'2','_', '_', '_'}, {'3','_', '_', '_&

javascript - Keeping thumbnails aligned in Twitter Bootstrap using AngularJS? -

as can seen various questions on stackoverflow, twitter bootstrap doesn't align thumbnails. how solve in python, similar php solution ; using counter detect row ending create new div go in. what 'angular'-way of doing this? - i'm guessing hacking solution span s isn't answer... here plnkr partial test-case; in actual app columns on left aren't aligned either: http://plnkr.co/edit/u8fjvavifglu7vq4kale your problem sizing of divs (span3) messing position of thumbnails. if have screen width, example, text "we welcome you" spills on next line causing thumbnail pushed down. can fixed altering sizing of spans if necessary or possibly other methods such playing around how you've laid html out. (possibly sticking "we welcome you" on next line). also, pilha mentioned in comments, need careful how use bootstrap span classes.

python - remove known exact row in huge csv -

i have ~220 million row, 7 column csv file. need remove row 2636759. file 7.7gb, more fit in memory. i'm familiar r, in python or bash. i can't read or write file in 1 operation. best way build file incrementally on disk, instead of trying in memory? i've tried find on have been able find how files small enough read/write in memory, or rows @ beginning of file. a python solution: import os open('tmp.csv','w') tmp: open('file.csv','r') infile: linenumber, line in enumerate(infile): if linenumber != 10234: tmp.write(line) # copy original file. can skip if don't # mind (or prefer) having both files lying around open('tmp.csv','r') tmp: open('file.csv','w') out: line in tmp: out.write(line) os.remove('tmp.csv') # remove temporary file this duplicates data, may not optimal if disk space issue. in place writ

reactjs - Design Pattern Help: How to render dynamic views from a single controller component? -

i current have component holds business logic, depending on page, i'd render different views. i'm having trouble since i'm not sure how elegantly pass functions , props of control component view component. right now, solution is: <controller viewcomponent={viewcomponent} /> and rendering inside controller: <this.props.viewcomponent function1={this.func} function2={this.func2} /> it works, it's confusing , i'm not elegant solution. there's solution cloning, seems hack too. does have insight how solve this? why not do: <controller> <viewcomponent ... /> </controller> and in controller's render function: <div> {this.props.children} </div> update: if want pass parents functions , state/props children use react.children.map func. renderchildren = () => { react.children.map(this.props.children, (c) => { <c.type {...this.props} {...c.props} somefunction={

caching - How to get L3 cache info (size, line length) on Intel processor using cpuid? -

i encountered trouble during getting l3 cache info on intel processors. getting l3 line length on amd simple, this: mov eax, 0x80000006 cpuid shl edx, 24 shr edx, 24 the same operation on intels more complicated. got might done using sequence: mov eax, 2 cpuid and pasring register values manual: http://www.microbe.cz/docs/cpuid.pdf (page 26, "table 2-7. descriptor decode values"). but program not found of enumerated descriptors , returns 0 cache size , line length. is there simpler and/or sufficient method cache size , line length on intels? here full code. cpuid output (eax, ebx, ecx, edx) pushed onto stack, each value compared hardcoded descriptors list. comparation made on lower 8 bits, these bits shrinked. __declspec(dllexport) __declspec(naked) void getmetriclevel2(int &length) { __asm { // check cpuid availability pushfd pop eax mov ebx, eax xor eax, 00200000h push eax popfd pu

html - Dynamically convert section of WordPress page into image -

been going crazy trying figure out. so basically, have page built in wordpress: http://www.allaroundmath.com/tempe-schedule-test/ what find way export what's in blue , grey table (built visual composer plugin) image, printable. ideally, happen when clicking on print-friendly version button (which right leads .jpg created photoshop). i've tried using print stylesheets recreate what's on page when printing, not working reason (perhaps issue visual composer). a way export page pdf form while keeping page styling acceptable solution. i'm not sure if possible, appreciate feedback regardless.

jms - How to configure Apache QPID to work with RabbitMQ? -

hello happy understand how can write simple java standalone program sends , receives messages rabbitmq using apache qpid jms client. how can create initial context qpid , lookup destination rabbitmq? i searched lot in internet not able find solution helps me better understanding on creating connection between two. i believe should possible due fact both rabbitmq , qpid using amqp protocol. i tried create context following jndi.properties: java.naming.factory.initial = org.apache.qpid.jms.jndi.jmsinitialcontextfactory connectionfactory.myfactorylookup = amqp://:5672 queue.myqueuelookup = queue and following code: context context = new initialcontext(); connectionfactory factory = (connectionfactory) context.lookup("myfactorylookup"); destination queue = (destination) context.lookup("myqueuelookup"); connection connection = factory.createconnection(user, password); connection.setexceptionlistener(new myexceptionliste

Python: Assigning user input as key in dictionary -

problem trying assign user input key in dictionary. if user input key print out value, else print invalid key. problem keys , values text file. simplicity use random data text. appreciated. file.txt dog,bark cat,meow bird,chirp code def main(): file = open("file.txt") in file: = i.strip() animal, sound = i.split(",") dict = {animal : sound} keyinput = input("enter animal know sounds like: ") if keyinput in dict: print("the ",keyinput,sound,"s") else: print("the animal not in list") on every iteration of loop, redefining dictionary , instead, add new entries: d = {} in file: = i.strip() animal, sound = i.split(",") d[animal] = sound then, can access dictionary items key: keyinput = input("enter animal know sounds like: ") if keyinput in d: print("the {key} {value}s".format(key=keyinput, value=

d3.js - nvd3 - Format Milliseconds to h:m:s in Chart (Period of Time, not Date) -

i've managed display dates in d3/ nvd3 charts, did passing value of milliseconds: chart.xaxis .tickformat(function(d) { return d3.time.format('%e, %h:%m')(new date(d)) }); i'd display milliseconds period of time on y-axis, "6 h : 23 min : 5 sec". is possible? thanks in advance! muff try d3.time.format('%h h : %m min : %s sec')(new date()) it format date this 05 h : 34 min : 26 sec or if don't 0 padding hours do d3.time.format('%-h h : %m min : %s sec')(new date()) it format date this 5 h : 37 min : 54 sec edit in such case need put if block check , return desired format this: .tickformat(function(d) { var date = new date(d); if (date.gethours() == 0){ return d3.time.format('%m min : %s sec')(d) } else { return d3.time.format('%-h h : %m min : %s sec')(d) } }

How to generate a certain amount from PHP array? -

i'm trying generate list php array when user enters number say, 3, 3 total of each element in array displayed. example: $number_to_generate = 3; jobs = array('academic', 'administrator', 'architect',.......); output: academic academic academic administrator administrator administrator architect architect architect this have: // check if tmp_profession_array empty // if empty grab random profession , add tmp_profession_array array_filter($tmp_profession_array); if (empty($tmp_profession_array)) { $profession = array_rand($professions_array, 1); $tmp_profession_array[$profession] = 1; } else { // if not empty, grab last profession end($tmp_profession_array); $profession = key($tmp_profession_array); //// if not less amount generate grab new profession not exist in tmp_profession_array if ($tmp_profession_array[$profession] > $number_to_generate) { $break = true; while ($break) { if (in

jquery - Fixed and Variable Column Widths (Table or Float)? -

i'm creating 3 column, full width page want have 2 columns fixed width , other 1 fit full width between them, so: | fixed width || variable width || fixed width | | left || adapts browser window size || fixed right | i tried float didn't work , suggested using display-table worked until had edit page slightly. right hand column ok 2 left columns have content right down @ bottom , not @ top needs be. can please this. here code using: .pagecontent{ background-color: #dadee1; width: 100%; padding: 10px 0px 10px 0px; } .gridsystem{ display: table; } section{ display: table-cell; } .mainsidebar{ float: left; vertical-align: top; width: 140px; } .mainpage{ width: inherit; overflow: hidden; margin: 0px 0px 0px 0px; padding: 20px; } .mainadvert{ float: right; width: 140px; } <div class="

ruby - Rails 5 beta Turbolinks events not firing, progress bar not working -

i'm kind of new rails , web development whole. i'm trying set default progress bar in turbolinks rails described here . at first, thought might have fact progress bar shows if page takes longer 500ms load. tried testing using sleep 10 in controller doesn't seem work. then tried debugging actual turbolink events see if callbacks registering using vanilla js straight in application.js : document.addeventlistener("turbolinks:load", function () { console.log("load"); }); document.addeventlistener("turbolinks:request-start", function () { console.log("request start"); }); document.addeventlistener("turbolinks:visit", function () { console.log("visit"); }); document.addeventlistener("turbolinks:render", function () { console.log("render"); }); for reason, turbolinks:load function seems work. what not seeing or doing wrong? thanks.

java - ReboundPanel Inheritance -

Image
the happy face im using----) this project wants me modify rebound program chapter such when mouse button clicked animation stops, , when clicked again animation resumes. when click on screen moving smiley face, doesnt stop when click nor start again because couldnt stop smiley face moving doing wrong? here problem area.------) | private class reboundmouselistener implements mouselistener { public void mouseclicked(mouseevent event) { if (timer.isrunning()) timer.stop(); else timer.start(); } } public void mouseentered(mouseevent event) {} public void mouseexited(mouseevent event) {} public void mousepressed(mouseevent event) {} public void mousereleased(mouseevent event) {} } here rest of code: public class reboundpanel extends jpanel { private final int width =300, height= 100; private final int delay= 20, image_size=35; private imageicon image; private timer timer; private int

jquery - Why does my dynamically changing link not work? (Javascript) -

i making flash site changes download link everytime button selected on page corespronding flash file download. weird part got working after week of working on project stopped , have no idea why input great. $(document).ready(function () { var links = [ 'swfs/#1%20(special%20japanese%20extended%20dance%20mix).swf', 'swfs/$d6.swf', 'swfs/(mad)%20huh.swf' ]; var displaytext = [ '#1 (special japanese extended dance mix)', '$d6', '(mad) huh' ]; var c = 0; var flashmovie, test, temp; function init() { flashmovie = document.getelementbyid('flashmovie'); document.getelementbyid('back').onclick = function () { if (c == 0) { c = links.length; } c-- displayfiles();

How can I make an angularjs button click call a passed-in function? -

i'm trying make application has data-driven ui. so, i'm trying pass in function should called when button clicked. second button works, of course, explicitly calls function. however, first 1 doesn't. here's angular js code: $scope.clickfunction = "clickedit()"; $scope.clickedit = function(){ alert("it worked!");} and html: <p>how can make button call passed-in function?</p> <button ng-click="{{clickfunction}}">click me</button> <p>i'd evaluate this, works.</p> <button ng-click="clickedit()">click me</button> here's plunker code i'm try make work. http://plnkr.co/edit/arbx3bbghcv15mgrozx1?p=preview you need define function name in controller want use event handler: $scope.clickfunction = "clickedit"; then in template use bracket notation: <button ng-click="this[clickfunction]()">click me</button> the idea thi

google bigquery - Same exactly Query Fails or "Succeeds" with different Aliases used -

Image
below 2 versions of same query version 1 (uses k alias in inner select): select k [year], w_vol, row_number() on (order k desc) rank1, row_number() on (order w_vol desc) rank2 ( select w_vol, c_date k (select 1590 c_date, 1 w_vol), (select 1599 c_date, 1 w_vol), (select 1602 c_date, 1 w_vol), (select 1609 c_date, 2 w_vol), (select 1610 c_date, 1 w_vol), ) order 1 version 2 (uses l alias in inner select): select l [year], w_vol, row_number() on (order l desc) rank1, row_number() on (order w_vol desc) rank2 ( select w_vol, c_date l (select 1590 c_date, 1 w_vol), (select 1599 c_date, 1 w_vol), (select 1602 c_date, 1 w_vol), (select 1609 c_date, 2 w_vol), (select 1610 c_date, 1 w_vol), ) order 1 below output consistently getting both queries (note no cached results used) i expected result same no matter alias used - alias @ all! question : why consistently getting failure version 1 , "success&qu

list - Python: I don't understand the order of a function calling a function -

i'm following book data science scratch joel grus , decribe following code create identity matrix def make_matrix(num_rows, num_cols, entry_fn): return [[entry_fn(i, j) j in range(num_cols)] in range(num_rows)] def is_diagonal(i, j): return 1 if == j else 0 identity_matrix = make_matrix(5, 5, is_diagonal) although can sort of see how create identity matrix, i'm having difficulties understanding it. the way see call function make_matrix arguments 5 , 5 , is_diagonal . @ point code go is_diagonal(i, j) j in range(5) , go function is_diagonal without having seen outer loop ... in range(5) . if true, seems function is_diagonal input variable (0,j) , (1,j) , ..., (4,j) , is_diagonal doesn't enough input variables (because j isn't defined). please explain i'm going wrong in train of thoughts? that type of expression (a comprehension) best of thought of in yoda sense: backwards is. last part of expre

Delete all null rows - Access VBA -

basic question. i need delete null/blank rows of table in database. trouble there no way know how many fields there are, or names of fields before delete. , need verify every field null/blank before deleting. not sure how query in access vba. in examples find, have field name can test blanks. thanks in advance. change testtabke table name. if have autonumber field, must skipped. using dao. if want ado, convert following code. function deleteemptyrows() dim db dao.database set db = currentdb dim rs dao.recordset set rs = db.openrecordset("testtable") until rs.eof inx = 0 rs.fields.count - 1 if isnull(rs.fields(inx).value) or len(trim(rs.fields(inx).value)) = 0 else: exit end if next if rs.fields.count = inx rs.delete end if rs.movenext loop end function

c++ - Is it possible to vsync a single buffered context? -

i writing time critical code scientific application uses opengl perform rendering. device i'm controlling appears computer monitor. dream refresh device @ 60 hz. i tried use single buffer raster mode, having trouble getting vsync work. in double buffered mode works. can vsync single buffered context? works pfd.dwflags = pfd_draw_to_window | pfd_support_opengl | pfd_doublebuffer; pfd.ipixeltype = pfd_type_rgba; pfd.ccolorbits = 24; pfd.cdepthbits = 16; pfd.ilayertype = pfd_main_plane; doesn't work pfd.dwflags = pfd_draw_to_window | pfd_support_opengl; pfd.ipixeltype = pfd_type_rgba; pfd.ccolorbits = 24; pfd.cdepthbits = 16; pfd.ilayertype = pfd_main_plane; edit at end of render loop glflush(); glfinish(); swapbuffers();//gdi? in order synchronize buffer swap screen refresh (what vsync does), going need have multiple buffers swap. thus, double buffering going necessary. the way enable vsync once have double buffering platform dependent, though a.l

Loop 2 arrays and check if equal values and update data C# -

i have 1 array max 2 ids of pictures null or 1 id on server side. second array coming client side , can have 2, 1 or 0 elements. now need check if id client side in array on server side , if yes delete old 1 , replace new. example: oldid(1 , 2) newid(2 , 3) if ([2] != [1] && [2] != [2]) { //ignore replacing oldid array } if ([3] != [1] && [3] != [2]) { //replace array } so @ end should have array(3 , 2) thank you. according example: foreach(var item in clientarray) { if(!serverarray.contains(item)) { // } } but sentence (above example) says opposite.

compiler construction - Preprocessing vs Linking -

everywhere linker (besides relocation, seem put under "loading") people give examples of 2 (say) c modules call functions each other. as far understand , should taken care of preprocessing (#include etc). can understand if want assemble 2 modules @ different times need link them later. when use gcc, directly outputs executable , in context don't see point of linking except when preprocessing (which recursive i'd guess) final hits object code. note : i'm referring static linking here. can see point when comes dynamic linking. gcc using lot of tools create executable, compiler 1 of them , linker, preprocessor etc, see it's doing pass -v option. if want see intermediate files use -save-temps ie once you've created files below try this... gcc-5 -save-temps -v -std=c11 -wall -pedantic-errors main.c foo.c if in directory you'll see several files... a.out // executable when no name specified foo.c // original foo.c foo.h // original

netlink multicast from kernel to user space error in linux kernel 3.10 in c -

i have refered following source yd ahhrk multicast kernel user space via netlink in c the module insmod correctly , lsmod|less can see there , while try run user space application , have error: seotsockopt < 0 in user space application , doing group error : if (setsockopt(sock, 270, netlink_add_membership, &group, sizeof(group)) < 0) { printf("seotsockopt < 0\n"); return -1; } while google other sources , setsockopt , netlink_add_membership doing exact right thing , except yd ahhrk tested in 3.13 , test in 3.10 , have no idea how avoid error , make work . edit : the following in code : xyzkernel.c #include <linux/module.h> #include <linux/kernel.h> #include <linux/netlink.h> #include <net/netlink.h> #include <net/net_namespace.h> /* protocol family, consistent in both kernel prog , user prog. */ #define myproto netlink_usersock /* multicast group, consistent in both kernel prog , user prog. */ #def

java - Mocking a interface with Mockito -

can please me below mock object. want write mock test case class. want mock interface public interface orderif{ list<order> ordersfor(string type); } and implementation doesn't exists. public class serviceimpl implements service { private list <order> orders ; private orderif orderif ; // 3rd party interface public int getval(string type) { //some code // returns list of objects (orders) orders = orderif.ordersfor(type); // code return orders.get(0) } i trying below no luck. receving nullpoinerexcetion. public class serviceimpltest { private list <order> ll ; private service reqservice ; @injectmocks private orderif order; @before public void setup() throws exception { ll = new arraylist<order> (); ll.add(new order("buy" , 11 , "usd" )); ll.add(new order("sell" , 22 , "usd" )); reqservice = spy

java - Threads Execution -

is possible know when thread has completed execution without using of builtin function isalive, join. suppose have 3 threads a, b , c running in parallel. how know whether threads have completed execution. you can use countdownlatch out it. let's you're making threads executorservice, make like countdownlatch latch = new countdownlatch(threadscount); executorservice executor = executors.newfixedthreadpool(threadscount); (int x = 0; x < threadscount; x++) { executor.submit(new classname(latch)); } try { latch.await(); } catch (exception ignored){} //all threads done @ point and in classname should have this: class classname implements runnable { private countdownlatch latch; //constructor: classname(countdownlatch latch) { this.latch = latch; } //run method: @override void run() { //your thread code...

java - OpenSessionInterceptor for Spring-Hibernate-AOP context -

i'm developing web app application spring 4, jsf 2 , hibernate 5. manage transactional operation in hibernate in web context, use opensessioninviewfilter in web.xml . <filter> <filter-name>opensessioninviewfilter</filter-name> <filter-class>org.springframework.orm.hibernate5.support.opensessioninviewfilter</filter-class> </filter> <filter-mapping> <filter-name>opensessioninviewfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> my spring context configuration datasource is: <bean id="datasource" class="com.p6spy.engine.spy.p6datasource"> <constructor-arg> <bean class="org.springframework.jdbc.datasource.drivermanagerdatasource"> <property name="driverclassname" value="${jdbc.driverclassname}" /> <property name="url" value="${jd

java - How to get LatLng data from Google Geocoding API json? -

i creating application map , faced problem. have mapview in fragment , autocompletetextview. when pick city autocomplete, should appear marker on map. here code , working on real samsung galaxy s3 , galaxy s6 emulator, not work on meizu mx5. found, geocoder not work on every device, there solution google geocoding api. got json answer, don't know how latlang , featurename json. example of json: http://maps.google.com/maps/api/geocode/json?address=london&sensor=true i new android, sorry if not clear. atvfrom.setonitemclicklistener(new adapterview.onitemclicklistener() { @override public void onitemclick(adapterview<?> parent, view view, int position, long id) { locationfrom = atvfrom.gettext().tostring(); list<address> addresslistfrom = null; geocoder geocoder = new geocoder(getactivity()); try { if (markerfrom[0] != null) {markerfrom[0].remove();} addressli

Event Sourcing - Aggregate modeling -

two questions 1) how model aggregate , reference between them 2) how organise/store events can retrieved efficiently take typical use case example, have order , lineitem (they aggregate, order aggregate root), , product aggregate. lineitem needs know product, there 2 options 1) lineitem has direct reference product aggregate (which seems not best practice, violate idea of aggregate being consistence boundary because can update product aggregate directly order aggregate) 2) lineitem has productid. it looks 2nd option way go...what think here? however, problem arises building order read/view model. in order view model, needs know products in order (i.e. productid, type, etc.). typical use case reporting, , commandhandler can use product object perform logic such whether there many particular products, etc. in order it, given fact data in 2 separate aggregate, need 1+ database roundtrips. using events build model, pseudo code looks below 1) given order id (guid, order aggregate

azure - How can I apply <clientCache /> settings to a specific extension in IIS? -

Image
i hosting web app on azure following web.config: <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webserver> <staticcontent> <mimemap fileextension=".text" mimetype="text/plain" /> <clientcache cachecontrolcustom="public" cachecontrolmode="usemaxage" cachecontrolmaxage="7.00:00:00" /> </staticcontent> </system.webserver> </configuration> this works vary cache age extension. set max age of .html files 1 day , max age of else 365 days. reason being of assets in html have filenames revved on change , served cdn, never need expire, html pages need fresh user can see new content. i see <location> element allows filtering web.config specific locations, don't see way limit extensions. please note don't require being able in web.config: means possible azure web app fine. others have mentioned not

sql server - How do you select an exact date in SQL? -

select o.customerid, c.customername, o.orderdate orders o, customers c o.orderdate='1997-08-26'; using sample northwind db, can't quite figure out wrong? have used format of date used in sample table. i trying extract id , name of placed order on 26th. you need join orders , customers tables each other: select o.customerid, c.customername, o.orderdate orders o, customers c o.orderdate='19970826' , o.customerid = c.customerid using explicit syntax: select o.customerid, c.customername, o.orderdate orders o join customers c on c.customerid = o.customerid o.orderdate = '19970826' you should read explicit vs. implicit join syntax.

asp.net - WebApi in OWIN always returning 200 instead of 404 when not matching a route -

i have relatively simple webapi site couple of controllers, running in owin autofac di container. the site setup using attribute routes returns 200 ok response if hit invalid route. had filters , static file server running i've commented out of code within our startup file (all iappbuilder calls , creation of httpconfiguration) still behaviour. happens in both iis , iis express. i've tried adding default route in have seen same behaviour. i've done reading , understand can write kind of hook pipeline or write controller catch route , action returns 404, feels though shouldn't necessary. is intended default behaviour? i've looked @ answer don't have global.asax: asp.net web api returns 200 ok when should return 404 see reduced code below still demonstrates issue startup.cs [assembly: owinstartup(typeof(startup))] namespace api.blah { using owin; public class startup { public void configuration(iappbuilder app) {