Posts

Showing posts from February, 2015

ios - Background fetch stops working after about 10 to 14 hours -

my application uses backgroud fetch send , upload small portion of data every 30 minutes. service working correctly 10 - 14 hours after application minimized working in foregroud - application correctly sending , receiving data every 30 minutes. does know happens service after couple of hours? ios system automatically terminate application , therefore background fetch stops working? can explain? ios provides 30 seconds time frame in order app woken up, fetch new data, update interface , go sleep again. duty make sure performed tasks manage finished within these 30 seconds, otherwise system stop them. maybe internet slow app took more 30 seconds & system stopped application. -(void)application:(uiapplication *)application performfetchwithcompletionhandler:(void (^)(uibackgroundfetchresult))completionhandler{ nsdate *fetchstart = [nsdate date]; // make process here [viewcontroller fetchnewdatawithcompletionhandler:^(uibackgroundfetchresult result)

html - having difficulty with responsive web design -

i image larger size on computer, fit smaller devices. when try have larger image size computer, increase size on phone, , shrinks , pushes navigation (which supposed in middle) left. (my navigation meant on left hand side on computer, in middle horizontally on smaller devices) how can set different image sizes different devices? tried @media doesn't seem working. i'm beginner, see i'm doing wrong? areas experience issue on .typecontainer, .type, .type1 link screenshots: http://imgur.com/bm5xdwr,p9eux4v,mq3gpp1#0 html: <!doctype html> <html> <head> <title>example</title> <link rel=”stylesheet” type=”text/css” href=”style.css” /> <meta name=”viewport” content=”width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0”> </head> <body> <div id=”topnav”> <nav class=”navigation” role=”navigation”> <ul> <li class=”work”> <a href=”work.html”>work<

java - Why this Regular Expression doesn't work? -

i have regular expression extract 2 tokens, delimiters [ ' ] , words between apostrophes ' stack overflow '. question is, why regular expression doesn't work? regex: (['])|'([^']*)' here link explain it: regular expression only works extracting apostrophes but, words between apostrophes no. note: need extract apostrophe , word between apostrophe separately 'stack overflow'. the result like: ' stack overflow ' greetings. your regex says match either single quote or content between quotes, it's exclusive or way have it. each of them capture group use regex: (')([^']*)(') to first quote, that's not quote last quote

javascript - Date class converts Timestamp wrong -

in application, creating live console output messages timestamp , contents. read, approach using below date() class should work expected, timestamp multiplied 1000 milliseconds. i logging timestamp debugging purposes , getting values "1441041070066". when plug these epoch/unix converters, date/time correct. code giving nonsense "22:7:46" , 1 minute later "20:48:37". can please explain doing wrong in case? messages.foreach( function (item) { var timestamp = item.timestamp; // /date(1440823073243)/ var timestamp = timestamp.substring(timestamp.lastindexof("(")+1, timestamp.lastindexof(")")); console.log(timestamp); var source = item.source; var type = item.type; var contents = item.contents; // date/time in milliseconds var date = new date(timestamp * 1000); var time = date.gethours() + ":" + date.getminutes() + ":" + date.getseconds(); console_log("<font colo

reflection - Java Dynamic Casting in Apache POI -

i using apache poi yield excel reports, , since each column compatible respective datatype (date, number, integer ...), made static method return object can "casted". since prone reducing code as possible, chose following: string value = resultset.getstring(i); object castablevalue = engine.formattingvalue(value); cell.setcellvalue((castablevalue.getclass().cast(castablevalue))); however, not accepted @ compile time poi library, while sure work @ run time. i have use if else 4 datatypes (double, integer, calendar, , string). any suggestions achieve dynamic solution ?

javascript - how to debug a div that shows and hides almost instantly -

on website, have lot of code, many js vendors, etc. on 1 specific page, have king of right sidebar pops out less half second, never enough me click on , try debug weird thing (i'm thinking of putting display none on class). i've tried go through dom , place dom breakpoints in chrome browser it's not doing nothing. does know how debug ? thanks lot ! use "inspect element" detect sidebar , navigate class or id has display:none; property. can click on or off in developer toolbar...

Array of values loaded through UART in VHDL -

i working on project in vhdl wich includes mutliplying matrices. able load data pc arrays on fpga using uart. making first bigger steps in vhdl , not sure if taking right attitude. i wanted declare array of integer signals, , implement uart receive data form pc , load signals. however, can't use for-loop that, synthesised load data parallelly (which impossible, because values comming pc 1 after another, using serial port.) , because matrices may various sizes, in order assign signals 1 one need write lots of specific code (and appears bad practice me.) is idea use array of signals , load data signals through uart realizable? , if approach entirely wrong, how achieve that? what want doable need design kind of hardware monitor act intermediate between uart , storage (your array of integer signals). hardware monitor interpret commands coming uart , perform read/write operations in storage. have 1 interface storage , uart. have define kind of protocol syntax commands ,

regex - Javascript Regular Expression not matching -

morning all i have javascript regular expression doesn't work correctly , i'm not sure why. i'm calling api @ https://uptimerobot.com , , getting json string details of monitor statues. wrapped in function call syntax. this: jsonuptimerobotapi({masked-statues-obj}) as call being made generic script hoping test response see if had type of syntax wrapping parse accordingly. however can't seem find regex syntax match logic: start of string an unknown number of characters [a-za-z] open parentheses open brace an unknown number of character close brace close parentheses end of string this looks right: ^[a-za-z]+\(\{.*\}\)$ and works in regex101: https://regex101.com/r/se7dm6/1 however fails in code , via jsfiddle: https://jsfiddle.net/po49pww3/1/ the "m" added in regex101 actual string longer, , failed match without it, number of small tweeks i've tried havn't resulted in match in jsfiddle. anyone know whats wrong?

python - setup celerybeat with supervisord -

i confused on how use celery beat supervisord process control system. following code example of celerybeat program on supervisord. ; ================================ ; celery beat supervisor example ; ================================ [program:celerybeat] ; set full path celery program if using virtualenv command=celery beat -a myapp --schedule /var/lib/celery/beat.db --loglevel=info ; remove -a myapp argument if not using app instance directory=/path/to/project user=nobody numprocs=1 stdout_logfile=/var/log/celery/beat.log stderr_logfile=/var/log/celery/beat.log autostart=true autorestart=true startsecs=10 ; if rabbitmq supervised, set priority higher ; starts first priority=999 on 7th line has following code: /var/lib/celery/beat.db , this, , replace path with? similarily, replace path /var/log/celery/beat.log ? thanks. from command help: --schedule is: -s schedule, --schedule=schedule path schedule database. extension '.db'

python - MongoEngine Query Optimization -

i have 2 collections scenariodrivers , modeldrivers has 1 many relationship each other. class scenariodrivers(document): meta = { 'collection': 'scenariodrivers' } scenarioid = referencefield('modelscenarios') driverid = referencefield('modeldrivers') drivercalibrationmethod = stringfield() segmentname = stringfield() drivervalue = listfield() calibrationstatus = stringfield() adjustedvalues = listfield(default=[]) createdate = datetimefield(default=objectid().generation_time) lastupdatedate = datetimefield(default=datetime.utcnow()) class modeldrivers(document): meta = { 'collection': 'modeldrivers' } portfoliomodelid = referencefield('portfoliomodels') drivername = stringfield() createdate = datetimefield(default=objectid().generation_time) lastupdatedate = datetimefield(default=datetime.utcnow()) fieldformat = stringfield() driv

node.js - Insert json file into mongodb specifying key to use as _id -

i have json has id want insert mongo db. json {"id" : 538748, "event_date":"2016-07-02", "name" : "tim"} is there way map "id" mongo's _id when inserting? router.get('/newpage', function (req, res) { var db = req.db; var collection = db.get('mydatabase'); request({ url: "http://someurl.com/json", json: true }, function (error, response, body) { if (!error && response.statuscode === 200) { // how specify _id here collection.insert(body); } }); }); you need modify body doc you're inserting rename id field _id : body._id = body.id; delete body.id; collection.insert(body); but it's typically cleaner , safer build new doc valid fields, performing mapping in process: var doc = { _id: body.id, event_date: body.event_date, name: body.name }; collection.insert(doc);

android - Fragments in Tabs of ViewPager shows wrong data -

i got following tutorial http://blog.grafixartist.com/material-design-tabs-with-android-design-support-library/ after implementing viewpager. relised though correct interfaces shown in tabs. if put toast in 3 fragments. first displays toast second , second shows toast third, , third shows no toast though has toast. below code public class activeseen extends appcompatactivity { // declaring view , variables toolbar toolbar; viewpager mviewpager; parseuser muser; public string objectid; public string mser; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_active_seen); toolbar = (toolbar) findviewbyid(r.id.tool_bar); setsupportactionbar(toolbar); muser = parseuser.getcurrentuser(); mser = muser.getusername(); intent = new intent(); intent geti=getintent(); objectid = geti.getstringextra("objectid"); final viewpager viewpager = (viewpag

java - Passing array from one android activity to another and using it in a spinner -

in source code, have 2 activities. in activity a.java have array private string[] typename = new string[100]; and starting new activity public void loadcuecardset(view view){ intent loadcuecardpage = new intent(this, loadcuecardset.class); loadcuecardpage.putextra("types", typename); startactivity(loadcuecardpage); } in second activity, have protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_load_cue_card_set); // array of choices // selection of spinner spinner spinner = (spinner) findviewbyid(r.id.spinner); // application of array spinner bundle extras = getintent().getextras(); string colors[] = extras.getstringarray("types"); // doesn't work arrayadapter<string> spinnerarrayadapter = new arrayadapter<string>(this, android.r.layout.simple_spinner_item, colors); spinnerarrayadapter.setdropdownviewresource(andr

java - Timeout Rest service -

i working on rest service. service retrieves information legacy third party system using proprietary protocol abstracted api exposed noway set sort of timeout on calls system. system slows down load on service increases. is there way service send default response if operation takes long?. suggestion on how tackle issue appreciated? you can wrap code block makes api request thread , use future timeout request. here example how it; https://stackoverflow.com/a/15120935/975816 after timeout; implement exceptions , set default response in catch block; string response; try { response = future.get(5, timeunit.minutes); } catch (interruptedexception ie) { /* handle interruption. or ignore it. */ response = "default interrupted response"; } catch (executionexception ee) { /* handle error. or ignore it. */ response = "default exception response"; } catch (timeoutexception te) { /* handle timeout. or ignore it. */ response = "

php - convert an array into individual strings -

i have following arrays , convert each 1 of them individual strings. in other words, break array individual pieces. $formatsarray = $_post['formats']; $topicsarray = $_post['topics']; this because include individual strings in following query " $resources = "select * resources stage '%".$stage."%' , format '%".$formats."%'"; $run_query = mysqli_query($con, $resources); this because format expect individual string comparison, such lets assume array ["video", "blogs", "articles"] , wouldn't work if format compared video,blogs,articles rather video, blogs or articles. i hope clear, , clarification, please advise. all best, update: $formats = explode(',', $formatsarray); $topics = explode(',', $topicsarray); $resources = "select * resources stage '%"

c++ - Working with two user interfaces - Qt 5.5 -

i have simple mainwindow has button , lineedit . when type , click button, new dialog appears label supposed display string typed. basically, have trouble sending information ui. tried working new class string variable, didn't work. i try give example of want do. //ui2 dialog ui2->label->settext(ui->lineedit->text()); ui private variable, it's not accessible class. //mainwindow.cpp mainwindow::mainwindow(qwidget*){ this->_dialog = new dialog(this); //... } mainwindow::on_pushbutton_clicked(){ _dialog->_labe->settext(ui->lineedit->text()); } //dialog.h class dialog{ public: qlabel* _label; dialog(qwidget* ){ _label = ui->label; } }

php - How to know the class who is calling a method on inherited class? -

i want know name of class calling method. ex: class mother{ static function foo(){ return "who call me"; } } class son extends mother{ } class otherson extends mother{ } son::foo(); >> son otherson::foo(); >> other son how this? found solution using get_called_class() : class mother{ static function foo(){ echo get_class(),php_eol; echo __class__,php_eol; echo get_called_class(),php_eol; } } class son1 extends mother {} class son2 extends mother {} son1::foo(); son2::foo(); returns: mother mother son1 mother mother son2 so can see get_class , __class__ both return mother , using get_called_class() return class called function! looks use static::class return same, if using php >= 5.5

gitlab - Git: Changing my application architecture -

i maintain repository of code in gitlab. due architectural changes in application, need maintain separate version of repository different. but, need keep old version too, future development. i know a new git branch serve purpose. but, in case, need branch permanently separated other branch. please correct me if right way, or suggest me otherwise. when working git have find workflow. tells when branch, tag, clone , on. i'm fond of feature branch one. your case doesn't seem fit in branching case me may find comfortable working way. personally, i'd create repository.

ios - Button action done when touched outside of keyboard - Swift Xcode -

i using following code enter value in uitextfield 'item', on clicking button addbutton value in textfield appended array , clear textfield . have added code hide keyboard when touched outside. the problem is, after typing word in textfield , touching outside, action in button in done, before button pressed @iboutlet weak var item: uitextfield! @ibaction func addbutton(sender: anyobject) { todolist.append(item.text!) item.text = "" } override func touchesbegan(touches: set<uitouch>, withevent event: uievent?) { self.view.endediting(true) } i don't know problem, because new swift, first delete the @iboutlet weak var item: uitextfield! & @ibaction func addbutton(sender: anyobject) { todolist.append(item.text!) item.text = "" } 02.then go story board click view controller , click last button sign of arrow right. check outlets. delete item , add button on list. then again add text field

multithreading - Does SAS have a concurrency framework like Java -

in java,you have concurrency framework developer can use submit multiple tasks in parallel each task runs in own thread. does similar concurrency framework exist in sas developer can submit parallel jobs or programs in different threads? with sas, there (as there are) myriad ways ask. the closest thing ask sas mp connect , system allowing multiple threads either on smp ( symmetric multiprocessing ) machine. it's part of sas/connect starting in version 8. if submitting code (via sas/connect) server, have other options. can submit multiple queries rsubmit using either synchronous or asynchronous processing, example. you can also, of course, submit multiple sas calls yourself, if don't have license sas/connect. can either have batch process calls multiple sas sessions different input parameters, or have sas call more copies of (recursively, perhaps). if have sas 9.4, can use proc ds2 , has built-in multithreading. more object-oriented approach sas data

javascript - Three.js and collision detection -

i'm quite new in 3d , threejs. i set scene ground, on top of ground lots of cubes. http://jsfiddle.net/whurp02s/1/ i'm trying select cubes cross yellow rectangle. so looked @ exemple on internet , found raycaster object , it's intersectobject function //**************** colision detection var caster = new three.raycaster(); var collisions = []; var rays = [ new three.vector3(0, 0, 1), new three.vector3(1, 0, 1), new three.vector3(1, 0, 0), new three.vector3(1, 0, -1), new three.vector3(0, 0, -1), new three.vector3(-1, 0, -1), new three.vector3(-1, 0, 0), new three.vector3(-1, 0, 1) ]; ( var = 0; < rays.length; += 1 ) { caster.set( squaretl.position, rays[i] ); for( var boxid in boxgroup ) { var boxobj = boxgroup[boxid]; collisions = caster.intersectobject( boxobj ); if ( collisions.length ) { console.log(collisions);

jsf - How do I change the second dropdown based on value changes from first dropdown using a4j? -

i using 2 dropdowns in jsf. need use a4j richfaces ajax call only. based on value change in 1st dropdown, have change display 2nd dropdown. first dropdown having values: dc, rc , ab. in 2nd dropdpwn: if value in dropdown 1 dc, change value in selectitem dc related subjects. ( have built list of subjects dc) similarly if value in dropddown 2 rc, change value in selectitem dc related subjects. ( have built list of subjects dc) if not dc or rc, show dropdpwn null values. dropdown 1: <h:selectonemenu id="skillsetarea" valuechangelistener="#{mybean.changeskillset}" value="#{mybean.skillset}"> <f:selectitem itemlabel=" " itemvalue="" /> <f:selectitems value="#{referencebean.skillsetcodes}" /> <a4j:support event="onchange" ajaxsingle="true"/> </h:selectonemenu> dropdown 2: <h:selectonemenu id="subjects"

javascript - Fetch selected item of DropDownList using $(this) object -

how fetch selected item of dropdownlist using $(this) ? i have 2 dropdownlists in web page. want selected item name. tried 3 ways , each gave different result. this method showed selected-item in "1st list" , selected-item of "2nd list". guess because selector not qualified id. this method gave proper result. can achieve same result using $(this), instead of id. guess object pointing html-element. this method gave no results $(document).ready( function() { $('#idservertype').bind("change", loadx); } ); . function loadx() { var str = ""; ///// 1 str = $("select option:selected").text(); console.log('menu clicked: ' + str); ///// 2 str = $("#idservertype option:selected").text(); console.log('menu clicked: ' + str); ///// 3 str = $("this option:selected").text(); //3 console.log('menu cli

C++ Looping through array and displaying something based on condition -

i‘m having trouble completing task, task follows: each savings account program must calculate interest paid follows: if account balance higher 10000 pounds, or account has not had money debited more 30 days, interest 6% of balance. if not, interest must 3%. this original code: #include <iostream> using namespace std; const int maxaccounts =8; int main() { int accountnumber[maxaccounts] = {1001, 7940, 4382, 2651, 3020, 7168, 6245, 9342}; double balance[maxaccounts] = {4254.40, 27006.25, 123.50, 85326.92, 657.0, 7423.34, 4.99, 107864.44}; int dayssincedebited[maxaccounts] = {20, 35, 2, 14, 5, 360, 1, 45}; //add code here return 0; } here attempt, i'm studying arrays right trying grasp it, there errors attempt. can post solution able study , learn it? #include <iostream> using namespace std; const int maxaccounts = 8; int interest(int balance, int maxaccounts); int main() { int accountnumber[maxaccounts] = { 1001, 7940, 4382, 2651, 3020, 7168, 6245, 9342

php - Error on Insert clause: Unknown column '$variableName' in 'field list' -

edit: read answers below before reading incorrect sql knowledge lol so i'm trying insert variable , reason thinks it's column, though have in single quotes. doing wrong? time. unknown column '$emailaddress' in 'field list'] in execute("update mailer_recipients set email_address=$emailaddress id=539") $sql = 'update ' . $this->recipientdbtable . ' set ' . $this->recipientdbcolumn['result_id'] . '=' . '$hash' . ' ' . $this->recipientdbcolumn['id'] . '=' . $this->emailid; $sql = 'update ' . $this->recipientdbtable . ' set ' . $this->recipientdbcolumn['address'] . '=' . '$emailaddress' . ' ' . $this->recipientdbcolumn['id'] . '=' . $this->emailid; try this: $sql = "update {$this->recipientdbtable} set {$this->recipientdbcolumn['result_id']} = '{$hash}'

git - No Merge Request Button for a branch in Gitlab -

Image
newbie in using git , gitlab on here i have gitlab setup whereby have following branches project devevlopment (dev) -> consolidation (cons) -> testing (test) -> production (prod) -> master i merge code on "dev" "cons". i see there not "merge request" button available "dev" why case? tia update thanks inputs. wound : creating project/repository in group called master forking project/repository in group master , placing in group production. continued forks represent other deployment areas (i.e. test, cons, dev) this seems have produced effect looking - way - no longer have branches :dev, test, prod, etc. under 1 repository/project. the merge request buttons on screen create request merge default branch. dev is default branch, no button exists. if go merge requests tab should able create merge request default branch: navigate merge requests tab click new merge request select dev branc

linux - Folder filled with 10M+ log files and I can't delete them -

i had logging process go haywire on 1 of servers , have tons of files can't delete: ➜ logs ls -l | wc -l 11135951 ➜ logs rm log* -bash: fork: cannot allocate memory ideas? blow server away i'm genuinely curious how fix this. find . -type f -name 'log*' -delete would efficient way it in cases replacing -delete with-print show files removed. in case though don't think help @biffen points out sub dirs too to prevent use maxdepth argument -maxdepth 1 1 limits current dir

java - Equivalent of HTTPBasicAuth (python) in OkHttp (Android) -

i need auth key: auth = requests.auth.httpbasicauth(client_id, client_secret) code in python. how can in java (i use okhttp android app). with okhttp can create authenticator on okhttpclient such okhttpclient myokhttpclient = new okhttpclient(); myokhttpclient.setauthenticator(new authenticator() { @override public request authenticate(proxy proxy, response response) throws ioexception { string credential = credentials.basic("username", "password"); return response.request().newbuilder().header("authorization", credential).build(); } @override public request authenticateproxy(proxy proxy, response response) throws ioexception { return null; } }); this should job. found there not documentation around using basic authentication found from: android okhttp basic authentication

hive - Finding the closest location to a lat and long value -

i have 2 tables t1 , t2 ( t1 has 1/10th of size of t2 ). each table has 2 columns <lat, long> contain latitude , longitude of points. each row in t1 i'd find row in t2 closest it. efficient query doing this? hive have sort of libraries geospatial search? you'll need bit of trig. please refer article on database journal the last routine believe looking (you'll need modify use): create definer=`root`@`localhost` procedure closest_restaurants_optimized` (in units varchar(5), in lat decimal(9,6), in lon decimal(9,6), in max_distance smallint, in limit_rows mediumint) begin declare one_degree_constant tinyint; declare earth_radius_constant smallint; declare lon1, lon2, lat1, lat2 float; if units = 'miles' set one_degree_constant = 69; set earth_radius_constant = 3959; else -- default kilometers set one_degree_constant = 111; set earth_radius_constant = 6371; end if; set lo

I need only date value part and time value part using ASP.NET C# -

i have 2 parameters 1 date , time, , need date value part , time values part. my 2 parameters below. // date parameter datetime dt = datetime.parseexact("01-jan-1999", "dd-mmm-yyyy", cultureinfo.invariantculture); bo.dateused5 = dt; // time parameter string fromtiming = ddl_fromhours.selecteditem.tostring() + ":" + ddl_fromminutes.selecteditem.tostring(); datetime interviewtime = convert.todatetime(fromtiming);//starttime bo.dateused4 = interviewtime;//interviewtime so need send mail candidate date part, should not contain time , time part, should not contain date. are looking this: datetime dt = datetime.parseexact("01-jan-1999", "dd-mmm-yyyy", cultureinfo.invariantculture); string maildate = dt.tostring("dd-mmm-yyyy");// give 01-jan-1999 string date = dt.tostring("dd-mm-yyyy"); // give 01-01-1999 you can try using string.format() string maildate = string.format(

machine learning - Data complexity measure -

as strive explain accuracy of machine learning algorithms, many authors suggest start degree of complexity in data. i working in data complexity measure like: class separability,overlapping , outlier measure, affect classifier performance. for example if classes more separable, accuracy of classifier increased , classifier takes less time. i want calculate outlier measure of each data point in dataset , combine these measure , make 1 measure outlier in dataset. how can calculate outlier using k nearest neighbour or using k means clustering technique. thanx in advance..

CSS Flexbox (Header & Content[overflow: scroll]) with unknown header height -

struggling figure out how can have flexbox header (unknown height) , content (which scrollable) should take rest of space header not using. if set header height have no issues, because header can have more or less content (or screen sizes causing content wrap), can't set fixed height. example image http://i.imgur.com/rygpp4a.jpg any ideas on how achieve above? html,body{ height: 100%; margin: 0; } main{ display: flex; flex-direction: column; height: 100%; width: 50%; margin: auto; } header{ background-color: #333; color: #eee; } article{ background-color: #eee; overflow-y: scroll; flex: 1; } <main> <header>some text</header> <article>lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. @ vero eos et accusam et justo duo dolores et ea rebum. stet clita kasd gubergren, no sea ta

Index of a substring in a string with Swift -

i'm used in javascript: var domains = "abcde".substring(0, "abcde".indexof("cd")) // returns "ab" swift doesn't have function, how similar? xcode 8.3.1 • swift 3.1 extension string { func index(of string: string, options: compareoptions = .literal) -> index? { return range(of: string, options: options)?.lowerbound } func endindex(of string: string, options: compareoptions = .literal) -> index? { return range(of: string, options: options)?.upperbound } func indexes(of string: string, options: compareoptions = .literal) -> [index] { var result: [index] = [] var start = startindex while let range = range(of: string, options: options, range: start..<endindex) { result.append(range.lowerbound) start = range.upperbound } return result } func ranges(of string: string, options: compareoptions = .literal) ->

powershell - Returning Error code and event from SQL Server procedure call -

i trying setup powershell script run sql server stored procedures. initially, script returned either 0 or non-zero return code (by evaluating catch block), depending on whether procedure call failed or not: try { $command = new-object system.data.sqlclient.sqlcommand ("$query", $connection) $dataadapter = new-object system.data.sqlclient.sqldataadapter $command $dataset = new-object system.data.dataset $rowcount = $dataadapter.fill($dataset) if($rowcount -gt 0) { $dataadapter.fill($dataset) | out-null $return =,[int]$command.parameters["@returnvalue"].value $return += ,$dataset.tables[0].rows[0] } else{ $return=,[int]$command.parameters["@returnvalue"].value } } catch { $return=,10000 throw } now want make bit more usable , return error message if job fails. this, using system.data.sqlclient.sq

javascript - css ul list multiple item alignment -

Image
i have ul element conatins multiple items in line. put list in 300px fixed panel. <div class="panel panel-primary" style="width:300px"> <div class="panel-heading"> menu items</div> <div class="panel-body"> <ul> <li> <div class="content"> <button class="btn btn-sm btn-default"> <span class="glyphicon glyphicon-th" ></span> </button> long menu item name <div class="settings"> <div class="show-settings pull-rigth"> <div class="btn-group pull-right"> <button class="btn btn-xs btn-info"> <span class="glyphicon glyphicon-eye-open"></span>

Any data structure in java that supports multiple keys - not map exactly -

i came cross situation need like: 197 => 6 (1 year) 197 => 12 (2 years) want add multiple products , price, based on years of subscription, value varies. i wonder if have data structure in java supports duplicates keys (should behave map must support duplicate keys). i can creating class wanted know if there supports thing..it more map no map since needs support multiple keys. yes can using existing libraries guava. here link interface multimap of guava library link . here example on how use (taken here ): multimap<string, string> mymultimap = arraylistmultimap.create(); // adding key/value mymultimap.put("fruits", "banana"); mymultimap.put("fruits", "apple"); mymultimap.put("fruits", "pear"); mymultimap.put("vegetables", "carrot"); // getting size int size = mymultimap.size(); system.out.println(size); // 4 // getting values collection<str

javascript - Enhanced grid pagination throwing invalid argument error on dialog and portlet dialog settings -

i using dojox/widget/portlet,dojox/widget/portletdialogsettings , dijit/dialog webpage. these portlets , dialogs have enhanced grid within. have other similar widgets these 3 types in same page working fine. issue current widget only. the enhanced grids uses pagination. var plug = plugins: { pagination: { pagesizes: ["7", "14", "28", "all"], description: true, sizeswitch: true, pagestepper: true, gotobutton: true, maxpagestep: 4, defaultpagesize:7, position: "bottom" } } when click on maximize/try open dialog, below error in dojo.js. script87: invalid argument. file: dojo.js, line: 15, column: 87982 the code corresponding error message isin below function in dojo.js. _3a0.set = function setstyle(node,name,_3b2){ var n=dom.byid(node),l=arguments.length,op=(name=="opacity"); name=_3b1[name]?"cssfloat" in

c# - Get style attributes with regex from html string -

this html string: <p style="opacity: 1; color: #000000; font-weight: bold; font-style: italic; text-decoration: line-through; background-color: #ffffff;">100 gram n!uts</p> i want font-weight value, if there one. how do regex? this should solve it (?<=font-weight: )[0-9a-za-z]+(?=;) explaination: (?<=font-weight: ) string previous result has font-weight: [0-9a-za-z]+ result contains letters , digits, @ least one (?=;) first char after result ; code: string pattern = @"(?<=font-weight: )[0-9a-za-z]+(?=;)"; string value = "<p style=\"opacity: 1; color: #000000; font-weight: bold; font-style: italic; text-decoration: line-through; background-color: #ffffff;\">100 gram n!uts</p>"; string result = regex.match(value, pattern).value; //bold

To use %in% to a subset in R -

i have data 'data' in r contains 2 columns data$user_id = 323, 10, 2033, 112,... , data$value= 231, 4321, 90,.. futhermore dim(data)= 41000 2 i have vector u <- c(25,36,38,..) , length(u)=900 i want make subset of 'data' 'user_id' equal vector 'u'. in other words, want user_id's in u , entry in data. in r this newdata <- subset(data, data$user_id %in% u) to make sure have same type can this newdata <- subset(data, as.numeric(data$user_id) %in% as.numeric(u)) when type head(newdata) can see make sense , dim(newdata) = 900 2 want. but when type newdata printet data strange. how can be? subset uses non-standard evaluation. newdata <- subset(data, user_id %in% u)

visual studio - How do i Cross-compiling Qt for ARM boards like Raspberry Pi 2 & BeagleBoard-xm from Windows 7 -

i need compile qt applications developed in visual studio on windows 7 embedded boards. tried google not find enough documentation. you have setup tool chain arm rpi , bb-xm has arm processor. download qt opensource setup . set arch=arm cross_compile=arm_tool_chain- command run appropriate command setup qt in above format. for binaries arch=arm cross_compile=arm_tool_chain- command --prefix=path --build=?? --target==?? --host=?? to generate qt-binaries arm define path in above format , define build,host,target per configuration , run command generate binaries. place these binary in kernel .recompile , burn boards. that's ..now can run qt application in board. these commands should perform in cygwin or pre-installed vm linux distro. or can concepts https://konqueror.org/embedded/ may you.

persistence - Mesos & persistent storage using MySQL -

this going generic question. we young startup faced inevitable problem of scaling , during our research, apache mesos seemed fit our architecture, – core scala based microservices, each responsible dealing part of our database, mysql middleware microservices, deal other persistent data-storage systems mongodb, elasticsearch etc. which means can containerise of our services , ship them single datacenter can deploy these containers in topographically agnostic way. what stumped – mesos doesn't seem have native support mysql container based persistence seems awfully tricky , hard manage/maintain. we'd continue using mysql/mongodb/elasticsearch because migrating cassandra etc. @ stage (we small team) of overhead , hence not option. best strategies problem? mesos provide persistent resources support storage-like services . if want use mysql on mesos, please consider try https://github.com/apache/incubator-cotton

typescript - Referenced files compiled to output on save, but ignored on rebuild -

i have solution 2 projects - 1 class library , 1 asp.net mvc project. class library project contains typescript file. asp.net mvc project contains typescript file references file in class library: solution classlibrary scripts basefile.ts mvcproject scripts projectfile.ts projectfile.ts has ///reference declaration basefile.ts . in mvcproject properties, under typescript build page, have checked compile on save , , set combine javascript output file: scripts\projectfile.js . when edit projectfile.ts , save, output file in right place, emitted javascript referenced file ( basefile.ts ). however, when rebuild solution, javascript referenced file not emitted projectfile.js , javascript projectfile.ts . (build alone doesn't seem affect file; timestamp remains same.) i've tried including tsconfig.json in project, no avail. i using visual studio 2015 community , typescript 1.5.4 how can resolve this? update

python - Iterating over a csv reader object to call api with requests.get -

i have several hundred companies query api. api url call each in csv file in 1 column in form: http://api.duedil.com/open/search?q= {"company name"}&api_key=xxxxxxxxxxxxxx i've used csv open , read in csv file reader object can't work out how iterate on return details each company e.g. for row in reader: requests.get(row) running on single url works fine giving json data i'd expect: r = requests.get(url) apologies if bit of trivial seeming question how can iterate on each url in csv reader object feeding requests.get call , store result in file object of sort. thanks this csv.reader object prints out as: for row in reader: print(row) ['http://api.duedil.com/open/search?q={"parkeon ltd"}&api_key=xxxxxxx '] ['http://api.duedil.com/open/search?q={"m , d foundations , building services ltd"}&api_key=xxxxxxxxx '] ['http://api.duedil.com/open/search?q={"tm lewin"}&api_key=xxxxxx '

html - How to move a svg element? -

am new web application development , trying move svg element , have problems....here code reference. <!doctype html> <html> <body> <svg width=500 height=500> <circle cx="200" cy="200" r="100" stroke="black" stroke-width="4" fill="black" /> <g transform="translate(200,200)"> <line x1="0" y1="0" x2="100" y2="0" style="stroke:rgb(255,255,255);stroke-width:2"> <animatetransform attributename="transform" attributetype="xml" type="rotate" from="0" to="360" dur="100s"/> </line> </svg> </body> </html> copy paste & try it,to clear context and requirement want rotate "line&

c++ - How to get the move constructor calling deliberately -

this question has answer here: what copy elision , return value optimization? 4 answers consider following code: class base { public: int bi; base() : bi(100) {std::cout << "\nbase default constructor ...";} base(int i) : bi(i) {std::cout << "\nbase int constructor: "<< bi;} base(const base& b) {std::cout << "\nbase copy constructor";} base(base&& b) {std::cout << "\nbase move constructor";} }; base getbase() { cout << "\nin getbase()"; return base(); } int main() { base b2(getbase()); base b3 = base(2); base b4 = getbase(); } in spite of rvalues being given, none of above constructions in main calling move constructor. there way ensure user defined move constructor called? here getting: in getbase() ba

java - OnDragListener Fires Several Times? -

i have several layouts; each containing textview . if user drags textview unto textview , i'm going execute method swapfamily() it fires several times, depending on number of families . familyitemlayout custom linearlayout string attribute attached , add'tl getters , setter attribute. however, issue that, private class ondropfamily implements view.ondraglistener { @override public boolean ondrag(view view, dragevent event) { textview txtdragged = (textview) event.getlocalstate(); textview txttarget = (textview) view; string familydragged = ((familyitemlayout) txtdragged.getparent()).getfamily(); string familytarget = ((familyitemlayout) txttarget.getparent()).getfamily(); switch (event.getaction()) { // signals start of drag , drop operation. case dragevent.action_drag_started: break; // signals view drag point has entered bounding box of view. case

find - Java: Style-Correcting Code: finding comment -

i'm writing these algorithms style-correcting program makes adjustments java source file, can compile without error. set read file line-by-line. right now, i'm having trouble writing 2 methods/algorithms which determine if current line (string) has comments, and finds comment starts i have: public static int findcomment (string textline) { int endofcode = textline.lastindexof("; "); return textline.indexof("//", endofcode); } public static boolean hascomment (string textline) { if (textline.contains("//")) { return true; } else { return false; } } i know incorrect because can have code, , comments, contain " ; // ; //" comments. tried other conditional statements without success. hello don't explain problem have think should escape backslash characters when

Node.js fs: detecting when outStream finishes writing -

i'm using node zlib.creategzip compress huge string. using streams, following operation. know when outstream finished writing data can invoke callback. know how detect instream 'end' event can't find equivalent writable outstream. any suggestions? var gzoption = { level: zlib.z_best_compression, memlevel: zlib.z_best_compression } var gzip = zlib.creategzip(gzoption) inputstream = fs.createreadstream(filepath); outstream = fs.createwritestream(gzfilepath); inputstream.pipe(gzip).pipe(outstream); did try listening finish event of writeable stream? it's documented here: https://nodejs.org/api/stream.html#stream_event_finish when end() method has been called, , data has been flushed underlying system, event emitted.

python - Execute coroutine from `call_soon` callback function -

i have following situation: some internal class (which have no control of) executing callback function using call_soon . within callback call courotune, end "frozen" callback. i use modified hello world call_soon() demonstrate this: import asyncio def hello_world(loop): print('hello') # call coroutine. yield asyncio.sleep(5, loop=loop) print('world') loop.stop() loop = asyncio.get_event_loop() # schedule call hello_world() loop.call_soon(hello_world, loop) # blocking call interrupted loop.stop() loop.run_forever() loop.close() when run this, nothing being printed , program never ends. ctrl+c traceback (most recent call last): file "../soon.py", line 15, in <module> loop.run_forever() file "/usr/lib/python3.4/asyncio/base_events.py", line 276, in run_forever self._run_once() file "/usr/lib/python3.4/asyncio/base_events.py", line 1136, in _run_once event_list = se

eclipse - Renaming packages in the project -

i have big eclipse web project hundreds of packages, have rename of packages without hurting functionality in code. there fast , precise way ? using java ee -eclipse luna. in advance. you can use refactor > rename .

html5 - want to give placeholder 2 different colors -

is there trick can make placeholder 2 different colors, here code <input type="text" class="form-control setting-form" id="inputdefault2" placeholder="http://blabbr.im/#itsmynewawesomechat"> i want give "blabbr.im/" color rgba(255,255,255,0.3) , "#itsmynewawesomechat" color rgba(255,255,255,1)... there no way style placeholder 2 different colors. alternative, style both <label> , <input> single <input> (or other tag <span> ). label, input { background-color: #4679bd; border: 1px solid #567890; float: left; font-family: sans-serif; font-size: 14px; line-height: 1.4; padding: 2px 5px; } label { border-radius: 2px 0 0 2px; border-right: 0; color: rgba(255,255,255,0.3); padding-right: 0; } input { border-radius: 0 2px 2px 0; border-left: 0; } ::-webkit-input-placeholder {

c# - fakepath while File Upload -

i using jquery upload file on server gets replaced fakepath : my path should "c:\users\download\filename.xls" gets replace "c:\fakepath\filename.xls" i used approach solve above problem : var selectedpath = $('input#filedata_file').val().split('\\').pop(); //filename.xls but gives filename , eliminates path , how fullpath filename. var srccontent; // give file function readurl(input) { if (input.files && input.files[0]) { var reader = new filereader(); reader.onload = function (e) { srccontent = e.target.result; } reader.readasdataurl(input.files[0]); } } $("#inputfile").change(function () { if (this.files[0].name != "") { readurl(this); } });

javascript - Ionic application for windows phone -

i developing app using ionic framework.i have successful developed app android , ios.now going windows phone: when add platform using: ionic platform add wp8 i got error module.js:338 throw err; ^ error: cannot find module 'q' @ function.module._resolvefilename (module.js:336:15) @ function.module._load (module.js:278:25) @ module.require (module.js:365:17) @ require (module.js:384:17) @ object.<anonymous> (/home/.cordova/lib/npm_cache/cordova-wp8/3.8.1/package/bin/lib/create.js:20:13) @ module._compile (module.js:460:26) @ object.module._extensions..js (module.js:478:10) @ module.load (module.js:355:32) @ function.module._load (module.js:310:12) @ module.require (module.js:365:17) error: /home/.cordova/lib/npm_cache/cordova-wp8/3.8.1/package/bin/create: command failed exit code 1 @ childprocess.whendone (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/superspawn.js:139:23) @

How do we do DNS query in Python -

how dns query, expecially mx query, in python not installing third party libs. i want query mx record domain, however, seems socket.getaddrinfo can query record. i have tried this: python -c "import socket; print socket.getaddrinfo('baidu.com', 25, socket.af_inet, socket.sock_dgram)" this prints [(2, 2, 17, '', ('220.181.57.217', 25)), (2, 2, 17, '', ('123.125.114.144', 25)), (2, 2, 17, '', ('180.149.132.47', 25))] however, can not telnet telnet 220.181.57.217 25 or telnet 123.125.114.144 25 or telnet 180.149.132.47 25 . first install dnspython import dns.resolver answers = dns.resolver.query('dnspython.org', 'mx') rdata in answers: print 'host', rdata.exchange, 'has preference', rdata.preference

javascript - How to change iframe src use angularjs -

<iframe src="{{url}}" width="300" height="600"> <p>your browser not support iframes.</p> </iframe> how change iframe src you need $sce.trustasresourceurl or won't open website inside iframe: jsfiddle html: <div ng-app="myapp" ng-controller="dummy"> <button ng-click="changeit()">change it</button> <iframe ng-src="{{url}}" width="300" height="600"></iframe> </div> js: angular.module('myapp', []) .controller('dummy', ['$scope', '$sce', function ($scope, $sce) { $scope.url = $sce.trustasresourceurl('https://www.angularjs.org'); $scope.changeit = function () { $scope.url = $sce.trustasresourceurl('https://docs.angularjs.org/tutorial'); } }]);