Posts

Showing posts from June, 2010

Is there any case when a Stack or a Queue implementation with ArrayList gives better, faster performance then a LinkedList implemented in Java? -

in question read following: if you're doing comparatively few operations, ie less 1000 or enqueue/dequeues in total, array faster because contiguous in memory. my question is: how caching arraylist works in java? there cases, when arraylist implemented queue or stack perform better linkedlist implemented in java? hen arraylist implemented queue or stack perform better linkedlist implemented in java? when queue empty or 1 element, arraylist faster , creates less garbage (ie none) if have fast consumer, consumer ever producer produces produces it. means there typically 0 or 1 elements in queue. under these conditions arraylist faster doesn't create objects or produce garbage. btw arraydeque better choice because performs if there more 1 element. how caching arraylist works in java? there nothing special way cpu caches accesses arraylist.

c - Creating a counter with atomic_fetch_add_explicit -

#include <stdatomic.h> void request_number(request_t *request) { static atomic_int counter; request->id = atomic_fetch_add_explicit(&counter, 1, memory_order_relaxed); printf("request assigned id %u\n" request->id); } in above c snippet, believe it's ok use memory_order_relaxed , because without memory fences compiler not re-arrange call printf , fetch of request->id , before store of value request->id . is correct? i'm wanted absolutely sure in case there other things need taken account atomics. you doing 1 atomic operation , when return have value. else done "normal" memory model sequential code, has been. the ; @ end of assignment sequence point. approach fine. indeed, thing need atomic operation here is undivided, don't need sequencing guarantees of "normal" atomic operations.

python - Is my fabric code actually multithreading? -

i attempting multi-threaded solution using gevent set of tasks, of use fabric api . when trying monkeypatch, fabric fails read env , prompts password. when not patching works, execution not appear asynchronous. created following toy example question: from gevent import monkey, spawn, sleep, joinall monkey.patch_socket() # if removed, "appears to" runs serial fabric.api import run, env, settings import os env.use_ssh_config = true env.host_string = "user@remotehost" env.user = "user" env.key_filename = os.path.expanduser('~/.ssh/id_rsa_4096') env.password = "" env.port = 22 def toytask(char): command = "ls %s*" %char print command settings(warn_only=true): run(command) sleep() charlist = list(map(chr,range(97,123))) # creates ['a','b',...........'z'] threads = [spawn(toytask, char) char in charlist] joinall(threads) in current form, returns: me@localhost:~$ pytho...

sql - RETURN comma list with NULLs if item not found IN list -

i running microsoft sql server 2012 - 11.0.5058.0 (x64) standard edition (64-bit) on windows nt 6.3 (build 9600: ) (hypervisor). inputing sensor data database @ 1hz. each test has variable number of sensors of type. channel name ( chname ) describe user are. the user select testid , chname 's want web interface. i have table setup contains approximately 15 million rows ~50 testids: timestamp datetime , testid int , chname varchar(100) , value real timestamp | testid | chname | value 13:52:12 | 1000 | | 23 13:52:12 | 1000 | b | 2 13:52:12 | 1000 | c | 150 13:52:13 | 1000 | | 25 13:52:13 | 1000 | c | 147 13:52:13 | 1000 | b | 1 13:52:14 | 1000 | | 24 13:52:14 | 1000 | b | 4 13:52:14 | 1000 | c | 151 13:52:15 | 1000 | b | 8 13:52:15 | 1000 | c | 153 13:52:16 | 1000 | b | 3 13:52:16 | 1000 | c | 149 13:52:17 | 1000 | c | 152 13:52:17 | 1000 | | 27 ...

c# - Scanning certificates store does not show all certificates -

i created c#.net console program listed below scan certificate stores , show certificate information. problem is not showing certificates. for example, command line shows certificates in personal store: certutil.exe -store however test program shows having no personal certificates. using windows 2008 r2. here abbreviated console app. idea might doing wrong? tried both in regular cmd window, , administrator same results. using system; using system.linq; using system.security.cryptography.x509certificates; using system.collections; namespace certview { class program { static int main(string[] args) { var stores = enum.getvalues(typeof(storename)); ienumerator enumstores = stores.getenumerator(); foreach (storename sn in stores) { x509store str = new x509store(sn.tostring()); str.open(openflags.readonly); int count = str.certificates.count; ...

