Posts

Showing posts from January, 2014

Array of bytes from View in android -

i have drawing view, , trying array of bytes view on button click this code: public void onclick( drawview.setdrawingcacheenabled(true); string imgsaved = mediastore.images.media.insertimage( getcontentresolver(), drawview.getdrawingcache(), uuid.randomuuid().tostring() + ".png", "drawing"); } } please help! if view imageview first convert bitmap convert byte array convert imageview bitmap public static bitmap getimageviewasbitmap(imageview imageview) { imageview.builddrawingcache(); bitmap bmap = imageview.getdrawingcache(); return bmap; } convert bitmap byte array public byte[] getbitmapasbytearray(bitmap bitmap) { bytearrayoutputstream outputstream = new bytearrayoutputstream(); bitmap.compress(compressformat.png, 0, outputstream); return outputstream.tobytearray(); } convert byte array bitmap public s

javascript - Transform data before rendering it to template in meteor -

i want return single document fields joined together. is, result follows { _id: "someid", name: "odin", profile: { game: { _id: "gameid", name: "world of warcraft" } } } i have route controller simple. usercontroller = routecontroller.extend({ waiton: function () { return meteor.subscribe('users'); }, showallusers: function () { this.render('userlist', { data: meteor.users.find() }) } }); i've tried changing data so: this.render('userlist', { data: meteor.users.find().map(function (doc) { doc.profile.game = games.findone(); return doc; }) }); however, not have intended effect of adding "game" user. (and yes, games.findone() has result) how can transform results of cursor in meteor , iron:router? try defining data function can dynamically re-executed when needed. usercontroller = routecontroller.extend({ waiton

PHP - Check if a foldername exists in the current page url -

i use php check if current page url has specific folder name , if echo hello for example: check if domain below has word: newyork http://www.domain.com/en/newyork/carrental/ as seen above word newyork exists , therefore need echo (hello) use $res = get_headers ( $url ) if (strpos($res[0],"200 ok")) { } more detailed information here: http://php.net/manual/en/function.get-headers.php

process - Monitoring android processes -

i working on project in monitoring of processes required (creation of process...). can running processes api activitymanager::getrunningappprocesses() . but calling above api every few seconds (polling) not efficient way. there way in android system through intimated create of new app process? information or guidance helpful. thanks. found monitoring zygote task able monitor creation of new process. monitor "/proc/zygotepid/task" folder. not give when created app(process) brought foreground. give information creation of new process. replace zygotepid actual pid of zygote in system. since every process created zygotepid, getting parent process id in application give zygotepid

shell - Unix script how to extract string from a file -

how extract value after 4th slash ( / ) /ftp-test/testautoupdate/test/1/x64 ? the extracted result example should 1 awk -f'/' '{print $5}' file kent$ echo "/ftp-test/testautoupdate/test/1/x64"|awk -f'/' '{print $5}' 1

sails.js - Skipper resize image before uploading using adapter -

i have similar question this one . how can have upload rackspace adapter well? here's code: upload: function(req, res){ var rackspaceadapter = require('../adapters/rackspace/index'), receiver = rackspaceadapter.receive({ username: sails.config.rackspace.username, apikey: sails.config.rackspace.apikey, region: sails.config.rackspace.region, container: sails.config.rackspace.container }); req.file('file').upload(function (err, uploadedfiles) { if (err) return res.send(500, err); for(u in uploadedfiles){ gm(uploadedfiles[u]).resize('500','','^').gravity('center').crop('500','500').stream().pipe(receiver); } return res.json({ message: uploadedfiles.length + ' file(s) uploaded successfully!', files: uploadedfiles

ios - How do I change the background color of the text in view of the UIPickerView with multiple components when a valid selection is made, in Swift -

