Posts

Showing posts from June, 2013

ruby on rails Errno::EACCES Permission denied @ rb_sysopen - product.log -

def show name = @product.productname file.open('product.log', 'a+') |f2| f2.write time.new f2.write "==>" end it works fine on local machine (mac) , error comes when deploy on ubuntu server (ec2 ) try file.open("#{rails.root}/product.log", 'a+') |f2| if @ root, or whatever path is. if still doesn't work try changing permission 775.

javascript - Json stringify in JS and decoding in php -

js var sim_list=[]; var simvalue = $('input[name="simnamecbx"]:checked').each(function(){ var sim_name=this.value.split(" ")[0]; console.log("simname:",sim_name); sim_list.push({ sim_name }); ); console.log(sim_list); var simulation_list = json.stringify(sim_list); $.ajax({ url: 'addprogram.php', data: {addpgmname:addprogname, addpgmcomp:addprogcomp, addpgmdate:addprogdate, simselvalue:simulation_list}, type: 'post', datatype: 'json', success: function(output){ var = output; console.log(a); } }); php $simvalue = json_decode($_post["simselvalue"],true); foreach($simvalue $key => $value) { print_r($value); } question when execute above php values array ( [0] => array ( [sim_name] => 12 ) [1] => array ( [sim_name] => 13 ) [2] => array ...

c++ - ORA-00904: "E_MAIL": invalid identifier -

i using mvc architecture.i trying update record in table taking customer id input. data taken input in viewcustomer.cpp class method returning object of type customer passed function in modelcustomer.pc via controlcustomer.cpp(controller) following function of modelcustomer.pc void modelcustomer::dbupdatecustomerdetail(customer &c) { id=c.getid(); ph=c.getid(); string memberfname=c.getfname(); string memberlname=c.getlname(); string memberstreet=c.getstreet(); string membercity=c.getcity(); string memberstate=c.getstate(); string memberemail=c.getemail(); fn=new char[memberfname.length()+1]; ln=new char[memberlname.length()+1]; street=new char[memberstreet.length()+1]; city=new char[membercity.length()+1]; state=new char[memberstate.length()+1]; e_mail=new char[memberemail.length()+1]; strcpy(fn,memberfname.c_str()); strcpy(ln,memberlname.c_str()); strcpy(street,memberstreet.c_str()); strcpy(city,membercity.c_str()); strcpy(state,memberstate.c_str()); strcpy(e_mail,memberema...

jquery - Javascript script loading order - function undefined -

Image
i working within not nice template has forced me load scripts in js can not control there order. trying load library when attempt call it, undefined error. $.getscript( "js/velocity.min.js").done(function(){ $('body').velocity({ width: 200}) }); get error: uncaught typeerror: $(...).velocity not function how can be? loaded you! ok there conflict script has loaded, fix wrapper velocity code in closure , set 'define' null within it. (function($){ var define = null; //then velocity code here })(jquery) be sure loading zepto/jquery before velocity.js <script type='text/javascript' src='js/zepto.min.js'></script> <script type="text/javascript" src="js/velocity.min.js"></script>

html - Button inside section element is rendered much larger -

Image
there ordered list , button inside section element. both elements, list , button placed inside section element place them in single row. browser makes button larger match list's size. how avoid it? also, button's float: right property not floating button right end. html code above image is, <section> <ol id="reports"><h3>reports</h3> <li>test_12345</li> <li>test_1405114424964</li></ol> <button style="float:right;">execute test </button></section> css properties are, section { display: flex; } button{ clear: left; background-color:#699db6; border-color:rgba(0,0,0,0.3); padding: 10px 30px; border-radius: 5px; float: right; } jsfiddle it depends of you're want achieve, if it's floating list left, , button right, need start using couple more of flex properties. possibly go here: html: <section> <ol id=...

angularjs - Tinymce's source code textarea is not editable -

i using ui-tinymce ( https://github.com/angular-ui/ui-tinymce ) 1 of projects. working demo (there isn't documentation directive). in general working fine except source code editor. in case wysiwyg opening within modal (also angular: http://angular-ui.github.io/bootstrap/#/modal ). implementation of source code in timymce opening modal. not problem, in case textarea of source code not editable. if force close the first modal, source code becomes aditable. at point, not sure dig. thing can see source code textarea have event attached (not sure if should). i appreciate in direction.

android - Excluding ARMv5 and ARMv6 devices from Google Play -

i build ffmpeg based library project , outputs huge. ok remove support of old arm processors , leave arm-v7 , x86 libraries? i suspect arm-v7 won't work on older arm processors. the application min sdk 4.0.3 , question whether percentage of devices old arm small can filter them out on google play?

python - Calling scikit-learn functions from C++ -

is there way call scikit-learn's functions c++? have rest of code in c++ opencv. able use classifiers scikit-learn provides. far understand, there's no easy way - need use boost::python or swig. came across project ( https://github.com/spillai/numpy-opencv-converter ) shows interop between numpy arrays <==> cv::mat objects, know how use call c++ code python script, not other way around. you can in pretty straightforward way, including python headers , calling python script and/or scikit methods via py* wrappers. see https://docs.python.org/2/extending/embedding.html#pure-embedding thorough example.

python - numpy how find local minimum in neighborhood on 1darray -

i've got list of sorted samples. they're sorted sample time, each sample taken 1 second after previous one. i'd find minimum value in neighborhood of specified size. for example, given neighborhood size of 2 , following sample size: samples = [ 5, 12.3, 12.3, 7, 2, 6, 9, 10, 5, 9, 17, 2 ] i'd expect following output: [5, 2, 5, 2] best way achieve in numpy / scipy edited: explained reasoning behind min values: 5 - 2 number window next [12.3 12.3]. 5 smaller 2 - left [12.3, 7] right [6 9]. 2 min 5 - left [9 10] right [9 17]. 5 min notice 9 isn't min there's 2 window left , right smaller value (2) use scipy's argrelextrema : >>> import numpy np >>> scipy.signal import argrelextrema >>> data = np.array([ 5, 12.3, 12.3, 7, 2, 6, 9, 10, 5, 9, 17, 2 ]) >>> radius = 2 # number of elements left , right compare >>> argrelextrema(data, np.less, order=radius) (array([4, 8]),) which suggest nu...

mysql - Extract rows using select query -

i have 2 queries shown below. select * `nhrd_members` b membership_number 'a%' , `member_fromdate` >= '2014-01-01' , `member_fromdate` <= '2015-01-01' which yields 98 rows.. select * `nhrd_members` membership_number 'a%' , `member_fromdate` >= '2014-01-01' , `member_fromdate` <= '2014-05-14' which yields 19 rows. as can see extracting data same table. actual result need 98-19 i.e 79 rows. i need exclude rows of query 2 query 1. , 81 records. appreciated. select * `nhrd_members` b membership_number 'a%' , ( `member_fromdate` >= '2014-01-01' , `member_fromdate` <= '2015-01-01' ) , not ( `member_fromdate` >= '2014-01-01' , `member_fromdate` <= '2014-05-14' ) that can simplified as: select * `nhrd_members` b membership_number 'a%' , ( `member_fromdate` > '2014-05-14' , `member_fromd...

java - Apply regex on captured group -

i'm new java , regex in particular have csv file : col1,col2,clo3,col4 word1,date1,date2,port1,port2,....some amount of port word2,date3,date4, .... what iterate on each line (i suppose i'll simple loop) , ports back. guess need fetch every thing after 2 dates , ,(\d+),? , group comes back my question(s) : 1) can done 1 expression? (meaning, without storing result in string , apply regex) 2) can maybe incorporate iteration on lines regex? yes, can done in 1 line: first remove non-port terms (those containing non-digit) then split result of step 1 on commas here's magic line: string[] ports = line.replaceall("(^|(?<=,))[^,]*[^,\\d][^,]*(,|$)", "").split(","); the regex says "any term has non-digit" "term" series of characters between start-of-input/comma , comma/end-of-input. conveniently, split() method doesn't return trailing blank terms, no need worry trailing commas left aft...

javascript - textarea content inside a .txt file but keep line-breaks -

i have piece of code saves value of textarea local text file. seems work fine don't want lose line breaks. code & fiddle: html <textarea id="textbox">type here</textarea> <button id="create">create file</button> <a download="info.txt" id="downloadlink" style="display:none">download</a> js (function () { var textfile = null, maketextfile = function (text) { var data = new blob([text], {type: 'text/plain'}); // if replacing generated file need // manually revoke object url avoid memory leaks. if (textfile !== null) { window.url.revokeobjecturl(textfile); } textfile = window.url.createobjecturl(data); return textfile; }; var create = document.getelementbyid('create'), textbox = document.getelementbyid('textbox'); create.addeventlistener('click', function () { var l...

sql server - visual studio version for XP users support ssis -

which latest visual studio version windows xp supports sql server integration services run ssis projects? thanks visual studio 2010 latest version supports xp, have use have computer running vista or later install sql 2012 server though. if want run on xp machine must use visual studio 2008. strongly recommend upgrading computer windows 7 or later security , simplicity reasons.

bash - Find & delete folder (ubuntu server) -

i have backup system in ubuntu server every day makes database backup , save in folder named day: $(date +%d%m%y) on script, when try find , delete folders last week, command don't find directory. im trying with: find -name $(date +%d%m%y) -type d -mtime +7 -exec rm -r {}; , never find directory. y tryed changing -mtime time 1 day or 2, dont find nothing. i think made small mistake: when backup on 7th of may, create folder name 070515. when search week later, folder name 140515 modified more 7 days ago. however, folder has been created today. you may not need name of folder, use find /backup/path -type d -mtime +7 to find folders older 7 days.

twitter bootstrap - Not able to upload file when using boostrap -

i new bootstrap framework. created small web page upload files. submit button working fine, file not getting uploaded. <html> <head> <!-- latest compiled , minified css --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> <!-- optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <!-- latest compiled , minified javascript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="row clearfix"> <div class="col-md-4 column"> <h1 class="text-left text...

java - Custom exception handle with spring boot -

here,my requirement want separate code in application exception handling,i saw nice option of spring there using @controller advice handle exceptions globally. @controlleradvice class globalcontrollerexceptionhandler { @responsestatus(httpstatus.conflict) // 409 @exceptionhandler(dataintegrityviolationexception.class) public void handleconflict() { // nothing } } but there want cutomization there,like proper dynamic messages,own error code. how can this,i new spring boot , don't have knowledge of spring.need basic example. you can come class capture information sent in response in case of exception:- public class apiresponse { int errorcode; string description; string someinformation; // other information want send in case of exception. } @controlleradvice class globalcontrollerexceptionhandler { @responsestatus(httpstatus.conflict) // 409 @responsebody @exceptionhandler(dataintegrityviolationexceptio...

javascript - Duplicate records are displayed while trying to bind different data to the same div using knockout js -

i have div displays 10 records time.when user clicks on next link, next 10 records loaded server. after binding, newly added records shown multiple times. kindly me know going wrong. function displaylastmonthvolume() { $.ajax({ type: "post", url: "dashboard.aspx/getlastmonthvolume", contenttype: "application/json; charset=utf-8", datatype: "json", success: function (response) { if (response != undefined && response != '') { var data = json.parse(response.d); var totalamt = 0; (var p = 0; p < data.length; p++) { totalamt += data[p].amount; } data.totalamt = totalamt; ko.cleann...

javascript - Google Maps cannot Load Properly due to CSS Tabs -

http://www.bchomescondos.ca/properties/?city=richmond&id=261681248 http://www.bchomescondos.ca/properties/?city=richmond&id=261704393 above sample links issue arising. actual issue google map street view not appearing when street view tab clicked. @ first thought issue map script later found out (from of thread in stackoverflow) problem css tabs , how loaded. somehow when roadmap tab active streetview not appearing , when streetview tab active roadmap appearing distorted. told me have load tabs during page load simultaneously , hide tabs don't want appear initially. guess needs knowledge of js or jquery, don't have. so, obliged if can me in this. have used simple gumby framework create tabs. code , links follows. <div class="row"> <div class="one columns"></div> <section class="ten columns tabs" style="margin: 20px 0;"> <ul class="tab-nav"> ...

jQuery Mobile + FullCalendar - need to refresh page to see it with multiple page divs -

please see jsbin test page illustrates issue i have simple jqm page 2 page divs. initialization being done inside $(document).on('pageshow', function(){}); block. inside block, initialize fullcalendar.js calendar. if load page external page (the first link in menu) loads without hitch (but it's not using ajax, page flickers , there's no transition). if load page using jqm convention of linking id of second page div anchor tag, loads calendar div page no data. if refresh page, data displayed. subsequent use of menu displays both page divs pages without issue. i've seen lot of discussion event of pagecontainer widget use, , i'm aware document.ready() not way go. i've tried possibilities, think (pagebeforeshow, pageshow, pageinit, etc.) there's more detail in demo, can see code. if need post here, too, can that, it's easier see issue if load test @ jsbin. suggest running in separate window, can refresh page. if else has solved or has ide...

python - What is the name of the page element that reads "+ Add telephone" on the Google Hangouts start page? -

i'm looking name of page element reads " + add telephone " on google hangouts start page , purpose of plugging selenium python api's webdriver.firefox().find_element_by_name() command. alternatively, element id work, know there find_element_by_id() command. that element not have name. go xpath contains function , use find_element_by_xpath //div[contains(text(),'add telephone')] however, it's idea not use google kind of testing. that's kind of trap. specially selenium

postgresql - Is it possible to truncate the pg_largeobject table in postgres? -

i discard contents of pg_largeobject table , reclaim disk space. when try issuing command: truncate pg_largeobject i response: error: permission denied: "pg_largeobject" system catalog this though issuing command user postgres (a superuser). there insufficient disk space vacuum full while table contains lot of rows. i've tried deleting rows in preparation vacuum full , still going after whole day, , ended being interrupted. i'd prefer truncate if @ possible. is truncation of table possible? contains around 1 tb of images no longer want. i've removed references table other tables (and deleted rows pg_largeobject_metadata ). turning on allow_system_table_mods answer. truncate took few minutes. nick barnes suggestion , old article confirmed approach.

javascript - Replacing content on click of a dynamically created button and an AJAX call -

i have dynamically created menu buttons when clicked fire ajax call php script, on success returned data displayed within specific div using $("#imageframe").append(...) . of buttons in menu created same way , have same function appending data 1 div . the issue have emptying div before appending new content. i have tried .empty() - .html('') - .empty().append(<html code>) - .replacewith() . have put these before ajax post , within success callback. best have achieved far emptying div, it's if once empty command run , successful script goes no further. the click ajax function <script type="text/javascript"> $(document).ready(function() {//ready func $(".albumname").click(function(){//click var albumid = this.id; $.post("includes/viewgallery.php",{albumid:albumid},function(data) {//json console.log(data); data = jquery.parsejson(data); $.each(data, function(key, val...

java - forward request from servlet to jsp after login using tomcat -

i'm trying forward request jsp file after login using tomacat. (servlet) not forwarding request. can figure out error here ? servlet : public class authenticationserver extends httpservlet { public void dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { doservice(request, response); } public void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { doservice (request, response); } public void doservice (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { string user = request.getremoteuser(); request.setattribute("user", user); requestdispatcher dispatcher = request.getrequestdispatcher("/" + request.getparameter("direct")); dispatcher.forward(request, response); } } when printed "/" + request.getparameter(...

c - Confused about this while statement -

i wrote program class , can't seem while loop work.. don't know wrong, it's small error know make tons of... thanks! ps i'm new stuff easy on me if small :p #include <stdio.h> #define stack_size 10 #define true 1 #define false 0 #define maxnum 5 /*************** prototypes ***************/ void make_empty(int *top); int is_full(int *top); int push(int content[], int maxnum, int newnum, int *top); int pop(int contents[], int maxmun, int *top); void printstack(int contents[], int maxnum, int *top); int is_empty(int *top); int search(const int content[], int maxnum, int num); // main function int main(void) { int popnum = 0; int foundindex = -1; int i; int contents[stack_size] = { 0 }; int top = 0; int input = 0; while (! == 0) { printf("/n/npick number 1 5, type number press enter: "); switch (input) { case 1: push(contents, maxnum, popnum, &top); break; ...

What would the ruby equivalent be to this python script? -

print ("{0:5s} {1:7s} {2:9s} {3:6s} {4:25s} {5:s}".format('rank', 'points', 'comments', 'hours', 'sub', 'link')) ent in results: print ("{0:5s} {1:7s} {2:9s} {3:6s} {4:25s} {5:s}".format(str(ent[0]), str(ent[1]), str(ent[2]), str(round(ent[3], 2)), str(ent[4]), str(ent[5]))) it printing outputs array rows. how can mirror in ruby? python: print ("{0:5s} {1:7s} {2:9s} {3:6s} {4:25s} {5:s}".format('rank', 'points', 'comments', 'hours', 'sub', 'link')) ruby: puts "%-5s %-7s %-9s %-6s %-25s %-5s" % ['rank', 'points', 'comments', 'hours', 'sub', 'link'] alternatively: puts sprintf("%-5s %-7s %-9s %-6s %-25s %-5s", *['rank', 'points', 'comments', 'hours', 'sub', 'link'])

javascript - Execute route if only the local Angular App calls it true the controller -

i have few api routes app ( controller.js ) should have access to. there way use ip address (possibly insecure because of spoofing) create restriction of uses part of api? server size (server.js) app.get("/api/specs",function(req,res){ // app should have access it, not external entities res.json({used:getused()}); }); client side (controller.js) $http.get('/api/specs').success(function(specs,code){ console.log(specs); }); by default browser doesn't allow make cross-site http requests because subject of same origin policy . note: in particular, meant web application using xmlhttprequest make http requests domain loaded from, , not other domains. which means in case js in same domain of api can have access them. what if want extend use of api other domains? well in case have setup in backend api access-control-allow-origin header. some eg: // cross-site http requests http://sitea.com access-control-allow-ori...

angularjs - How angular promise .then works -

i new angularjs $q , promise, learn if use $http.get() , can promise , can use .then function chainly like $http.get(url) .then(function(data){}, function(err){}) .then(function(data){}, function(err){}) ..... each return new promise, question how know has been resolved? 1 thing notice if add return function(data){} , next function can return value previous function, mean need give return resolve? how know has been resolved? as noticed, promise returned then() resolved after callback executed (which executed when first promise fulfilled). , resolve result callback indeed. do need give return resolve? no, if don't return callback, result undefined - regular function calls. however, in fact have more options build result in callback returning plain value: you can return promise. promise returned then() adopt it, i.e. fulfills result or reject reason settles. you can throw exception. automatically caught , resulting promise re...

javascript - div not showing after setting display='block'; -

it works div not hidden, start off display set none. html <div class="container-fluid"> <div class="row"> <button class ="col-md-6" ng-click="showassessments()">product groups</button> <button class="col-md-6" ng-click="showskills()">skills</button> </div> </div> <ng-include src="detailstemplate"></ng-include> <ng-include src="skillstemplate" style="display:none"></ng-include> </div> html of detailstemplate (these partial views) <form ng-submit="submit()" name="assessmentform" id="assessmentform"> <!-- todo: don't use table layout --> <table class="table table-striped table-bordered" assessment-input-tabber> //...... </table> </form> html of skillstemplate <form ng-submit="submit()...

.net - How to convert to double with 2 precision - string after dot? -

i want convert string: 0.55000000000000004 double: 0.55 . how that? is string or double? if string: double d = double.parse(s,cultureinfo.invariantculture); string s=string.format("{0:0.00}",d); if double format using second line.

iOS Swift - UIImageView can't set ContentMode -

i'm using cifilter add filter image. resulted image after filtering image has size: cgrectmake(10, 10, 70, 70) . can't set resulted image content mode scaleaspectfill . here code: filter2image.frame = cgrectmake(90, 10, 70, 70) let filter2data = cifilter(name: "ciphotoeffectchrome") filter2data.setvalue(ciimage(image: imageview.image), forkey: kciinputimagekey) self.filter2image.image = uiimage(ciimage: filter2data.outputimage) filter2image.contentmode = uiviewcontentmode.scaleaspectfill try changing frame after set contentmode. this: let filter2data = cifilter(name: "ciphotoeffectchrome") filter2data.setvalue(ciimage(image: imageview.image), forkey: kciinputimagekey) self.filter2image.image = uiimage(ciimage: filter2data.outputimage) filter2image.contentmode = uiviewcontentmode.scaleaspectfill filter2image.frame = cgrectmake(90, 10, 70, 70)

python 3.x - Is this intended behavior or a bug in datetime timedelta? -

from datetime import datetime timedelta import pytz ppt = pytz.timezone('us/pacific') first = ppt.localize(datetime(2013, 3, 10, 0, 0, 0)) first+=timedelta(hours=2) first returns datetime.datetime(2013, 3, 10, 2, 0, tzinfo=<dsttzinfo 'us/pacific' pst-1 day, 16:00:00 std>) it should return datetime.datetime(2013, 3, 10, 3, 0, tzinfo=<dsttzinfo 'us/pacific' pdt-1 day, 17:00:00 dst>) you can workaround this, apparent, bug doing astimezone(ppt) after adding hours. so, bug? doing wrong? or intended have code refresh after adding time? you need call normalize() using timezone object again when doing datetime arithmetic: >>> first datetime.datetime(2013, 3, 10, 2, 0, tzinfo=<dsttzinfo 'us/pacific' pst-1 day, 16:00:00 std>) >>> ppt.normalize(first) datetime.datetime(2013, 3, 10, 3, 0, tzinfo=<dsttzinfo 'us/pacific' pdt-1 day, 17:00:00 dst>) as noted in docs : in addition, if per...

linux - Invoking multi-line GAWK program in one line -

i'm wondering if it's possible run multi-line gawk program through shell can't have tabs or newlines. seems crop issue when have variable assignments. (e.g. one=$1 two=$2 in same line). thanks! looks adding stock-standard semi-colon allow this.

ansible ssh prompt known_hosts issue -

i'm running ansible playbook , works fine on 1 machine. on new machine when try first time, following error. 17:04:34 play [appservers] ************************************************************* 17:04:34 17:04:34 gathering facts *************************************************************** 17:04:34 fatal: [server02.cit.product-ref.dev] => {'msg': "failed: (22, 'invalid argument')", 'failed': true} 17:04:34 fatal: [server01.cit.product-ref.dev] => {'msg': "failed: (22, 'invalid argument')", 'failed': true} 17:04:34 17:04:34 task: [common | remove old ansible-tmp-*] ************************************* 17:04:34 fatal: no hosts matched or hosts have failed -- aborting 17:04:34 17:04:34 17:04:34 play recap ******************************************************************** 17:04:34 retry, use: --limit @/var/lib/jenkins/site.retry 17:04:34 17:04:34 server01.cit.product-ref.dev ...

java - How to gracefully delete a file from disk in a web application? -

in our web application based on logic generate file on disk. user's browser can request file. done using ajax. want delete file when there no need it. have done far delete in following situations: successful completion of logic when file sent user if there failures before delivery (in case of exceptions i'm deleting file. i've overridden finalize method in case of garbage collection going deleted well). if user's session terminates. using listener listens httpsessiondestroyedevent . cover scenario in user request file before delivery close browser. some info application: application based on spring , using singleton-scoped bean injected proxy (aop scoped-proxy) handle file locations in session. now, here question: if user opens 2 tabs in browser , in 1 of tabs request file (assume long running process) , in second tab, log out of system. in case file generated , there no means deleted system automatically. how can cover scenario?

Python sort list of tuples by first value of tuple except for special case -

hey have list of tuples looks like: [(5, "dummmy_string1"), (6, "dummy_string2"), (3, "special_string")] i want order in ascending order of first value of tuple, except case string equal special_string . want special_string ordered last regardless of integer value in tuple. i have right doesn't seem working: sorted(li, key=lambda x: (x.string_value == "special_string", x.int_value)) i find tuples have special_string , remove them list, sort list, , append them end, looking cleaner solution. edit: i made silly mistake , realized solution work...=) li = [(5, "dummmy_string1"), (6, "dummy_string2"), (3, "special_string")] print sorted(li,key=lambda x:(x[-1]=="special_string",)+x) should work fine ... no idea x.string_value (other perhaps attributeerror ) in event there several special_string 's sort them in same order other strings (that standard left2right tuple sortin...

Getting file path from polymer to Java program -

i have java program takes around 1000 files input , performs necessary functions on , return new files output. works fine. have made ui using polymer.js , issue facing of file path. java program receives fake path polymer ui , therefore unable process files. solution can provide files polymer , receive exact file paths in java program , perform necessary functions on it. thanks

javascript - Setting Access-Control-Allow-Origin doesn't work with AJAX/Node.js -

i keep facing same error on , on again: xmlhttprequest cannot load http://localhost:3000/form. no 'access-control-allow-origin' header present on requested resource. origin 'http://localhost:8000' therefore not allowed access. response had http status code 404. i've read countless posts similar 1 , pretty have same answer, namely add following setting: res.setheader('access-control-allow-origin', '*') . that's i've been doing still doesn't work. gave angular.js app on localhost:8000 (when btn clicked logsth() called) , node works on localhost:3000. here's like: app.controller('contact', ['$scope', function($scope) { $scope.logsth = function(){ var datas = {'may':'4','june':'17'}; $.ajax({ url: 'http://localhost:3000/form', method: 'post', crossdomain: true, data: datas }); }; }]); and node...

VBA in Word code to delete or change code from ThisDocument -

i have code in microsoft word .docm file disables save function , pops message: sub filesave() msgbox "save disabled." & vbnewline & "" & vbnewline & "to save changes, use save as." end sub this might tricky want disable that code, is, enable saving again, on trigger event (when user clicks button). when document first opened have save enabled, not save. after event, want save work again. i've gotten things work, programmatically add code thisdocument: thisdocument.vbproject.vbcompontents("thisdocument").codemodule.addfromstring "private sub document_close(): activedocument.saved = true: end sub" however don't know if there way edit or delete code, using other code. a simpler way have variable of type boolean. when button clicked change value of boolean, , use conditional statement re-enable saving

c# - Update record if it exists -

i'm new ef, , i'm trying understand best way handle inserting , updating data. context, i'm using .net mvc website boiler plate, , i've created customers table 1:1 relationship aspnetusers. i've created view manage customer data. here httppost actionresult: [httppost] [validateantiforgerytoken] public async task<actionresult> addcard(external.stripe.customer customer) { if (!modelstate.isvalid) { return view(customer); } external.stripe.customeroperations co = new external.stripe.customeroperations(); customer = co.create(customer); var user = usermanager.findbyid(user.identity.getuserid()); customer.userid = user.id; var context = new external.stripe.customercontext(); context.customers.add(customer); context.savechanges(); return redirecttoaction("index", "manage"); } i feel i'm going down wrong path,...

google bigquery - Alter table or select/copy to new table with new columns -

i have huge bq table complex schema (lots of repeated , record fields). there way me add more columns table and/or create select copy the entire table new 1 addition of 1 (or more) columns? appears if copying table requires flattening of repeated columns (not good). need exact copy of original table new columns. i found way update table schema looks rather limited can seem add nullable or repeated columns. can't add record columns or remove anything. if modify import json data (and schema) import anything. import data huge , conveniently in denormalized gzipped json changing seems huge effort. if want use query copy table, don't want nested , repeated fields flattened, can set flattenresults parameter false preserve structure of output schema.

How to check if JSON object is null in Java -

i working on app performs search on server, data transmission based on json, experiencing problems when parsing results, if there no network nullexception when getting information json object, tried checking connection, if connected internet can proceed in situations had internet when requesting data , lost when receiving server nullexception too, thought checking if json object null before tempering it, methods of checking null know have failed, below java code: mcommentlist = new arraylist<hashmap<string, string>>(); try { // building parameters list<namevaluepair> params = new arraylist<namevaluepair>(); params.add(new basicnamevaluepair("query", searchbox.gettext().tostring())); log.d("request!", "starting search"); // getting product details making http request jsonobject json = jsonparser.makehttprequest(sear...

javascript - How to iterate multiarray on jquery? -

Image
i have jquery array i trying iterate it, first value [false, false] , cycle ends i using function iterate function compareandshoworhide(url) { var elem = jquery(".vanessa_content .block-title"); $.each(url_array , function( index, obj ) { $.each(obj, function( key, value ) { console.log(key); console.log(value); }); }); } with no success, appreciated thanks jsfiddle -> https://jsfiddle.net/xvcg0spz/ you declare url_array array, var url_array = []; but not using one. arrays take numerical indexes, javascript not have associative arrays (arrays take strings index). so doing following: url_array['/'] = [false, false]; url_array['/cart'] = [true, false]; url_array['/checkout/34'] = [true, false]; you setting properties on array object, , not adding array. array empty. since instance of array, jquery treat such , try access array elements , not properties have set. ...

wordpress - MySQL sql dump wrong char encoding -

we did wordpress sql backup sql dump, can see charset set utf8 reason non english text shows this: ╫ó╫¿╫¢╫×¥╫¬ ╫ó╫ש╫ª╫×¥╫ס is can fix? encoding it? found proper encoding, reason encoded hebrew chars in cp862

java - what is the reason behind below condition -

this question has answer here: comparing float , double primitives in java 5 answers class magicwithoperators{ public static void main(string[] args) { float f = 10.2f; double d = 10.2; system.out.println(f==d); } } output: false . why 10.2f==10.2 false 10.0f==10.0 true? the reason value 10.2 cannot represented exactly, using either float or double representations. both different approximations 10.2, mathematically not equal. the reason it's true 10.0f , 10.0 10 can represented in both float , double representations. here hexadecimal representations of numbers above. 41233333 // 10.2f (float, inexact) 4024666666666666 // 10.2 (double, inexact) 4024666660000000 // 10.2f (widened double, inexact) 41200000 // 10.0f (float, exact) 4024000000000000 // 10.0 (double, exact) 40240000...

c++ - Partial specialization for pointer as function return type -

i have template wrapper function returns value this: template<class t> t foo(bar& bar, const char* key) { return bar.value<t>(key); } but want handle pointer types bit different, this: template<class t> t foo(bar& bar, const char* key) { return (t)bar.value<void*>(key); } so can do: int x = foo<int>(bar, "x"); baz* b = foo<baz*>(bar, "b"); writing above gives me error because of multiple definitions. there other way this? prefer not add cast each function uses pointer. i've tried following: template<class t> t foo(bar& bar, const char* key) { if(std::is_pointer<t>::value) return (t)bar.value<void*>(key); else return bar.value<t>(key); } but doesn't work either because there qvariants involved , produce error instantiating 1 of template functions unknown pointer type (the bar.value<t> ). use tag dispatching delegate call...

jsf - I can't see pdf generated by DynamicReport -

i'm making pdf report, i'm using jsf, primefaces, can see report in dialog without problems when download pdf, it's can't show. message adobe reader file damaged. this code: bytearrayoutputstream baos = new bytearrayoutputstream(); try { dynamicreports.report() .settemplate(plantillas.reporttemplate) .columns(statecolumn, stateporc) .title(templates.createtitlecomponent2("tittle")) .summary( dynamicreports.cht.barchart() .settitlefont(boldfont) .setcategory(statecolumn) .series( dynamicreports.cht.serie(itemcolumn).setseries(statecolumn) ) .setcategoryaxisformat(dynamicreports.cht.axisformat().setlabel("label")) ) .pagefooter(templates.footercomponent) ...

sql server - Date Picker format vs Database timestamp -

is possible compare 2 dates if formatted in different ways? 1 date coming coldfusion ui input in following format: mm/dd/yyyy my timestamp in mssql database in following format: yyyy/mm/dd background: need write query compares dates , returns rows timestamp after user selected date. need reformat either date? example: <cfset start_date = 'form.sdate'> <cfquery name="sortdate" datasource="rc"> select * my_db_table submission_date > #start_date# </cfquery> first off, always use cfqueryparam in queries when dynamically including content. second, should able use start_date "as is" compare date date in database so, like: <cfquery name="sortdate" datasource="rc"> select * my_db_table submission_date > <cfqueryparam value="#start_date#" cfsqltype="cf_sql_date"> </cfquery> last, can test raw sql in mssql management studio test da...

Get class name from a class nested in a module in ruby -

if give you: module module somethingelse class foo end end end how class name of "foo"? in console, have similar example, when .name on it doesn't print out expect. this whats in console: pry(main)> aisiswriter::controllers::commentsmanagement::commentshandler.name => "aisiswriter::controllers::commentsmanagement::commentshandler" what expect "commentshandler" you can do: aisiswriter::controllers::commentsmanagement::commentshandler.name.split('::').last || ''

ios - Swift - Using CGContext to draw with finger -

i'm trying make drawing app. have single custom uiview: class drawview: uiview { var touch : uitouch! var lastpoint : cgpoint! var currentpoint : cgpoint! override func touchesbegan(touches: set<nsobject>, withevent event: uievent) { touch = touches.first as! uitouch lastpoint = touch.locationinview(self) println(lastpoint) } override func touchesmoved(touches: set<nsobject>, withevent event: uievent) { touch = touches.first as! uitouch currentpoint = touch.locationinview(self) self.setneedsdisplay() lastpoint = currentpoint } override func drawrect(rect: cgrect) { var context = uigraphicsgetcurrentcontext() cgcontextsetlinewidth(context, 5) cgcontextsetstrokecolorwithcolor(context, uicolor.bluecolor().cgcolor) cgcontextsetlinecap(context, kcglinecapround) cgcontextbeginpath(context) if lastpoint != nil { cgcontextmovetopoint(context, lastpoint.x, lastpoint.y) cgcontextaddlinetopoint(conte...

ifstream - Reading from text file is not working C++ -

i want read text file , don't know why code not working. have put correct text file name on folder program running. must doing small. please highlight issue in code below: // consoleapplication1.cpp : defines entry point console application. // #include "stdafx.h" #include <iostream> #include <fstream> #include <string> #include<cstdio> using namespace std; #ifdef win32 #include <direct.h> #define getcurrentdir _getcwd #else #include <unistd.h> #define getcurrentdir getcwd #endif std::string get_working_path() { char cwd[1024]; if (getcurrentdir(cwd, sizeof(cwd)) != null) return std::string(cwd); else return std::string(""); } int main() { string line; //ofstream myfile; //myfile.open("cmesymbols.txt", ios::out | ios::app | ios::binary); ifstream myfile("cmd.txt"); if (myfile.is_open()) { while (getline(myfile, line)) { ...

security - sh script vulnerability in Linux -

i given assignment computer security class. we given piece of code analyze , determine vulnerabilities might have. #!/bin/sh # shell script create copy of shadow file /tmp directory echo > /tmp/shadowcopy # allow root access chmod 600 /tmp/shadowcopy # append original file copy cat /etc/shadow >> /tmp/shadowcopy # hint: access permissions of file in linux verified when # file opened. process keep original permissions long # keeps file open, if permissions change. some classmates , determined script might suffer race condition vulnerability if 2 separate process try open /tmp/shadowcopy. we think command injection vulnerability possible if /tmp/shadowcopy changed before append begins. are our assumptions wrong, or code suffer other vulnerabilities might have not considered? there indeed race condition, in adversary potentially access /tmp/shadowcopy between script creating , script setting permissions. however, if indeed script creates file, initial ...

regex - How to match a string with a wildcard character in java -

i need write regular expression match string of value "*.log" have following code , doesnt seem work expected. if (name.matches("\\*\\.log") the above statement returns false, when value of name "*.log" any appreciated. why doing that? couldn't do if(name.endswith(".log")) it seems me simpler option, since can before .log, if used wildcard. also, if want make sure isn't ".log", simple. if(name.endswith(".log") && !name.equals(".log")) hopefully helped bit!

json - How do I ignore PHP Notice: json_decode(): integer overflow detected in Yii? -

i'm trying decode long integer in json, crashes , gives error in yii. use json_bigint_as_string option. how bypass error or ignore it? php > var_dump( json_decode('[66933258,"b009gq034c",281441845828]', false, 512, json_bigint_as_string)); php notice: json_decode(): integer overflow detected in php shell code on line 1 array(3) { [0]=> int(66933258) [1]=> string(10) "b009gq034c" [2]=> string(19) "9223372036854775807" } in app, gives php notice – yii\base\errorexception json_decode(): integer overflow detected just tried code , on machine works perfectly, perhaps has php version or so? the thing can think of (if don't need values number, values) use preg_replace "escape" numbers strings first: $json = '[66933258,"b009gq034c",281441845828]'; var_dump(json_decode(preg_replace('/(\w)(\d+)(\w)/', '\\1"\\2"\\3', $json))); will yield th...

c# - Discard changes made in a Gridcontrol when a user clicks the "Cancel" button and exit -

i have 2 forms. first forms creating/updating person , has button 2nd form holds information person's children using devexpress gridcontrol. i let user option crud children form when created new person (maybe design failure me that's matter). when finish filling children details can hit "save" or "cancel , exit" buttons. if hit "cancel.." need underlying children datatable revert way before. tried canceledit() method of bindingsource without success. tried next thing: void cancelbtn_click(object sender,eventargs e) { datatable dt = (datatable)bindingsource.datasouce datatable; dt.rejectchanges(); } which doesn't work if first time open , crud children grid , hit save , on second time open other stuff , hit cancel revert first save operations cause update database when user finish creating person , hit "save" on person form , not in between children form updates. i'm taking care of relation manually...

Visually compare forcasted values (ARIMA model) in MATLAB -

i'm new time-series analysis. forecast values based on arima model , plot them against hold out data. here's have: % retrieve ibm closing prices c = yahoo; imb_data = fetch(c,'ibm','close','1-sept-2014','31-dec-2014'); imb_date = imb_data(:,1); imb_close = imb_data(:,2); % contains 85 data points using autocorr , parcorr , deduce appropriate model should be: mdl = arima(1,0,0); fit model first 60 observations, , reserve remaining 15 observations evaluate forecast performance. fit_model = estimate(mdl, imb_close(1:60)); use fitted model forecast 15-period horizon: [y, mse] = forecast(fit_model,15,'y0',imb_close(1:60)); visually compare forecasts holdout data: figure plot(imb_date, imb_close,'color',[.7,.7,.7]) datetick hold on plot(61:85,y,'b'); hold off the problem forecasted values not being ploted, doing wrong?

c# - Attaching an event to UIWebView ScrollViewer prevents zooming -

whenever attach event uiwebview's scrollviewer detect scrolling prevent uiwebview zooming in , out. however, scrolling , down still works. viewing pdf in uiwebview. i've tried these events: scrolled scrolledanimationended zoomingended didzoom for example tried: contractwebview.scrollview.scrolled += (object sender, eventargs e) =>{ debug.writeline("scrolled"); }; i have event tried empty event body. did tried set delegate scrollview instead of using events? this: public class scrollviewdelegate : uiscrollviewdelegate { public override void scrolled(uiscrollview scrollview) { console.writeline("scrolled"); } } contractwebview.scrollview.delegate = new scrollviewdelegate(); edit: here complete code used test , worked me: public class ipadviewcontroller1 : uiviewcontroller { public override void viewdidload() { base.viewdidload(); uiwebview webview = new uiwebview(new cgrect(0, 0...

ios8 - how to get the distance between to points on earth in Swift? -

i used 2 methods .. apple's 1 @ibaction func getdistancepressed(sender: anyobject) { distancelabel.text = "\(location_2.distancefromlocation(location_1))m" // meters } and mine @ibaction func getdistancepressed(sender: anyobject) { let lat1 = location_1.coordinate.latitude let lon1 = location_1.coordinate.longitude let lat2 = location_2.coordinate.latitude let lon2 = location_2.coordinate.longitude distancelabel.text = "\(getdistancefromlatloninmeter(lat1, lon1: lon1, lat2: lat2, lon2: lon2))m" } func getdistancefromlatloninmeter(lat1 : double ,lon1 : double ,lat2 : double ,lon2 : double) -> double{ var earthradius : double = 6372797.560856 //inmeter var deltalat : double = deg2rad(lat2 - lat1) var deltalon : double = deg2rad(lon2 - lon1) var latitudeh = sin(deltalat * 0.5) latitudeh *= latitudeh var lontitudeh = sin(deltalon * 0.5) lontitudeh *= lontitudeh var tmp = cos(deg2rad(...

Magento: Showing only simple products on checkout success page -

i've displayed products ordered on checkout success (success.phtml), problem it's displaying configurable and associated simple product when want display simple one. tried doing below doesn't display anything. can't use typeof on $item doing wrong. kindly take @ code , give me hint how working properly? cheers. <?php $order_id = mage::getsingleton('checkout/session')->getlastrealorderid(); $order_details = mage::getmodel('sales/order')->loadbyincrementid($order_id); foreach ($order_details->getallitems() $item): ?> <?php if ($item->getparentproductid()): ?> <h4> <?php echo $item->getname(); ?> </h4> <br /> <h4>quantity: <?php echo round($item->getqtyordered(), 0); ?> </h4> <br /> <img src="<?php echo $this->helper('catalog/image')->init($item, 'small_image')->resize(200); ?>" width="200" height="200" cla...