excel - macro to copy multiple cell ranges and paste in a row on another sheet -

i recorded macro, i'm trying obtain creating code copy following range in code on each worksheet , paste in rows underneath each other on sheet "master". i have following code: sub macro1() ' ' macro1 macro ' ' dim rng range sheets("al-jackson hospital-fvar").select set rng = range( _ "k50:m50,k58:m58,k59:m59,k55:m55,k12:m12,k14:m14,k24:l24,k28:l28,k29:l29,k35:l35,k62:l62,k32:l32,k30:l30,k31:l31,k63:l63,k33:l33,k34:l34,k37:l37,k40:l40,k41:l41,k42:l42,k46:l46" _ ) rng.select selection.copy sheets("master").select range("b4").select range("b4").select selection.pastespecial paste:=xlpastevalues, operation:=xlnone, skipblanks _ :=false, transpose:=false activewindow.scrollworkbooktabs position:=xlfirst end sub for example: on sheet 1, 2 ,3 copy following range on each sheet , paste values in sheet master starting in cell b1. sheet 1 data range should in b1, sheet 2 data range should in...

html - Positioning a nested DIV relative to the page and not the first positioned ancestor -

is there way position nested div (or other nested html element) relative page (so 0,0 put @ top left of page) when has positioned ancestor, without using javascript. using position:fixed won't work because positions relative viewport, not move if page scrolled. using position:absolute won't work since asking nested div positioned ancestor. cause position relative positioned ancestor. no, can't done without script ... ... unless outer element's left/top position known/fixed, in example .nr1, .nr2 { position: absolute; width: 300px; height: 100px; } .nr1 { left: 50px; top: 50px; background: red; } .nr2 { left: 0; top: 0; background: blue; margin: -50px 0 0 -50px; } <div class="nr1"> <div class="nr2"> </div> </div>

installation - Cannot download resources. Added EULA package on prequisites clickonce application -

Image
i have click once application deployed on web server. added eula prerequisite application. when downloaded setup installer, eula getting printed, when click accept , starts download. shows me following error. my publish files stored on path c:\webapplications\zephyr\zephyrpos\downloads i'm not sure why i'm getting error. i'm sure files there. ideas? thanks! for encounters same error. did add .bat on mime types on iis can download .bat files.

sql - I am not able to connect with a local user in a pluggable database(12C) -

i not able connect local user in pluggable database(12c) here relevant code: enter image description here sql> conn sys/sys sysdba connected. sql> alter session set container=pdborcl; session altered. sql> create user user1 identified user1; user created. sql> grant create session,create table user1; grant succeeded. sql> alter user user1 quota unlimited on users; user altered. sql> conn user1/user1 error: ora-01017: invalid username/password; logon denied warning: no longer connected oracle.

why is the first member of the tuple received from kafka using spark direct stream is null -

when reading messages kafka using kafkautils.createdirectstream, v1._1 member of tuple2 null: kafkautils.createdirectstream( streamingcontext, string.class, string.class, stringdecoder.class, stringdecoder.class, kafkaparams, topicsset ).map(new function<tuple2<string,string>, string>() { @override public string call(tuple2<string, string> v1) throws exception { system.out.println(v1._1); return null; } }); while _2 member contains message passed kafka. i have 2 questions: 1) why v1._1 null? 2) there way pass topic name in kafka (the same way message put kafka) v1._1 contain topic name?

c# - Insert into multiple tables using WCF Transactions -

i trying add entry table , use primary key of added entry create additional entry table. the error getting is the transaction manager has disabled support remote/network transactions. (exception hresult: 0x8004d024) i believe caused creating multiple connections within single transactionscope, doing within 1 context / using statement, not believe should receiving error. service [operationbehavior(transactionscoperequired = true)] public void creategroup(newgroupdata data) { var grouprepo = _grouprepo ?? new investigatorgrouprepository(); grouprepo.creategroup(data.userid, data.investigatorgroupname, data.hasgameassignment, data.institutionid); } repository public void creategroup(string userid, string investigatorgroupname, bool hasgameassignment, int institutionid) { using (var context = new gamedbcontext()) { var newgroup = new investigatorgroup() { investigatorgrou...

linux - Get ldap server ip address and port no in centos -

i trying ip address , port number of open ldap server in centos. not find proper documentation it. please me on how ldap server ip address , port number in centos? the ip address of ldap server ip address of host running in. the port number 389 plaintext or 636 ssl.

React Native android build fails without an exception -

i'm trying run simple react native app on android, build keeps on failing. build not giving errors , run-ios works fine. $ react-native run-android js server running. building , installing app on device (cd android && ./gradlew installdebug... not install app on device, read error above details. make sure have android emulator running or device connected , have set android development environment: https://facebook.github.io/react-native/docs/android-setup.html i'm running on osx , trying deploy app on samsung galaxy s6 on adb devices list. tried set android_home variable .bash_profile , update build tools, didn't help. i'd glad if me out one. change gradle version 1.2.3. file android/build.gradle modify line: classpath 'com.android.tools.build:gradle:1.2.3'

c++ - Window Class Registration Failed -

i writing beginnings of game win32 application. worked fine when registered class within main.cpp, i'm trying move game class make code easier me use. since have moved code game class, window class registration fails. here code, please note functions empty because haven't got far yet. getlasterror() returns 87. main.cpp #include "main.h" // entry point program, see game explanation of parameters int winapi winmain(hinstance hinstance, hinstance hprevinstance, lpstr lpcmdline, int ncmdshow) { game = std::unique_ptr<game>(new game(hinstance, hprevinstance, lpcmdline, ncmdshow)); game->init(); // main game loop while(game->isrunning()) { game->handlemessages(); game->update(0.0f); game->render(); } return exit_success; } game.cpp #include "game.h" #include <windows.h> lpcwstr g_szclassname = l"life sim...

java - Why do we need to import a class if the parent already imports it -

say have: import android.os.bundle; import android.app.activity; public class myactivity extends activity { @override public void oncreate(bundle b) { } } and extend class such: public class mynewactivity extends myactivity { @override public void oncreate(bundle b) { } } if don't include import android.os.bundle; mynewactivity class won't compile, should know bundle since parent class imports it. gives? in java, scope of import not class declared, file in import given. so, in different file, must still import need. according jls, section 7.5 , an import declaration makes types or members available simple names within compilation unit contains import declaration. that is, scope of import file within it's located.

terminal - Change a files permission to write -

can tell me how change files permission write access in ubuntu? can't seem work. this files location /usr/local/lib/python3.4/dist-packages/moviepy/video/fx/resize.py thanks to change file permission use chmod command followed value. to change file write access can use chmod 777 /usr/local/lib/python3.4/dist-packages/moviepy/video/fx/resize.py beware make file write-able anyone! more file permissions here https://www.linux.com/learn/understanding-linux-file-permissions

Manipulating JMeter JDBC connection fields in Java/beanshell code -

this followup using jmeter jdbc connection in java code . how use methods such getpassword() or getusername in datasourceelement class? want , modify username , password (among other things) jdbc connection configuration config. i'm using same code in post, in beanshell sampler (which used in preprocessor element). think problem need datasourceelement object , have defined connection object. stuck. my code: import java.sql.connection; import org.apache.jmeter.protocol.jdbc.config.datasourceelement; print("\nbeanshell script beginning"); try { connection con = datasourceelement.getconnection("jdbcconfig"); print(con); string conpasswd = con.getpassword(); print(conpasswd); if(con!=null) con.close(); } catch (throwable ex) { log.error("something went wrong: ", ex); } print("the end"); jmeter.log returns this: error - jmeter.util.beanshellinterpreter: error invoking bsh me...

html - How do I align the 2 stacked elements using the same background image so it looks like one image? -

the header of website's homepage consists of following layout: <header> <div class="navbar-lock"></div> <div class="hero"></div> </header> where div.navbar-lock fixed navigation initial height of 90px, , div.hero contains header text. visually, want give appearance 1 background image (2000px x 481px) spans height , width of both. on scroll, fixed navbar's background top 90px of image; when scroll position @ top of page, header once again appears 1 background image. what i've tried: approach a : header { background: #f60 url(../images/header_bg.jpg) no-repeat 0 0; background-size: cover; } div.navbar-lock { background: #f60 url(../images/header_bg.jpg) no-repeat 0 0; background-size: cover; min-height: 90px; padding-top: 20px; position: fixed; top: 0; z-index: 100; width: 100%; } approach b (crop image 2): div.navbar-lock { background: #f60 url(../images/header_bg.jpg) no-r...

javascript - Disabling aspxgridviews on server-side, how to handle on client-side? -

i've started project our ba guy needs me disable of our aspxgridviews past time. c# public void cutoffdatetime() { //datetime today = datetime.now; // live code datetime today = new datetime(2016, 4, 15, 7, 00, 00); // testing datetime cutoff = new datetime(2016, 4, 19, 7, 00, 00); if (today >= cutoff.adddays(7)) { cutoff = cutoff.adddays(7); } // if today past cutoff, disable grids if (today < cutoff.addhours(-55)) { gvproduction.enabled = false; gvproductionsummary.enabled = false; gvdowntimesummary.enabled = false; gvnonprod.enabled = false; cbcutoff.checked = false; } else cbcutoff.checked = true; } the grids disabled correctly, affects client-side code calls grid.refresh() methods. i've added checkbox invisible control can interface clie...

ios - App freezes when didReceiveChallenge method called -

i attempting connect api using self-signed certificate testing. -(nsdata*)getdatafrompostrequestwithheaders:(nsdictionary*)headers withpostdata:(nsdata*)postdata fromurl:(nsstring*)urlstring { __block nsdata* responsedata; nslog(@"url %@", urlstring); nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:[nsurl urlwithstring:urlstring] cachepolicy:nsurlrequestuseprotocolcachepolicy timeoutinterval:10.0]; [request sethttpmethod:@"post"]; [request sethttpbody:postdata]; [request setallhttpheaderfields:headers]; nsurlsessionconfiguration *config = [nsurlsessionconfiguration defaultsessionconfiguration]; // [config sethttpadditionalheaders:headers]; nsurlsession *session = [nsurlsession sessionwithconfiguration:config delegate:self delegatequeue:nil]; nslog(@"%@", @"nsurlse...

java - RecyclerView scrolling makes changes -

i have recyclerview has custom adapter inflates rowlayout. each row contains cardview , in text , images buttons. in particular have "like" button( imageview ) supposed change imageresource on click. i able set onclicklistener in onbindviewholder() method , indeed register when click button, not changes buttons image changes of other buttons , when scroll down , again first button reset. here adapter code. public class myadapter extends recyclerview.adapter<myadapter.viewholder> implements view.onclicklistener { private arraylist<wallpost> wallposts; @override public void onclick(view v) { } public static class viewholder extends recyclerview.viewholder { public view view; public viewholder(view v) { super(v); view = v; } } public myadapter(arraylist<wallpost> wallposts) { this.wallposts = wallposts; } @override public myadapter.viewholder oncreatevi...

operating system - How to Convert NSURL to CFURLRef -

apple gives sample code creating pdf document. uses cfurlref nspanel savepanel gives nsurl. i can't convert nsurl cfurlref path = cfstringcreatewithcstring (null, filename, kcfstringencodingutf8); url = cfurlcreatewithfilesystempath (null, path, kcfurlposixpathstyle, 0); nslog(@"cfurlref %@",url); output is 2016-04-22 00:34:26.648 xxx analysis[12242:813106] cfurlref analysisreport.pdf -- file:///users/xxxxxx/library/containers/com.xxxxxx.xxxnalysis/data/ convert code find url = (__bridge cfurlref)thefile; nslog(@"nsurl %@",url); output 2016-04-22 00:37:20.494 xxx analysis[12325:816505] nsurl file:///users/xxxxxx/documents/xxxnalysis.pdf at end pdf file saved program crash when nspanel closed. cfurlref , nsurl toll-free bridged. typically, this: nsurl *url = ...; cfurlref cfurl = cfbridgingretain(url); and when no longer need cfurl object: cfrelease(cfurl); or if you're reasonably nsurl stick around long enou...

google bigquery - Different Aliases produce different Result for exactly same Query -

Image
below 2 versions of same query version 1 (uses k alias in inner select): select k, 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, 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 don't have problem understanding why or result generated (it relatively trivial) - - expected result same no matter alias used - alias @ all! ...

Visual studio code extension: How can I add error markers to files in the explorer? -

i have written validator vscode extension, uses diagnosticcollection set errors files. works , errors shown when file opened. i mark files in explorer, easy find files errors. here example of how looks in eclipse. possible in vscode extension? there extension doing this? unfortunately, can't that. there open issue asking related git, not open want. maybe using api described in this issue create new panel marked files. it still experimental, btw...

Android - Fatal Signal 11 when stopping and resetting camera after recording video -

i have app trying record video, following method initialize camera: private void initrecorder(surface surface) throws ioexception { if (mcamera == null) { mcamera = camera.open(); mcamera.unlock(); } if (mmediarecorder == null) mmediarecorder = new mediarecorder(); mmediarecorder.setpreviewdisplay(surface); mmediarecorder.setcamera(mcamera); mmediarecorder.setvideosource(mediarecorder.videosource.default); mmediarecorder.setoutputformat(mediarecorder.outputformat.mpeg_4); mmediarecorder.setvideoencoder(mediarecorder.videoencoder.h264); mmediarecorder.setvideoencodingbitrate(512 * 1000); mmediarecorder.setvideoframerate(30); mmediarecorder.setvideosize(640, 480); mmediarecorder.setoutputfile(videofile); try { mmediarecorder.prepare(); } catch (illegalstateexception e) { e.printstacktrace(); } initsuccess = true; } when try stop camera or when surfacedestroyed called, call followi...

cassandra - How to make the query to work? -

i have cassandra version 2.0, , in totally new in it, question... have table t1 , columns names: 1,2,3...14 (for simplicity); partitioning key column 1 , 2 ; clustering key column 3 , 1 , 5 ; need perform following query: select 1,2,7 t1 2='a'; column 2 flag, values repeating. following error: unable execute cql query: partitioning column 2 cannot restricted because preceding column 1 either not restricted or restricted non-eq relation so right way it? need data filtered. thanks. so, make sure understand schema, have defined table t1 : create table t1 ( 1 int, 2 int, 3 int, ... 14 int, primary ((1, 2), 3, 1, 5) ); correct? if case, cassandra cannot find data answer cql query: select 1,2,7 t1 2 = 'a'; because query has not provided value column "1", without cassandra cannot compute partition key (which requires, per composite primary key definition, both columns "1" and "2"), , without that...

c# - How to get tablet's IMEI number? -

this not winrt application. it's standard wpf. device behaves normal windows pc, has windows 10 installed. has 3g broadband modem , sim card slot. some more information helpful. example brand , connection type (usb/internal). if understood correctly looking solution programmatically (in wpf) collect information (imei) connected modems (in general or 1 specific?) depending on device have several options. option 1 wmi: depending if manufacturer included information might successful simple wmi query. to verify take @ device manager (start -> run -> devmgmt.msc) right click on modem -> properties go register "details". scroll through properties , imei (the property doesn't named imei). if find there, can use wmi query information wpf program. example here: http://www.codeproject.com/questions/448125/how-to-write-wmi-query-to-find-usb-modems-in-cshar option 2 @ commands: if able communicate modem on serial connection can use called ...

jquery - add class to element which grandgrandparent has no "display:none" style -

using jquery want add class select element if grandgrandparent hasn't style="display:none" atribute html this( here don't want add class ): <div style"display:none"> <div> <div> <select></select> </div> </div> </div> and here want add class select element: <div> <div> <div> <select></select> </div> </div> </div> is there possibility that? first add missing equal sign : style="display:none" then can : $('select').addclass(function() { return $(this).parents().eq(2).is(':visible') ? 'myclass' : ''; }); fiddle

python - Django numeric comparison of hstore or json data? -

is possible filter queryset casting hstore value int or float ? i've run issue need add more robust queries existing data model. data model uses hstorefield store majority of building data, , need able query/filter against them, , of values need treated numeric values. however, since values treated strings, they're compared character character , results in incorrect queries. example, '700' > '1000' . so if want query items sqft value between 700 , 1000, 0 results, though can plainly see there hundreds of items values within range. if query items sqft value >= 700, results sqft value starts 7, 8 or 9. i tried testing using jsonfield django-pgjson (since we're not yet on django 1.9), appears have same issue. setup django==1.8.9 django-pgjson==0.3.1 (for jsonfield functionality) postgres==9.4.7 models.py from django.contrib.postgres.fields import hstorefield django.db import models class building (models.model): address1 = mo...

javascript - Provide default value to getter without causing stack overflow in Angular 2 Model Class -

so i'm trying find way provide fallback behavior getter on class in javascript. idea provide modified version of property (title) if property being accessed set null @ creation time. trouble i'm facing recursive call when getting subtitle property because it's accessing itself. rename _subtitle, typescript you'd have modify interface , provide throwaway temporary value _subtitle in addition subtitle, breaks semantics of interface. export interface ifoo { title: string; subtitle?: string; } export class foo implements ifoo { public title: string; public set subtitle(val) { this.subtitle = val; } public subtitle() { return this.subtitle ? this.subtitle : this.title.split('//')[0]; }; constructor(obj?: any) { this.title = obj && obj.title || null; } so ended realizing shortly after can use private property serve 'temporary' storage location without breaking semantics or contract of interface. so, few sim...

python - Error with a pygame project very early into it -

basically have far , appear there wrong computer or py.game. here code far: import pygame pygame.init() gamedisplay = pygame.display.set_mode((1280,720)) pygame.display.set_caption('python platformer') python_char = pygame.image.load('python_char') when run in python launcher 2 errors. 20:52:53.731 warning: 140: application, or library uses, using deprecated carbon component manager hosting audio units. support removed in future release. also, makes host incompatible version 3 audio units. please transition api's in audiocomponent.h. line 8, in python_char = pygame.image.load('python_char') i left out directory because dont see them being of if needed can add them in. the code entered here has 1 issue me. make sure have right version of pygame installed corresponds python version. second error, change ('python_char') supported image file. example: python_char=pygame.image.load('snake.png') but re...

android - How do I create a URL to query Google places with the CID -

i have app searches google places api , returns places based on categories choose. the result json object contains lot of data each place. want share place via email other people. extract information want object specified place using following code: jsonobject geometry = (jsonobject) point.get("geometry"); jsonobject location = (jsonobject) geometry.get("location"); result.setlatitude((double) location.get("lat")); result.setlongitude((double) location.get("lng")); result.seticon(point.getstring("icon")); result.setname(point.getstring("name")); result.setvicinity(point.getstring("vicinity")); result.setid(point.getstring("place_id")); return result; the place_id cid of place, unique place. want share this, or able show place going google maps , search unique cid. construct web browser url follows: http://maps.google.com/maps/place?cid=chijgzzejr9_24arnu3loimy7k4 this doesn...

checkstyle - prohibit initializing object of type -

suppose have external library class called foo. can't change foo have private constructor, have foofactory class wrote. so have foofactory.getafoo() want checkstyle catch new foo() in rest of code, force using factory. i have this: <module name="illegaltokentext"> <property name="tokens" value="literal_new"/> <property name="format" value="foo"/> </module> but doesn't seem detect new foo() . i use regex cleaner. i had similar problem preventing extending class: <module name="illegaltokentext"> <property name="tokens" value="extends_clause"/> <property name="format" value="androidtestcase"/> </module> neither of these checkstyle module seem @ all. what doing wrong? illegaltokentext checks illegal text on token itself, not on subsequent ident tokens or such. why seems nothing in case...

ruby on rails - How should a form error page be rendered with Turbolinks 5 -

using new turbolinks 5 in rails application - best way render form error messages. documentation says: instead of submitting forms normally, submit them xhr. in response xhr submit on server, return javascript performs turbolinks.visit evaluated browser. so if form submits remote request update should doing js form replace or turbolinks 5 have better way? example - controller: def update @success = @team.update_attributes( team_params ) end update.js <% if @success %> turbolinks.visit('<%= teams_path %>', {action: 'replace'}); <% else %> $('form').replacewith('<%= j(render partial: '/teams/form') %>'); <% end %> is there more turbolinks 5 way handle failed update? i'm still tinkering around well. thing i'd doing differently put conditional logic in controller instead of view. somethings_controller.rb def create if @something.save redirect_to @something else ...

PHP: How to properly copy a primitive to a new memory address -

i had issue ( php: variable value mysteriously set 0 ) variable being passed value php function, , somehow value of variable changed, so: $var = 'hello'; some_function($var); echo $var; // outputs 0 it hypothesized it's old function written in c , in innards doing corrupt variable, since in c apparently can kind of thing. anyway, tried copy value first , pass in, so: $var = 'hello'; $var2 = $var; some_function($var2); echo $var; // still outputs 0 of course didn't help, because, reading here php pointing $var2 in symbol table same zval container $var , increasing zval container's refcount. of course, if $var2 reassigned "by value", new zval container should created it, not regular assign-by-value, apparently (there's bit in previous question __set() magic method thing). presumed happening physical memory address @ value stored, rather assignment happening through normal php machinery, , pointing zval affected. well. my worka...

hadoop - what difference of managed and unmanaged hconnection in hbase? -

when tried create htable instance in way. configuration conf = hbaseconfiguration.create(); hconnection conn = hconnectionmanager.getconnection(conf); conn.gettable("table_name"); then got exception. @override public htableinterface gettable(tablename tablename, executorservice pool) throws ioexception { if (managed) { throw new ioexception("the connection has unmanaged."); } return new htable(tablename, this, pool); } so , wants know concrete reflection of managed , 'unmanaged' hconnection? before call hconnectionmanager.getconnection have create connection using hconnectionmanager.createconnection passing earlier created hbaseconfiguration instance. hconnectionmanager.getconnection return connection exists. bit of hconnectionmanager javadoc how handle connection pool: this class has static map of hconnection instances keyed by configuration; invocations of getconnection(configuration)...

javascript - jQuery won't load external html template using .load() -

i'm attempting use jquery change main content area of homepage when nav link clicked. i'm using .load() this, external html page i'm referencing won't load (nothing happens). custom.js $(document).ready(function(){ $("#about").click(function(event){ event.preventdefault(); $(".main-content").fadetoggle("slow", function(){ $(this).load("about-us.html") }); }); }); index.html <div class="inner cover main-content"> <h1 class="cover-heading">a heading</h1> <p class="lead">this best page of time.</p> </div> figured i'd answer own question since took hours figure out trivial. if you're loading jquery locally, must run file using local web server mamp rather "clicking" on (e.g. loading file in browser). jquery won't load external files if aren't served kind of web server. if check console...

idris - Data Type Encompassing Two Sum Types? -

given these 2 sum types: data foo = int | b string data bar = c int | d string i'd define function returns either (foo or bar) string . so, attempted make: data higher = foo | bar but failed compile: *adt> :r type checking ./adt.idr adt.idr:3:6:main.foo defined adt.idr:4:6:main.bar defined how can create higher data type, consists of foo or bar ? yes can indeed! data foo = int | b string data bar = c int | d string data higher : type injfoo : foo -> higher injbar : bar -> higher now can injfoo (b "hello") or injbar (c 5) .

do get() and getline() in c++ treat newline differently? -

ifstream fin; ofstream fout; char ch; string st; fin.open("testfile.txt"); fout.open("testfile.txt"); while(!fin.eof()) { fin.get(ch); cout << ch; } fin.clear(); fin.seekg(ios::beg); while(!fin.eof()) { getline(fin, st); cout << st; } test file contains following: abcd efg 1234 hij result: abcd efg 1234 hijabcd efg1234 hij what asking is: why results different between reading fin.get(ch) , getline(fin, st)? get() returns every character. getline() throws away line terminator.

java - @Message annotation doesn't work when I run atmosphere-chat-multiroom of atmosphere-samples -

Image
i've searched issue long while no solution comes me. here code (i've added system.out.println phrases). web.xml <display-name>atmosphere chat</display-name> <servlet> <description>atmosphereservlet</description> <servlet-name>atmosphereservlet</servlet-name> <servlet-class>org.atmosphere.cpr.atmosphereservlet</servlet-class> <load-on-startup>0</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>atmosphereservlet</servlet-name> <url-pattern>/chat/*</url-pattern> </servlet-mapping> chatroom.java @managedservice(path = "/chat/{room}") public class chatroom { private final concurrenthashmap<string, string> users = new concurrenthashmap<string, string>(); private final static string chat = "/chat/"; @pathparam("room") ...

osx - Python can't install with pyenv in mac -

$ brew install pyenv-virtualenv and append following .bash_profile. export pyenv_root="$home/.pyenv" export path="$pyenv_root/bin:$path" eval "$(pyenv init -)" $ source ~/.bash_profile and install python. $ pyenv install 2.7.11 then error occured. zipimport.zipimporterror: can't decompress data; zlib not available how solve? all have following command. $ xcode-select --install

excel - Conditional Min/Max -

using excel 2010, how calculate min or max column a, when needs take value of column b consideration? so table looks this amt spent quintile 545,40 q1 2146,41 q1 753,66 q2 821,11 q2 2157,99 q3 718,06 q3 526,58 q4 1047,50 q4 2009,30 q5 824,99 q5 to maximum quintile "q1" : =aggregate(14, 6, a:a*(b:b="q1"), 1) to minimum quintile "q1" : =aggregate(15, 6, a:a/(b:b="q1"), 1) you can place cell reference in place of hard-coded constant "q1" . i.e. =aggregate(14, 6, a:a *(b:b=b2), 1)

swift - How to check if string contains a certain character? -

i've been trying find can't. have code: func ayylmao(vorno: string){ if (vorno.(whatever function finding string goes here)("a", "e", "i", "o", "u")) { print("input includes vowels") } } but right @ if statement can't find check if characters in string. like this: let s = "hello" let ok = s.characters.contains {"aeiou".characters.contains($0)} // true

android - How to get heart rate from fitbit charge HR used BLE -

i purchased heart rate fitbit charge hr , want implement app information heart rate. tried read sensor through example uses bluetooth low energy (link: https://developer.android.com/guide/topics/connectivity/bluetooth-le.html ). able connect devices not information measure heart rate. have refer https://dev.fitbit.com api same , generate consumer key , consumer secret. seems web application only. want fitbit android bluetooth api data fitbit android apps on bluetooth. please me. the charge hr has no support rebroadcasting hr on standard btle profile want able collect data way live. chance if have private api surprised if have live data. recorded data yes live data no. 'can re-broadcast heart rate data' line interested in in dc rainmaker product comparison chart. http://www.dcrainmaker.com/2015/02/fitbit-charge-review.html the live rebroadcast feature rare there devices it, more ant+ though btle.

python - Creating database file one directory above current -

in php, refer higher directory use '../../test'; how in python? in case, i'm using sqlite create database file. import sqlite3 conn = sqlite3.connect('../data/test.db') however; says 'unable open database file' i'm considering directory access error. how refer higher directory in python? you might try this: conn = sqlite3.connect(os.path.realpath('../data/test.db'))