below code change background color of uipickerview cyan showing valid selection when total of row indexes = 6. have pickerlabel background in view(selected) turn cyan instead in 4 components when selection valid. idea? import uikit class viewcontroller: uiviewcontroller, uipickerviewdatasource, uipickerviewdelegate { @iboutlet weak var mypicker: uipickerview! let pickerdata0 = ["0r","1r","2r","3r","4r","5r","6r"] let pickerdata1 = ["0b","1b","2b","3b","4b","5b","6b"] let pickerdata2 = ["0y","1y","2y","3y","4y","5y","6y"] let pickerdata3 = ["0g","1g","2g","3g","4g","5g","6g"] override func viewdidload() { super.viewdidload() // additional setup after loading view,

IPC/RPC for communication between R and Python -

summary i'm looking ipc/rpc protocol which: has libraries in both r , python 2.7 work on windows allows me pass data , make calls between 2 languages does not embed 1 language inside other (i want use python , r in favourite ides, not embedding bits of r expression strings in python code, vice/versa) supports circular references supports millisecond time data fast , efficient when need pass large amounts of data i have seen this similar question , unlike op question, do not want use r in pythonic way. want use r in r way in rstudio ide. , want use python in pythonic way in pycharm ide. want pass data or make calls between 2 languages, not blend languages one. does have suggestions? background i use both python , r interactively (by typing console of favourite ide: pycharm , rstudio respectively). need pass data , call functions between 2 languages ad-hoc when doing exploratory data analysis. instance, may start processing data in python, later stumble ac

Workload Scheduler for Node.js script - is it equivalent to cron jobs in Bluemix? -

i'm trying call node file.js bluemix workload scheduler every morning; file.js in root of node.js project; file.js not server file. used use cron seems "bluemix doesn't have concept of cron jobs." as result (only) step of process, got "node : command not found" i think missed something. possible workload scheduler or should find alternative options? more information i'm trying : var wls = new workloadservice(credentials); var wp = new waprocess("myprocessname", "descriptionprocess"); wp.addstep(new commandstep("node file.js", myagentname)); wp.addtrigger( triggerfactory.repeatdaily(1) ); wls.createandenabletask(wp, function(res){ wls.runtask(res.id, function(){console.log("process created , started.")}); }); i can see in "ibm workload automation on cloud - application lab" process created , started. few later, process has failed saying "node command not found" i think re

Spring Hibernate get tuple by id -

i trying create simple "teacher" database. able create method adding new teacher database, need able 1 , delete 1 "id". help, of how should implement it. have added following code files: appconfig, teacher (entity class), iteacherdao (interface), teacherdao(implementation of interface) , class main method timestarapplication. appconfig package com.superum.timestar; import javax.sql.datasource; import org.apache.commons.dbcp.basicdatasource; import org.hibernate.sessionfactory; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import org.springframework.orm.hibernate4.hibernatetemplate; import org.springframework.orm.hibernate4.hibernatetransactionmanager; import org.springframework.orm.hibernate4.localsessionfactorybuilder; import org.springframework.transaction.annotation.enabletransactionmanagement; import com.superum.timestar.dao.iteacherdao; import com.superum.timestar.dao.teacherdao; import

ios - How to add overlay path in MKMapView swift -

i want add overlay path among multiple coordinates in mapview. tried below code, shows error of "cannot invoke 'map' argument list of type ((cllocation) -> cllocationcoordinate2d)". please let me know how can fix ? my viewcontroller.swift file import uikit import mapkit class viewcontroller: uiviewcontroller, mkmapviewdelegate{ @iboutlet weak var mapview: mkmapview! override func viewdidload() { super.viewdidload() //for location 1 let location1 = cllocationcoordinate2d( latitude: 51.481188400000010000, longitude: -0.190209099999947280 ) let annotation1 = mkpointannotation() annotation1.coordinate = location1; annotation1.title = "chelsea" annotation1.subtitle = "chelsea" let span = mkcoordinatespanmake(0.15, 0.15) let region1 = mkcoordinateregion(center: location1, span: span) mapview.setregion(region1, animated:

angularjs - Go back to N'th "page" of a page in Angular -

there page thumbnails. @ bottom there have "show more" button loads more thumbnails. user can click on thumbnail , re-direct application details. when user clicks browser's "back" him land in same position before. how achieve without complex routing? you can achieve using angular-bootstrap-lightbox , ui-bootstrap pagination . both angular , use common resources edit: what you're looking along lines of scroll-sneak , want save scroll position when redirect page , load last position when redirect back. since not find angular directive so, can either get 1 , wrap around directive, of them use jquery you can make own. for example, can use js define queue array , store in localstorage/sessionstorage, when redirect "push" current page location queue, when redirect back, "pop" last stored position. maintain scroll position of large html page when client returns

f# - How can I reference FakeLib.dll in a Fake.Deploy deployment script? -

i'm trying reference fakelib.dll local fake.deploy installation in deployment script can't seem find correct path use. found environment.currentdirectory points fake.deploy installation, using #r @"fakelib.dll" doesn't work: deploy messages { 2015-05-12 09::22:50.413 2015-05-12 09::22:50.417 2015-05-12 09::22:50.417 install.fsx(2,1): error fs0082: not resolve reference. not locate assembly "fakelib.dll". check make sure assembly exists on disk. if reference required code, may compilation errors. (code=msb3245) 2015-05-12 09::22:50.432 2015-05-12 09::22:50.432 2015-05-12 09::22:50.433 install.fsx(2,1): error fs0084: assembly reference 'fakelib.dll' not found or invalid } examples found on web suggest deploy fake along application in nuget package , reference this: #r @"tools\fake\tools\fakelib.dll" but seems overkill , unnecessary reference. does know path use reference local fake.deploy installation?

java - Ability to rollback changes when insert data using a server API -

i have following situation: i have build client java application, used communicate mysql database directly. when inserting lot of data, used autocommit turned off. easy do, because had direct access connection . had chosen this, because enabled me rollback changes when went wrong during synchronization. now, application evolving , thought better build server api communicates mysql database. so, @ moment, inserting data doing http requests. each request opens , closes new connection . now, able rollback changes when 1 of requests goes wrong. assume can not work autocommit , because based on connection , , 1 different each request. can tell me how done usually? i have thought of following: first call url sets autocommit false, , requests , check if 1 fails. go wrong if client inserting data @ same time. sending data server 1 request, force me alter design drastically. note: know code required when asking question, can not see how improve question. however, if neede

php - merge two array with the same key and value -

i have arrays of $array_one: print_r($array_one); array ( [0] => stdclass object ( [myid] => 653509 [date] => 2015-03-15 00:07:03 ) [1] => stdclass object ( [myid] => 653511 [date] => never ) [2] => stdclass object ( [myid] => 653530 [date] => 2015-03-15 02:06:26 ) and arrays of $array_two; print_r($array_two); array ( [0] => stdclass object ( [myid] => 653530 [pin] => 12fdg34345 ) [1] => stdclass object ( [myid] => 653509 [pin] => 1we2534dgf5 ) [2] => stdclass object ( [myid] => 653511 [pin] => 12wer3u45 ) and want merge based on keys same value, in expected result be: array ( [0] => stdclass object ( [myid] => 653530

Can not open Visual Studio C# solution after upgrading from VS2010 to VS2013 (or VS2012), error message "The given path's format is not supported" -

i had upgrade legacy project visual studio 2010 visual studio 2013. when in vs 2013 tried load solutions, showed migration report warnings (and no errors!) - warnings ­visual studio needs make non-functional changes project in order enable project open in visual studio 2013, (..) . and in visual studio solution explorer, output window see error message the given path's format not supported. , result solution not loaded. i tried find information path's format error message , seems it's file names/directories, can't find has gone wrong during solution loading/migration. any ideas wrong/what should check? it project create sql clr assembly, , turns out project type (visual c# sql clr database project) no more available in visual studio 2012 , visual studio 2013

Why these strings are not translated by Qt 5 -

Image
i'm porting qt4 project qt5 (qt 5.4.1 + vs2013), project have string translations. source file utf-8 encoded. today found piece of code won't work (they worked in qt4). this->paralist.push_back( qpair<qstring,qstring>( qstring(tr("℃:")), qstring(tr("Ω")) ) ); 'paralist' qlist, , strings in shown in qtablewidget. both show correctly in qliguist, when application run, centigrade symbol , ohm symbol don't translated correctly, below but other strings translated correctly. locale zh_cn. why these 2 characters so special ? problem encoding. using non ascii characters translation pattern. there change in qt5 how c-strings converted (i don't remember details) , i'm suspecting might problem. try use trutf8 should fix problem.

How can I save a variable from a database and use it in C#? -

i changing program , need because don't know c#. change things with: strsql = "update materials set "; strsql = strsql + "dscr = 'concrete', "; strsql = strsql + "width=50 "; strsql = strsql + " id=385"; objcmd = new oledbcommand(strsql, db_def.conn); objcmd.executenonquery(); there case need find id, store , use again. use select oledbcommand cmd = new oledbcommand("select id materials type=1", db_def.conn); oledbdatareader reader = cmd.executereader(); if (reader.hasrows) { reader.read(); var result = reader.getint32(0); } strsql = "update materials set "; strsql = strsql + "dscr = 'concrete', "; strsql = strsql + "width=50 "; strsql = strsql + " id=result"; objcmd = new oledbcommand(strsql, db_def.conn); objcmd.executenonquery(); but error: no value given 1 or more required parameters. you can try , tell me if works o

regex - find and replace strings in files in a particular directory -

i have pattern need replace in .hpp , .h , .cpp files in multiple directories. i have read find , replace particular term in multiple files question guidance. using this tutorial not able achieve intend do. here pattern. throw some::lengthy::exception(); i want replace this throw createexception(some::lengthy::exception()); how can achieve this? update: moreover, if some::lengthy::exception() part variant such changes every search result ? throw some::changing::text::exception(); will converted throw createexception(some::changing::text::exception()); you can use sed expression: sed 's/throw some::lengthy::exception();/throw createexception(some::lengthy::exception());/g' and add find command check .h , .cpp , .hpp files (idea coming list files extensions ls , grep ): find . -iregex '.*\.\(h\|cpp\|hpp\)' all together: find . -iregex '.*\.\(h\|cpp\|hpp\)' -exec sed -i.bak 's/throw some::lengthy::exception

c# - Confirm email doesn't work -

i'm working asp.net mvc5 project , want users confirm email before login webpage. did manage when user register user email. did manage make when user clicks link in email confirmed in database. so, problem. want them confirm email before can login. here code trying achieve this. // post: /account/login [httppost] [allowanonymous] [validateantiforgerytoken] public async task<actionresult> login(loginviewmodel model, string returnurl) { if (!modelstate.isvalid) { var user = await usermanager.findasync(model.username, model.password); if (user != null) { if (user.emailconfirmed == true) { await signinasync(user, model.rememberme); return redirecttolocal(returnurl); } else { modelstate.addmodelerror("", "confirm email address."); } } e

filtering - Google Custom Search - filter data from within a page -

i using google custom search enable users search within website. have 1 page displays list of references (to scientific publications) other content (dynamic). display results references including search term filtered own tab - can see how label whole page, not section of page. means can filter 'references', other content in results, not references. there way of doing this? yes, possible suppose. , had done sometime , had worked expected. have @ these links - tech republic set google custom search , google custom search

php - How to run a sql query in solr -

Image
ok have install solr , index database following structure : db_name - solr, table - users my db-data-config.xml file : <dataconfig> <datasource type="jdbcdatasource" driver="com.mysql.jdbc.driver" url="jdbc:mysql://localhost:3306/solr" user="root" password="" /> <document> <entity name="users" query="select id,name users;" /> <field column="id" name="id" /> <field column="name" name="name" /> </document> </dataconfig> which returns rows of database table users. problem 1 : but should if want search 'rakesh shetty' , should return result "rakesh vasant shetty" ? i have tried <entity name="users" query="select id,name users name '%rakesh shetty%' ;" /> returns empty result. problem 2 : also

python - Exporting DOORS Objects to csv files with dxl wont write all objects? -

i wrote script doors 9.5 looks in doors module specific objects , writes them in csv-file. after specific number of lines stops writing in csv-file , got half of requested objects. i'm using string replacement function found in internet. thats maybe problem or there kind of maximum dxl write in csv files? would nice if me this, because cant find solution in internet or understand why wont work. // string replacement function string replace (string ssource, string ssearch, string sreplace) { int ilen = length ssource if (ilen == 0) return "" int ilensearch = length(ssearch) if (ilensearch == 0) { print "search string must not empty" return "" } // read first char latter comparison -> speed optimization char firstchar = ssearch[0] buffer s = create() int pos = 0, d1,d2; int while (pos < ilen) { char ch = ssource[pos]; bool found = true if (ch != firstchar) {pos ++; s+= ch; continue} (i = 1; < ilen

mongodb - Detecting concurrent data modification of document between read and write -

i'm interested in scenario document fetched database, computations run based on external conditions, 1 of fields of document gets updated , document gets saved, in system might have concurrent threads accessing db. to make easier understand, here's simplistic example. suppose have following document: { ... items_average: 1234, last_10_items: [10,2187,2133, ...] ... } suppose new item (x) comes in, 5 things need done: read document db remove first (oldest) item in last_10_items add x end of array re-compute average* , save in items_average . write document db * note: average computation chosen simple example, question should take account more complex operations based on data existing in document , on new data (i.e. not solvable $inc operator) this easy implement in single-threaded system, in concurrent system, if 2 threads follow above steps, inconsistencies might occur since both update last_10_items , items_average values without considerin

javascript - endDate showing as Invalid Date using Daterangepicker -

i using daterangepicker select startdate , enddate. startdate works fine enddate shows invalid date. here code: var dateformat = "d mmm yyyy"; var displaydate = function() { var dateformat = "d mmm yyyy"; var begin = moment($("#add-start-date").val()); var end = moment($("#add-end-date").val()); if( begin !== null && end !== null ) { $("#add-start-date").parent().removeclass("hidden"); $("#add-start-date").parent().siblings().removeclass("hidden"); } else if( begin !== null ) { $("#add-start-date").parent().removeclass("hidden"); $("#add-start-date").parent().siblings().addclass("hidden"); } if (begin !== null){ $("#add-start-date").html(begin.format(dateformat)); }

point cloud librarby on visual studio 2012 -

i have problem during instalation of pcl visual studio 2012. can describe me exactly, should (step step) because tutorials have watched don't contains informations configuration of library. i tried install pcl 1.7.2 allinone , use cmake 3.2, didn't work. cmake gives information files missing. , during instalation of pcl not appear file: cmakelist, required cmake used file provided on github: https://github.com/pointcloudlibrary/pcl.git i use pcl 1.7.2 , vs2012 in win8.1. it's difficult compile pcl scratch. answer: point cloud library on visual studio

c# - How to work with SQL Server stored procedures using Entity Framework -

i'm new programming using stored procedures , entity framework. have created sql server database table called dbo.book hold book title , auto incremental id column. i have created stored procedure insert record dbo.book , return id column value of newly entered record: use [testing1db] go set ansi_nulls on go set quoted_identifier on go create procedure dbo.uspaddbook @title nvarchar(50), @bookid int output begin set nocount on; insert dbo.book (title) values (@title) select @bookid = @@identity end when move visual studio , add entity framework data model c# windows forms project using existing database, generates ...context.cs code related stored procedure follows: public virtual int uspaddbook(string title, objectparameter bookid) { var titleparameter = title != null ? new objectparameter("title", title) : new objectparameter("title", typeof(string)); retur

python - How to delete synonyms? -

i'm creating code on python 3.4.3. have linguistic program. part of code has delete next word if synonym of previous word. firstly, have create list of synonyms each word. transform our lists sets. eventually, have compare our lists check if have same synonyms. don't know how compare them. have keep 1 word if there synonym of next. from nltk.corpus import wordnet text = ['','',''] text4 = [] def f4(text): global text4 synonyms = [] sentence in text: d = ' ' sentence = sentence.split(d) word in sentence: syn = [] syn in wordnet.synsets(word): lemma in syn.lemmas(): syn.append(lemma.name()) synonyms.append(syn) synonyms2 = [] x in synonyms: x = set(x) synonyms2.append(x) my code has delete next word if synonym of previous word. i suggest different algorithm. here's example: text = 'run rac

java - How do I create custom field to store user credentials in REVINFO table -

we using hibernate-envers , having *_aud table stores historical state of entities. there global revinfo table contains revision number, timestamp. i need add user field in revinfo table. how add "user" field in revinfo table? you can create custom revisioninfo entity. custom revisions entity must have integer-valued unique property (preferably primary id) annotated {@link revisionnumber} , long-valued property annotated {@link revisiontimestamp}. the {@link defaultrevisionentity} has 2 fields, may extend it, may write own revision entity scratch. in case revision entity may following: @entity @revisionentity() public class revisionsinfo extends defaultrevisionentity { private long userid; public long getuserid() { return userid; } public void setuserid(final long uid) { this.userid = uid; } } in addition can give custom revisionlistener other special needs . see following example: public class revisionlistener implements org.hibernate.enver

functional programming - Evaluate a list of functions in Clojure -

i have list of functions have no side-effects , take same arguments. need evaluate each function in list , put results list. there function in clojure it? (map #(% arg) function-list) should job?

android - What should be used to substitute BasicNameValuePair in building URL? -

i using below code build url networking. have been using basicnamevaluepair , urlencodedutils build url since android 5.0 both have been deprecated. shall use create url? list<namevaluepair> pairs = new arraylist<namevaluepair>(); pairs.add(new basicnamevaluepair("appid", "0000000000000000")); pairs.add(new basicnamevaluepair("lat", string.valueof(latitude))); pairs.add(new basicnamevaluepair("lon", string.valueof(longitude))); pairs.add(new basicnamevaluepair("type", "accurate")); pairs.add(new basicnamevaluepair("units", "metric")); // create new url url url = new url("http://api.openweathermap.org/data/2.5/weather" + "?" + urlencodedutils.format(pairs, "utf-8")); @samvid ...use volley library public static void postnewcomment(context context,final

javascript - jQuery: Checked event on checkbox added later through innerHTML is not working. -

this question has answer here: event binding on dynamically created elements? 18 answers there 2 checkboxes in page change event i'm capturing in below code: $(':checkbox').change(function(){ alert('hello '+this.checked); }); but if add third checkbox group , click checkbox, above function not triggered. i adding third checkbox group through innerhtml code below: var text2='<li><input type="checkbox" name="vehicle" value="true"/><a href="#"> new function</a></li>'; text1=text1+' '+ text2; parent.innerhtml=text1; note: text1 existing innerhtml code of existing 2 checkboxes. use event delegation. use on method. attach event handler function 1 or more events selected elements. $('document/parentselector').on('change

amazon ec2 - How to composite large images stored on S3 in ImageMagick from EC2 instances? -

i have ongoing list of image processing tasks do, using imagemagick composite large individual graphic files (20mb each). these images stored on s3 (approximately 2.5gb in total). i thinking use multiple ec2 instances process tasks, composite images , upload output file s3. the problem setup imagemagick needs file library local (on machine). images on s3, means each instance need download copy of images s3, slowing down whole process. what's best way share image library nodes? consider following points: you can processing of imagemagick files in memory "saving" input image in special format mpr: ( magick pixel register ). details see answer: " imagemagick multiple operations in single invocation " imagemagick can access remote images via http:// . you can put lot of imagemagick's operations 1 single command line can produce multiple output files, , can segment command line sub- or side-processes using parentheses syntax: ... \( im s

I want to get all nextPageTokens in python youtube data api -

i'm trying nextpagetoken in youtube data api below code, want nextpagetoken s. in loop, want reassign nextpagetoken def get_next_videos(): while true: r = requests.get("https://www.googleapis.com/youtube/v3/search?part=snippet&maxresults=50&channelid="+channelid+"&order=date&key="+developer_key) json_data = r.json() nextpagetoken = json_data.get("nextpagetoken") second_r = requests.get(&qu

javascript - How can I create a nested object from a list of keys and a value? -

i trying come script take array of keys , 1 value , return object: keys = ['a', 'b', 'c']; value = 'hello'; and trying this: {'a': {'b': {'c': 'hello'}}} my code: var data = {}; (var i=0; < keys.length; i++) { var key = keys[i]; if (i < keys.length -1) { if (data[key] === undefined) { data[key] = {}; } } else { data[key] = value; } data = data[key]; } also want make sure data contained in data value not erase whenever uses different key. you can use array.prototype.reduceright , this var keys = ['a', 'b', 'c']; var value = 'hello'; console.log(keys.reduceright(function (pastresult, currentkey) { var obj = {}; obj[currentkey] = pastresult; return obj; }, value)); // { a: { b: { c: 'hello' } } } reduceright process array right left. , everytime create new object , store old object against current key name.

javascript - How to get json data coming from ajax and show it prefilled in input box -

following code ii have used response in json . when add alert alert(response.subject); returns "undefined" html: <input type="text" id="subject" value='subject'> javascript: $.ajax({ url: "/ebays/prefilledcontentajax", type: "post", cache: false, async: true, data: { type: $("#type").val(), }, success: function (response) { console.log(response); // show json response returns. want show in input box prefilled data response return } }); please me out. you can use val set value in textbox $('#subject').val(response[0].subject); also, might want change ajax call: $.ajax({ url: "/ebays/prefilledcontentajax", type: "post", cache: false, async: true, data: { type: $("#type").val(), }, datatype: "json", // ^^^^^^^^^^^^^ success: function (response) {

javascript - is there is any easy way to detect attr jquery -

i trying detect if element has attribute not specific . wanna know if there . , if there attr want remove themm , add new attributes . , if there not new attributes added only. my codes are if ($('.element').attr('style').length > 0) { $(this).removeattr('style'); } $('.element').css({ "top": (posy), "left":(posx) }); but in console shows uncaught typeerror: cannot read property 'length' of undefined can 1 help? try this, if($('.element').attr('style') && $('.element').attr('style').length > 0){ $('.element').removeattr('style'); } $('.element').css({ "top": (posy), "left": (posx) });

linux - It is possible to load list perl modules depending on conditional statements? -

this question has answer here: how can conditionally use module in perl? 3 answers (correct me if ask question in wrong way). i making standard/generic way simplify scripts/app making in linux using perl. i found solution make standard sub routines , calling them file of standard jobs want have (variable declarations/checkers/etc). now last problem have how call different set of modules(tk, dbi, etc..) need calling them file. not that. made flags activate contents standard/generic sub routines, want conditions applied when activating list of modules based on flag. meaning based on flag declared, list of modules needs activated activated. how that? :) additional details. not modules made using .pm, perl modules like: use net::domain qw(hostname hostfqdn hostdomain); use time::local; use time::piece; use switch; use exporter; #use strict; use file::b

ios - Alamofire Priority Queue -

i using alamofire networking library swift app. there way keep "priority queue" of network requests alamofire? believe saw feature in library in past can no longer find or find other posts this. let's open page in application , starts make few requests. first gets json, fast , no problem. from json, pulls out information , starts downloading images. these images have potential quite large , take many seconds (~30 seconds or more sometimes). tricky part user has option move on next page before image(s) finish downloading. if user moves on next page before image downloading done, possible move on lower priority queue? when images on next page start loading go faster? open pausing old 1 entirely until new requests finished if possible. keep in mind open many suggestions. have lot of freedom implementation. if different library, or different mechanism in ios fine. if continue use alamofire json , image downloading , management else alright too. also, irrelevant

python - Query Python3 script to get stats about the script -

i have script continually runs , accepts data (for familiar , if helps, connected emdr - https://eve-market-data-relay.readthedocs.org ). inside script have debugging built in can see how data in queue threads process, built used printing console. able either run same script additional option or totally different script return current queue count without having enable debug. is there way please point me in direction of documentation/libaries need research? there many ways solve this; 2 come mind: you can write queue count k/v store (like memcache or redis) , have script read , whatever other actions required. you can create specific logger informational output (like queue length) , set log somewhere else other console. example, use send email or log external service, etc. see logging cookbook examples.

drop down menu - I want to disable it as soon as a value from dropdown has been selected -

i have drop down menu few options , want enable selected portion , disable other portions once select value dropdown using php. are looking this? var ddl = $('#test'); ddl.on('change', function() { if (ddl.find('selected').val() != '') { ddl.prop('disabled', true); } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select id='test'> <option value=''>select</option> <option value=''>a</option> <option value=''>b</option> <option value=''>c</option> </select>

How can one import the whole webDriver project in an executable form so that anybody else can run the suite by just a click.? -

i relatively new selenium webdriver , self learner. have created webdriver project consists of different packages , have made use of page factory concepts extensively. use testng framework run suite generate report. test cases following testng framework concepts. team wants use script run @ every build test sanity. build team wants run whole script click. can shell script command or .exe or jar. build team uses linux m/c , dont have ecplise , testng installed in machine. intention whenever build given want run script click or command in command prompt.( has simple them) , report should generated in location in hdfs my script runs on ff version 32 , selenium webdriver 2.44.0 would appreciate if give me solution works requirement. i found similar query not sure if answer still suits. how make java executable jar file of webdriver project could please give me solution. or solution mentioned in above link stil best? regards there few ways it: use ci tool (je

java - Properly using toString to print array? -

this question has answer here: how print java object without getting “sometype@2f92e0f4”? 8 answers i have array need print, , i've looked through stackoverflow know need use tostring don't print hashcode, reason it's still printing stuff " music2.music2@4162b8ce , music2.music2@3852fdeb , music2.music2@509c6c30 " music2[] musiclist = new music2[10]; musiclist[0] = new music2("pieces of you", "1994", "jewel"); musiclist[1] = new music2("jagged little pill", "1995", "alanis morissette"); musiclist[2] = new music2("what if it's you", "1995", "reba mcentire"); musiclist[3] = new music2("misunderstood", "2001", "pink"); musiclist[4] = new music2("laundry service", "2001", "shakira"); musiclist[5

Calculating the MSE with a RGB and grayscale image in MATLAB - Image Processing -

how calculate mse rgb , grayscale image in matlab? have written code here: i = imread('iris.jpg); gray = rgb2gray(i); n = size(i); m = n(1); n = n(2); mse = sum(sum(i-gray).^2))/(m*n); fprintf('\nmse:%7.2f',mse); however, when run code, error: error using - matrix dimension must agree. how fix error? i'm not sure why you'd want this.... since grayscale , colour images different each other in terms of colour values. the error you're getting quite clear. grayscale image has 1 channel while rgb image has three. trying subtract images of incompatible dimensions , error. however, if mse calculation want, need make sure grayscale image has 3 colour channels. grayscale images have red, green , blue components equal, , simple fix repmat should trick. can use duplicate grayscale image on multiple channels simulate colour image. do gray variable before computing mse: gray = repmat(gray, [1 1 3]); as such, doing this. btw there typo in

javascript - Callback for $.post cannot access this -

i'm beginner in javascript/jquery, etc. , i'm facing little problem maybe me solve. have object prototype name page , in there array , function ajax post , process answer. code looks this: function page( url ){ this.url = url; this.elarr = []; this.addelem = function( elem ){ this.elarr.push( elem ); } this.job = function(){ $.post( this.url, { // data here... }, function( data, status ){ var decodeddata = json.parse( data ); this.elarr[0].value = decodeddata.value; // error: elarr not defined }); } }; i like: var page = new page( 'page.php' ); page.addelem( new elem ); elem prototype .value . the php code on server side answers correctly post request. using chrome development tools, can step javascript code , decoded json answer correct. problem arises when tries access this.elarr[0] (yes, in page1, elarr[0] exists!) ex

node.js - about pm2 reloadLogs and log-date-format -

i using pm2 version 0.12.9 i start app using command: pm2 start bin/www --name gototravel --log-date-format="yyyy-mm-dd hh:mm z" then query pm2 logs ll ~/.pm2/logs -rw-rw-r-- 1 wucho wucho 0 may 12 11:03 gototravel-error-0.log -rw-rw-r-- 1 wucho wucho 1822 may 12 11:03 gototravel-out-0.log my first question don't see log file prefixed timestamp. then run pm2 reloadlogs and query pm2 logs,but no log generated ll ~/.pm2/logs -rw-rw-r-- 1 wucho wucho 0 may 12 11:03 gototravel-error-0.log -rw-rw-r-- 1 wucho wucho 1822 may 12 11:03 gototravel-out-0.log i nodejs newbee , give me suggestions? s --log-date-format prefix entries in log files, not prefix log file names. reloadlogs doesn't rotate logs you. causes log file recreated if it's been rotated out under program process.

OpenCV Android - error on match template -

i've seen questions here related error such this , this , know can't execute imgproc.matchtemplate() method if image , template don't have same datatype. i'm still confused on how know type of mat i'm using. below code adapted example here : for (int = 0; < 24; i++) { arrdraw[i] = getresources().getidentifier("let" + i, "drawable", getpackagename()); } mat mimage = input.submat(bigrect); (int = 0; < 24; i++) { mat mtemplate = utils.loadresource(this, arrdraw[i], highgui.cv_load_image_color); mat mresult = new mat(mimage.rows(), mimage.cols(), cvtype.cv_32fc1); imgproc.matchtemplate(mimage, mtemplate, mresult, match_method); core.normalize(mresult, mresult, 0, 1, core.norm_minmax, -1, new mat()); ... // further process } so i'm trying take mimage submat of inputframe , match template process 24 other pictures , decide has best value (either lowest or highest). yet error shows this. opencv error: