Posts

Showing posts from May, 2015

python - Different ways of deleting lists -

i want understand why: a = [] ; del a ; and del a[:] ; behave differently. i ran test each illustrate differences witnessed: >>> # test 1: reset = [] ... >>> = [1,2,3] >>> b = >>> = [] >>> [] >>> b [1, 2, 3] >>> >>> # test 2: reset del ... >>> = [1,2,3] >>> b = >>> del >>> traceback (most recent call last): file "<stdin>", line 1, in <module> nameerror: name 'a' not defined >>> b [1, 2, 3] >>> >>> # test 3: reset del a[:] ... >>> = [1,2,3] >>> b = >>> del a[:] >>> [] >>> b [] i did find different ways of clearing lists , didn't find explanation differences in behaviour. can clarify this? test 1 >>> = [1,2,3] # set point list [1, 2, 3] >>> b = # set b pointing @ >>> = [] # set point empty list # step 1: --> [1

javascript - React js onClick can't pass value to method -

i want read onclick event value properties. when click on it, see on console: syntheticmouseevent {dispatchconfig: object, dispatchmarker: ".1.1.0.2.0.0:1", nativeevent: mouseevent, type: "click", target my code working correctly. when run can see {column} cant in onclick event. my code: var headerrows = react.createclass({ handlesort: function(value) { console.log(value); }, render: function () { var = this; return( <tr> {this.props.defaultcolumns.map(function (column) { return ( <th value={column} onclick={that.handlesort} >{column}</th> ); })} {this.props.externalcolumns.map(function (column) { // multi dimension array - 0 column name var externalcolumnname = column[0]; return ( <th>{externalcolumnname}</th> ); })}

c++ Can a class contain a class member that is friends with it? -

i have class called restaurant contains employee member. employee friend class of restaurant. when try compile errors on employee mcurrentemployee saying missing type specifier - int assumed. why compiler mad @ me this? ideas on how can fix it? thanks. #pragma once #include "employee.h" class restaurant{ friend class employee; private: employee mcurrentemployee; }; - #pragma once #include "restaurant.h" class employee { } if remove include of "restaurant.h" employee should resolve friend issue (you may need use forward declarations code compile it's impossible given minimal code you've shown us). that said should ask why employee needs friend of restaurant in first place.

actionscript 3 - ENTER_FRAME Event not working correctly with MouseEvent As3 -

i know missing simple can't seem figure out. have buttons control log on stage so: //buttons main screen left , right mainscreen.leftbtn.addeventlistener(mouseevent.click, leftbuttonclicked); mainscreen.rightbtn.addeventlistener(mouseevent.click, rightbuttonclicked); private function leftbuttonclicked(e:mouseevent):void { if (e.type == mouseevent.click) { clickleft = true; trace("left_true"); } } private function rightbuttonclicked(e:mouseevent):void { if (e.type == mouseevent.click) { clickright = true; trace("right_true"); } } now these control logs rotation have setup in enter_frame event listener function called logcontrols(); so: private function logcontrols():void { if (clickright) { log.rotation += 20; }else if (clickleft) { log.rotati

wpf - Why does my Rectangle's Fill not update when the GradientStops within the Brush change? -

i'm trying make gradient editor in wpf. this, i'm using gradientstopcollection datacontext rectangle (to display gradient) , itemscontrol (to display controls editing stops). <window x:class="my.mainwindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" height="350" width="525"> <stackpanel> <stackpanel.datacontext> <gradientstopcollection> <gradientstop color="black" offset=".25"/> <gradientstop color="white" offset=".75"/> </gradientstopcollection> </stackpanel.datacontext> <rectangle height="100"> <rectangle.fill> <lineargradientbrush gradientstops="{binding}"/> </rectangle.fi

dojo - Make DGrid selector shown or hidden based on row content -

i'm using dgrid selection grid grid uses check boxes selecting content. however, child node of tree should show checkbox parents categories , can't selected. used editor plugin this, created difficulty clearing selections (specifically, "clearselection" method of grid did nothing). switched selector plugin, selecting , deselecting rows works fine, can't seem figure out way hide check box on rows , not others. original code var columns = [ editor({ label: " ", field: "itemselected", sortable: false, width: 33, canedit: function(object) { // add checkboxes child objects return object.type === "child"; } }, "checkbox"), tree({ label: "item", field: "shortitemid", width: 150, shouldexpand: function() { return 1; } }), { label: "grouping name"

MySQL update just day in date column in many rows -

having rows: 1|2015-04-22 2|2015-03-11 3|2015-02-15 i want update on rows day, example: 1|2015-04-25 2|2015-03-25 3|2015-02-25 it looks want keep year , month same, , change days 25th of whichever year , month shown. the formula need date(date_format(datecolumn, '%y-%m-25')) so, update table it's update mytable set datecolumn = date(date_format(datecolumn, '%y-%m-25'))

unix - Is it possible to create a shell script used as soft link? -

i not know if there way create shell script soft link/symbolic link? thank you. type in terminal: ln -s /path/to/shell/script/to/be/linked /path/to/shell/script/soft/link example: ln -s /usr/local/script1.sh /usr/scripts/ this command create soft link script1.sh in folder /usr/scripts note: can execute shell script using soft link itself

sql - Extracting Records which 'No' Criteria only -

i have view in sql retrieves below result: emp id first name last name made payment bigger $2000 in last 12 months 10023 keith brown no 10023 keith brown no 10023 keith brown yes 31522 maxine wood no 31522 maxine wood no 31522 maxine wood yes 31522 maxine wood yes 31522 maxine wood no 32007 mark taylor no 32007 mark taylor no 32007 mark taylor no 32007 mark taylor no 32012 christopher benson yes 32034 william cecchini no 32034 william cecchini no 32034 william cecchini no 32034 william cecchini no 32037 gregory thomas no 32037 gregory thomas no 32037 gregory thomas no 32037 gregory thomas no 32037 gregory thomas no 32037 gregory thomas no 32037 gregory thomas yes i want result employees resu

ios - Multiple buttons to single IBAction - How to change background of the previous tapped button? -

i have group of buttons user can tap, calculator. the app collect series of 2 buttons taps. select card deck. 1st tap ace through king. 2nd tap suit. when 1st button tapped, change background yellow (the rank). when 2nd button tapped, save 2 selections pair , append string (the suit). once 2nd button tapped, want change 1st tapped button blue. with buttons linked single ibaction 'buttontapped', can't change 1st button background blue, when tapping 2nd button. (i ok 2nd button changing buttons linked ibaction blue) @ibaction func buttontapped(thebutton: uibutton) { var buttondump = thebutton.titlelabel!.text! var firstchar = array(buttondump)[0] if firstchar == "♠️" || firstchar == "♥️" || firstchar == "♦️" || firstchar == "♣️" { // must 2nd tap, lets change 1st tapped bg blue self.n2.text = buttondump thebutton.backgroundcolor = uicolor.bluecolor() } else { self.n1.text = b

regex - Canned Regexps for Ruby? -

does ruby have gem provides canned set of regular expressions (ala perl's regexp::common module)? if not, how community share commonly-needed regexps? thanks. yes, kind of. there gem called ruby_regex exact thing. github page: add gemfile gem 'ruby_regex' in models validates_format_of :email, :with => rubyregex::email and have listed regex for: rubyregex::url rubyregex::domain rubyregex::email rubyregex::username rubyregex::ussocialsecurity rubyregex::generalpostalcode rubyregex::zipcode rubyregex::creditcard rubyregex::mastercard rubyregex::visa rubyregex::twitterusername rubyregex::delicioususername rubyregex::slidesahreusername rubyregex::githubusername rubyregex::uuid rubyregex::dbdate rubyregex::dbdatetime rubyregex::spanishbankaccountnumber rubyregex::dni i'm not sure if support else. there lots of little one-off projects this. haven't been able find complete perl module. i found 1 called cregexp has limited numbers of th

python - Sort Column in a file from high to low -

i have file has set of peoples scores. there 3 scores each person. able display highest score of person. however, not able print python shell, highest score in descending order. example: persona 12 personb 14 personc 17 persond 11 and want sorted descending order of score. should like: personc 17 personb 14 persona 12 persond 11 so far have created code, not know how continue: with open("class.txt","r") file: lines = file.readlines() open('class.txt','w') fileout: line in lines: fields = line.split() name, grades = fields[0], fields[1:] grades = [int(grade) grade in grades] grades.sort() highest = str(max(grades)) grades = [str(highest) grade in grades] rows = filter(none, [line.strip().split() line in open("file.txt", "r")]) data = [(name, int(highest)) name, high

My firefox direct me to my old domain -

i have github page: amovah.github.io i removed cname file, when open page show me old domain added in cname. actually know cname removed , page publish on amovah.github.io not old domain. and although works correct in mobile browser , browser in pc. can test it. how can fix it? try other browsers, if problem doesn't happen in other browsers mozilla using it's cache memory show website. when hit load website, it's not retrieving data server, instead it's retrieving cache. so, changes in server side not appearing. obtain desired result, you've clear browser cache. clear browser cache ... from history menu, select clear recent history. [or press ctrl + shift + del] from time range clear: drop-down menu, select desired range; clear entire cache, select everything. next "details", click down arrow choose elements of history clear; clear entire cache, select items. click clear now. exit/quit browser windows , re-open browser. sourc

c# 4.0 - Access the first object in grouby list of lists -

groupby creates list of lists of objects i'm sorting. need first element in each list list<string> topfive = listofobjects.groupby(x=>x.names).orderbydescending(x=>x.count())... ok, have list of objects, in descending order how many objects in each list. need retrieve 1 object each list, i.e. need retrieve first object in each nested list , put in new list can .select .names property the confusion arising fact groupby creating list there multiple objects in list, list in element of external list. need extract 1 object each nested list i have been scanning stack overflow last 2 hours , lack keywords find relevant answer. this best guess doesn't work list<string> topfive = listofobjects.groupby(x => x.names).orderbydescending(x => x.count()).select(x => x.select(y => y.names)); have tried: topfive.first().names

regex - What are the frameworks available in perl -

can list frameworks available in perl , used testing , tool development. had lot of confusion on it. answer me lot. in advance. these perl web framework : mojolicious perl dancer catalyst for more information read this: which perl web framework should use see comparison of perl web application frameworks

MYSQL JAVA , Adding Values and and displaying auto-incremented number -

if(i > 0){ joptionpane.showmessagedialog(null,"saved id = " + rs.getstring("id")); } i adding value database, can add easily. there no option adding id database (as auto incremented within database). after data added, want auto incremented id number database. if(i>0) if data added successfully. adding database fine, , in database id number increasing.

algorithm - How do I use MATLAB to solve this PDE -

Image
i have following question on practice exam: i need use matlab solve it. problem is, have not seen problem before , i'm struggling started. i have 1x1 grid, split 10x10. know can calculate whole bottom row besides corners using 1/10 * x*2. know can calculate entire right row using (1/10)(1+t)^2. however, cannot figure out how enough points able fill in values entire grid. know must have partial derivatives given in problem, i'm not quite sure come play (especially u_x equation). can me start here? i don't need whole solution. once have enough points can write matlab program solve rest. really, think need x=0 axis solved, fill in middle of grid. i have calculated bottom row, minus 2 corners, 0.001, 0.004, 0.009, 0.016, 0.025, 0.036, 0.049, 0.064, 0.081. , similarly, entire right row trival calculate using given boundry condition. can't piece go there. edit: third boundry condition equation mistyped. should read: u_x(0,t) = 1/5t, not u(0,t) = 1

android - Not understanding whether to use notifyDataSetChanged() when elements in listview are updated? -

i have android application uses listview adapter of custom objects. oncreate of activity if list of objects available populate adapter previous objects , make async call fetch new objects , populate adapter. while populating adapter again old list of elements removed , new added. have not used notifydatasetchanged(). private customadapter listadapter; private gridview gridview; // oncreateview of fragment if find old list in singleton populate list , shows on screen function oncreateview() { ... ... listadapter = new customadapter(getactivity(), countersingleton.getinstance(getactivity()) .getobjects()); gridview.setadapter(listadapter); .... ... new asnyctask().execute(); } class asnyctask { // fetch new list , replace old list shown

android - Getting java.io.FileNotFoundException -

i have 4 file in subfolder in assets folder. have written code @override public view getview(final int position, view convertview, viewgroup parent) { if (convertview == null){ convertview = layoutinflater.from(context).inflate(r.layout.item_list, parent, false); } final textview textview1 = (textview) convertview.findviewbyid(r.id.textview1); final textview textview2 = (textview) convertview.findviewbyid(r.id.textview2); final button show = (button) convertview.findviewbyid(r.id.show1); final button hide = (button) convertview.findviewbyid(r.id.hide1); textview1.settext(data[position]); show.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { show.setvisibility(view.invisible); hide.setvisibility(view.visible); try{ resources resources = getresources(); assetmanager assetmanager = resources.getassets();

security - How to stop public seeing error messages in PHP -

pretty if mistake happen in php not want public see error security purposes, there anyway of having log or file people file or access can see it? use following line first line: error_reporting(0); another alternative .htaccess file.

amazon web services - spring-cloud-aws Spring creates message header attribute not supported by SQS -

i'm using spring cloud aws messaging send/receive messages using sqs. my code looks this: @springbootapplication @import(messagingconfig.class) public class app { public static void main(string[] args) { springapplication.run(app.class, args); } } @configuration public class messagingconfig { @bean public queuemessagingtemplate queuemessagingtemplate(amazonsqs amazonsqs, resourceidresolver resourceidresolver) { return new queuemessagingtemplate(amazonsqs, resourceidresolver); } } the sender code (wired via controller): @component public class sender { @autowired private queuemessagingtemplate queuemessagingtemplate; public void send(mymessage message) { queuemessagingtemplate.convertandsend("testqueue", message); } } i have application.yaml file defines aws parameters seem correctly loaded. so, when run application, following warning/error: message header name 'id' , type 'java.

c++ - How to use std::thread? -

when use std::thread this: func() { std::thread(std::bind(&foo, this)); } the thread object allocated in stack , destroyed when func() returns. try use like: func() { std::thread* threadptr = new std::thread(std::bind(&foo, this)); } where should delete threadptr ? , how can create thread suspended? if want thread run independently, need use detach() method on object. otherwise, thread destructor terminate program if object destroyed while thread still running. threads start running created. cannot create thread object in suspended state. can either store arguments create thread instead of creating (possibly using, instance, std::function ), or make block on mutex or condition variable until ready let run.

java - Search if a column value in database exists in a file -

i have column in db has list of vendors available. system outputs file after processing. text file contain 1 vendor name present in db column. there way find vendor present in text file list of vendors available in db. example, column values can be, walmart target moretex electra the text file have "moretex, textile company invoice number #384722 5119 09/22/14 rome limited name dept terms card payment eggplant blah blah blah. total 329 tax moretex, textile company address visit www.moretextile.com" have find if above text contains of vendors in db. in above example matches "moretex". should write custom or lucene or sphinxsearch here. vendor list can grow 100000+ , performance matters. you can use org.apache.commons.io.fileutils better performance. here's code file file = new file("file url"); string content = fileutils.readfiletostring(file); string[] dbcolumn = new string[no. of rows]; //your column values db string colv

node.js - Restify getting request.body when content-type is application/octet-stream -

does know why setting content-type application/octet-stream request body undefined in restify? here code var restify = require('restify'); var server = restify.createserver({}); server.use(restify.bodyparser({ })); server.post('/test', function(req, res, next){ console.log(req.body); }); server.listen(8090, function() {}); http request post /test content-type: text/plain hello console print: hello post /test content-type: image/png hello console print: <buffer 68 65 6c 6c 6f> post /test content-type: application/octet-stream hello console print: undefined from can see in restify, due bodyparser expecting content-type: application/json extracted https://github.com/restify/node-restify/blob/master/lib/plugins/json_body_parser.js#l28 if (req.getcontenttype() !== 'application/json' || !req.body) { next(); return; } so req.body never gets assigned...

javascript - How to access the values of local variables globally -

this question has answer here: how return response asynchronous call? 24 answers i returned rsltcallback function , when call googlesearchsuggestions function , getting undefined. when console.log input parameter inside rsltcallback function it's printing output console. var googlesearchsuggestions = function(search_keyword , element) { var parsed; var uri = 'http://suggestqueries.google.com/complete/search?output=toolbar&hl=en&q=' + search_keyword; var xhr = (typeof xmlhttprequest !== 'undefined') ? new xmlhttprequest() : new activexobject(microsoft.xmlhttp); xhr.onreadystatechange = function(){ xhr.responsetype = 'xml'; if(xhr.status == 200 && xhr.readystate == 4) { var response = xhr.responsexml; var items = response.getelementsbytagname('toplevel'

javascript - Stop page from scrolling past specified Div (or Footer element) -

seemingly, question has been asked several times, not specific situation / needs. i had product filter developed ecommerce site. it's working fine, however, setup involves products have been 'filtered out' being sent out of view @ bottom of site. whilst out of view customer, browser still allocates space them @ bottom, hence site scrolls past footer. my question is; possible lock off scrolling @ part of page using jquery or css? eg; stop scrolling @ base of footer. or slot in div id @ bottom of page , spec no scrolling past that? many in advance. damien jsfiddle: http://jsfiddle.net/kwgmj/184/ you can handle scroll event , restrict scroll given value. $(window).scroll(function(e) { if($(window).scrolltop() >=150) { $(window).scrolltop(150); } }); just replace "150" y-position of desired div.

Sharepoint 2013 Office365 - DelegateControl -

i'm trying find official answer question: can use delegatecontrol in sharepoint 2013 on office365 ? does have microsoft link or article possible or not possible? or of guys know experience possible? thansk emilio no it's not possible use delegate control can install sandboxed solutions in sharepoint 365 , delegate controls not permitted in sandboxed solutions. similar question asked office365 community http://community.office365.com/en-us/f/154/t/55979.aspx richard dizerega has written blog possible , not possible on sharepoint 365 http://blogs.msdn.com/b/richard_dizeregas_blog/archive/2013/07/16/app-approaches-to-common-sharepoint-customizations.aspx delegate control apps sharepoint not support "control" elements can used delegate controls in master page. delegate controls common mechanism swapping out functionality of site using farm solutions (particularly useful additionalpagehead delegate). alternative, same result can achie

wordpress - Where the view rendering logic belongs to, functions.php or content-partial template? -

i implementing "recently post" rendering logic wordpress recently. based on @helenhousandi's example , did task through wp_query() pull out posts. however, facing architecture issue right now. in wordpress, there 3 ways include loop rendering snippets inside single.php file: 1. put rendering logic directly in single.php single.php <div id="header-announcements"> <h3>announcements</h3> <?php $queryobject = new wp_query( 'post_type=announcements&posts_per_page=5' ); // loop! if ($queryobject->have_posts()) { ?> <ul> <?php while ($queryobject->have_posts()) { $queryobject->the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php } ?> </ul> <div><a href="#">v

c# - Inserting nodes from DataGridView into a TreeView -

i don't know how manage correctly have ask here. have code: (int = 0; < cusids.count; i++) { treenode node = new treenode(cusids[i]); treeview1.nodes.add(node); } cusids list customer ids stored once (distinct - taken datagridview). have datatable called dtfoundids stores every single row datagridview ids appear in list above prresent (in datagridview customer id cann appear multiple times). code above creates nodes tree customer ids. wanted add type numbers each id listed in datagridview. records in datagridview like: cusid |typenum ------------------ 111 | 234 111 | 211 122 | 123 122 | 556 122 | 222 so how can fill type numbers child nodes ids? want have 1 node every id , type numbers childnodes. thank much! you can use node.imagekey or node.name , pass value on it treenode node = new treenode(); node.imagekey = convert.tostring(cusids.rows[i]["cusid"]); node.name = convert.tos

mongodb - Mongo transactions and updates -

if i've got environment multiple instances of same client connecting mongodb server , want simple locking mechanism ensure single client access short time, can safely use own lock object? say have 1 object lockstate can "locked" or "unlocked" , plan checks "unlocked" before doing "stuff". lock system say: db.collection.update( { "lockstate": "unlocked" }, { "lockstate": "locked" }) (aka update lockobj set lockstate = 'locked' lockstate = 'unlocked' ) if 2 clients try lock system @ same time, possible both clients can end thinking "have lock"? both clients find record query parameter of update client 1 updates record (which atomic operation) update returns success client 2 updates document (it's found before client 1 modified it) update returns success i realize contrived case hard reproduce, possible or mongo somehow make client 2's update fai

c++ - OpenCV-2.4.8.2: imshow differs from imwrite -

Image
i'm using opencv2.4.8.2 on mac os 10.9.5. have following snippet of code: static void compute_weights(const vector<mat>& images, vector<mat>& weights) { weights.clear(); (int = 0; < images.size(); i++) { mat image = images[i]; mat mask = mat::zeros(image.size(), cv_32f); int x_start = (i == 0) ? 0 : image.cols/2; int y_start = 0; int width = image.cols/2; int height = image.rows; mat roi = mask(rect(x_start,y_start,width,height)); // set roi roi.setto(1); weights.push_back(mask); } } static void blend(const vector<mat>& inputimages, mat& outputimage) { int maxpyrindex = 6; vector<mat> weights; compute_weights(inputimages, weights); // find fused pyramid: vector<mat> fused_pyramid; (int = 0; < inputimages.size(); i++) { mat image = inputimages[i]; // build gaussian pyramid weights vector<ma

graph - to plot the values of coordinates in first unit quadrant in matlab -

i have 2 row vectors of size 1x1024 , consist of values in range [0 1]. want plot points on graph within first unit quadrant in matlab. please me out draw graph. ydata = ydata(xdata>=0 && xdata<=1); xdata = xdata(xdata>=0 && xdata<=1); plot(xdata, ydata);

porting - JavaScript implementation of jq? -

the implementation of jq seems in c. there comparable in (browser-side) javascript? the reason i'm asking work out how it's worth investing in jq - prefer toolkits js-based, since can installed via npm, can used in browser et. , 2 environments encounter json... there fiatjaf/jq-web this build of jq, command-line json processor in javascript using emscripten along wrapper making usable library. demo here http://fiatjaf.alhur.es/jq-web/

Is there any OWASP checking tool for scala project? -

i found there owasp dependency checking tool java projects: https://www.owasp.org/index.php/owasp_dependency_check i tried tool on scala projects, can find no dependencies. is there similar thing scala projects? there 1 (june 2016): albuch/sbt-dependency-check alexander v. buchholtz . sbt plugin owasp dependencycheck. can used monitor dependencies used in application , report if there publicly known vulnerabilities (e.g. cves). runs dependency-check against current project,its aggregate , dependencies , generates report each project. you need add project/plugins.sbt addsbtplugin("net.vonbuchholtz" % "sbt-dependency-check" % "0.1.4") and after call $ sbt dependencycheck the report written location crosstarget.value(by default target/scala-2.11/).

mysql - Replace last string in IP-address accornding to specific condition in PL/SQL -

i've got table fields , values: entaddr (varchar2) entifindex (varchar2) 18.17.16.2 1 18.17.16.53 2 18.17.16.1 3 18.17.16.54 4 i have join 1st , 3rd record knowing 1st entaddr. how can 18.17.16.1 18.17.16.2? (last char -1). have join 2nd , 4th record knowing 2nd entaddr (18.17.16.54 18.17.16.53, i.e last char +1) so need "select" like: select entifindex table1 ' some transformation of entaddr (changing last char) '= entaddr thanks in advice!! is looking @ sql> select concat (substr('18.17.16.2',1,9),substr ('18.17.16.2',-1)-1 ) "concat val" dual; concat val ---------- 18.17.16.1

javascript - $(document).ready() doesn't always fire in Content Script for Chrome Extension -

this question has answer here: chrome extension not loading on browser navigation @ youtube 1 answer i making chrome extension interacts pages loaded youtube.com. want reorder related videos largest smallest on page, content script has talk background page information first. content script starts sorting following event: content_script.js: $(document).ready(function() { chrome.runtime.sendmessage({message: "getrecentsorttype"}, function(response) { performsortaction(response.sorttype); }); }); the background.js script listens, , executes code based off request: chrome.runtime.onmessage.addlistener(function(request, sender, sendresponse) { if(request.message === "getrecentsorttype") { var recentsorttype = localstorage.getitem("sorttype"); if(recentsorttype === null) { rec

scrapy + tor always returns 403 but I can curl and browse -

i'm trying setup scrapy + tor i'm using scrapy 0.24.6 i first tried using polipo able access tor http proxy ( https://pkmishra.github.io/blog/2013/04/16/scrapy-run-using-tor-and-multiple-agents-part-2-ubuntu/ ) i'm able configure web browser use polipo , i'm able browse using tor , can curl. tried httpproxymiddleware , using env var or writing own custom middleware, same result: scrapy returns 403 then tried use tor directly, again can configure web browser use socks proxy , can curl torsocks , scrapy returns 403 anyone has idea might wrong ? it looks error come scrapy because have exact same headers/user-agent , without tor, through tor 403

javascript - Display message in iframe, if there is a .doc file which cannot be displayed -

i using iframe display pdf or doc file on page. pdf without doubt displayed doc file downloaded , aware why. now problem want display message in iframe file doc files cannot displayed , need downloaded view. till have searched , found various solutions display message or while loading iframe guess here not case of loading anything. here fiddle show sample code can give best solution. can use js fiddle well. otherwise can add if condition check check file type , show alert notification users.

Using an API Key & Secret for Swagger Security Scheme -

swagger supports security of api key , seems limited single parameter. is there way define set of parameters (key , secret) expected parameters in request? or way skip security scheme, , add parameters every request? yes, in swagger 2.0 can specify multiple api key security definition , mark operation require multiple securities. in following example, i'm using 2 api key securities should presented in header of each request in order authenticated. swagger: '2.0' info: version: 0.0.0 title: simple api securitydefinitions: key: type: apikey in: header name: key value: type: apikey in: header name: value paths: /: get: security: - key: [] - value: [] responses: 200: description: ok at moment swagger editor's "try operation" not support multiple securities being used doesn't mean swagger not supporting it. follow this issue in github support of featur

mysql - Php Year Month Calculation -

friends, need data year='2015' , month='8' using & to. got empty results. please me out. here query. select * me_fees year= '2015' && month = '8' && register_no= '9' && year between '2015' , '2015' && month between '6' , '12' select * me_fees year= '2015' && month = '8' && register_no= '9' && year between '2015' , '2015' && month between '6' , '12' that query uses mysql reserved words need escaped, month , year if field names escape them tick `month` then last 2 conditions useless. equivalent correct query be select * me_fees `year`= 2015 , `month`= 8 , register_no= 9

Find all file types for Ubuntu font -

i need file types ubuntu font (eot, ttf, eot, woff) bold, light , regular. i've searched on internet, have found ttf download link. i tried find them, there tons of information method page load type of font, using google's server, need files on server. how can find them? all type of fonts can found on github repo: https://github.com/earaujoassis/ubuntu-fontface

java - Data insertion fails after a particular level of values in spark -

i have created apache spark application analyze table cassandra , insert table in cassandra. after particular number of insertion (217 records), insertion failing , spark stops abruptly. have tried setting executor memory 2g. there else should add configuration? i found issue , there null value present in cassandra clustering column .that reason error.

jquery - Call JavaScript function in AbstractJavaScriptExtension class -

i call javascript function in vaadin. abstractjavascriptextension . this.callfunction("removenode"); not fire javascript function. bug or doing wrong? @override public void remove() { super.remove(); fireremovenode(); this.callfunction("removenode"); } javascript code: window.vaadin_components_graph_node = function() { var self = this; var state = this.getstate(); ... this.removenode = function() { console.log("call function", "remove node") $(node).remove(); } }; you can't call javascript functions after abstractjavascriptextension removed. try placing javascript call method , don't call remove();

unit testing - AngularJS Karma Jasmine Error: Cannot Read Property of Undefined -

this first attempt @ using karma/jasmine. want use test angularjs app. this simple hello world test make sure things working not. i trying test controller called inboxcontroller. have defined scope variable: $scope.greeting = 'hello world'. i trying test in separate file called controllers-test.js. this test: 'use strict'; describe('controllers tests ', function () { describe('inboxcontroller', function () { var scope; beforeeach(angular.mock.module('myapp')); beforeeach(angular.mock.inject(function($rootscope, $controller){ scope = $rootscope.$new(); $controller('inboxcontroller', {$scope: scope}); })); it('should return hello world', function () { expect(scope.greeting).tobe('hello world'); }); }); }); i keep getting error: cannot read property 'greeting' of undefined, relates scope.greeting in test code. karma config: files : [

security - How can you configure session timeout in the Azure Portal? -

we have been using azure 5 years, , concerned security. one thing not understand why there no session timeout in azure portal (e.g. automatically sign out after 30 minutes of inactivity). know, if have access portal you can delete click of button . i always start portal in chrome incognito mode, , sign in two-step authentication. forget close browser, , when resume laptop after few days have hit f5, , have access everything . worse... if navigates away portal , revisits after few days still signed in. is possible configure session timeout, ensure session not live forever? start out asking what's attack vector? if it's can come along , resume session, can lot more damage. if attacker can access computer unlocked, can worse. example, install modified browser keylogs , sends them. or worse can execute man in browser attack . session expiry going extremely little since gain access next time login. the same attacks happen if you're using shared computer.

ios - Strange behaviour - instantiating a UITextField in willMoveToSuperview as opposed to didMoveToSuperview -

i'm working xcode 6.3/ios/swift 1.2. i've stumbled upon strange behaviour don't understand (coming strong oo background). put simply, if subclass uiview , use instantiate uitextfields; in constructor, overriding didmovetosuperview, on dynamically (ie, click event)... uitextfields work expected. however, when creating uitextfield object during willmovetosuperview, seems fine... doesn't respond touch events. this demonstrated in code below (a uiviewcontroller , subclassed uiview). i've added gesture recognizer entire view containing uitextfields. clicking of them other 1 creating during willmovetosuperview, move focus textfield, , ignore touch event (as expected). however, clicking on 1 added during willmovetosuperview fires touch event. event without touch event... textfield remains unresponsive. can explain behaviour? import uikit class rootviewcontroller:uiviewcontroller { override func viewdidload() { super.viewdidload()

ruby - How to get the next hash element from hash? -

i have hash: hash = { 'x' => { :amount => 0 }, 'c' => { :amount => 5 }, 'q' => { :amount => 10 }, 'y' => { :amount => 20 }, 'n' => { :amount => 50 } } how can key next highest amount hash? for example, if supply x , should return c . if there no higher amount, key lowest amount should returned. means when supply n , x returned. can help? i'd use this: def next_higher(key) amount = hash[key][:amount] sorted = hash.sort_by { |_, v| v[:amount] } sorted.find(sorted.method(:first)) { |_, v| v[:amount] > amount }.first end next_higher "x" #=> "c" next_higher "n" #=> "x"

regex - How to extract next url of base URL from a string in regular expression in php? -

for example : http://www.baseurl.com/sports/what-sports/sportsname-golf/golf/mini-golf/menu or : http://www.baseurl.com/dance/what-dnace/dnacename-dhupodi/menu i'd get: dance or sports here code : $router->map('get','/[*:submenu]/menu','kisornirutest/index.php','submenu'); by way i'm getting result result either sports/what-sports/sportsname-golf/golf/mini-golf or dance/what-dnace/dnacename-dhupodi want pick sports or dance . i've done searching on this, didn't expected result. i use class routing : http://altorouter.com/ if use php library manipulate urls like : http://url.thephpleague.com/3.0/ it did want several project.

vba - Access Query with Variable and Export to Excel -

when pressing button execute sql statement uses variable. for example: select a, b, data not null , b = '&<variable>&'; then result of query shall exported worksheet of excel file. you might have create sql on fly , save docmd.outputto method export you. like. option compare database option explicit sub exportquerytoexcel() dim dbobj dao.database, qdobj dao.querydef dim filepath string, sqltext string, yourvariable string set dbobj = currentdb yourvariable = "apple" sqltext = "select a, b, c not null , b = '" & yourvariable & "'" filepath = "c:\users\p\desktop\filename.xlsx" on error resume next dbobj .querydefs.delete "tmpdataqry" set qdfnew = .createquerydef("tmpdataqry", sqltext) .close end on error goto 0 docmd.outputto acoutputquery, "tmpdataqry", acformatxlsx, filepath

c# - Is it possible to force azure blob metadata to be overwritten on new blob when copying -

so copying blob blob , overwriting blob newblob following code: copystatus copy = copystatus.pending; while (copy != copystatus.success) { newblob.startcopyfromblob(blob); copy = manager.checkisdonecopying(newblob, container.name); } newblob has metadata on before copy , here see that: if no name-value pairs specified, operation copy source blob metadata destination blob. if 1 or more name-value pairs specified, destination blob created specified metadata, , metadata not copied source blob. which gather means old blobs metadata not copied over. force original blob overwrite newblob's metadata , edit newblobs metadata using following: newblob.fetchattributes(); if (newblob.metadata.containskey(storagemanager.islive)) { newblob.metadata[storagemanager.islive] = "y"; } else { newblob.metadata.add(new keyvaluepair<string, string>(storagemanager.islive, "y")); } if (newblob.metadata.containskey(storag

android - How to get random data in SQLite? -

i trying random order using order newid() following: public cursor getspeciallist(string bloodcategory) { sqlitedatabase db = this.getreadabledatabase(); cursor cur = db.rawquery("select " + colname + " ," + "" + colfather + " ," + "" + colfamily + " ,"+ "" + colphone + " " + listinfotable + " " + colbloodcategory + "='" + bloodcategory + "'" + " order newid() ", new string[]{}); return cur; } sqlite log gives me following error: no such function newid you can use following code random data: public cursor getspeciallist(string bloodcategory ) { sqlitedatabase db=this.getreadabledatabase(); cursor cur=db.rawquery("select "+colname+" ,"+ ""+colfather+" ,"+ ""+colfamil

angularjs - Unit testing Module with with $routeParams fails? -

i'm using test case use $routeparams without glicth can't make work on new test case. module i reduce content minimal "use strict"; angular.module('warehousesmodule', ['smart-table', 'services', 'ngroute']) .controller('warehouseeditctrl', [ '$scope', '$routeparams', '$location', '$window', 'api', 'gettextcatalog', 'form', function ($scope, $routeparams, $location, $window, api, gettextcatalog, form) { }]); unit test "use strict"; describe('testmodule', function () { beforeeach(module('warehousesmodule')); describe('warehouseeditctrl', function () { var $scope, ctrl, $httpbackend; beforeeach(inject(function ($rootscope, $routeparams, $controller) { $routeparams.compoundid = 3; $scope = $rootscope.$new(); ctrl = $controller('warehouseeditctrl', {

php - how to set phpdbg colours -

i'm using phpdbg , see can change colour of errors , output. useful not easy read when in 1 colour. but can't work. doing wrong or known not working on windows 8.1? this have tried: s c on set color prompt white-bold s c error red-bold just suggested in help. following message on 3 of above lines: [no set command selected!] i'm using php 5.6.7 x86 on windows 8.1 i have tried setting prompt eg. set p > , works, set recognized. have tried entering command in full eg. set colors on makes no difference.

c# - OData cast binary data before filtering -

so, i trying use odata's filtering , greater operator on binary field. want field cast int64 before comparison, cant find way to. the example request have come far : http://urltocontroller?$select=__version&$orderby=__version &$filter=__version ge cast(binary'00000000000009fd', 'edm.int64') this throws incompatible types edm.binary , edm.int64 error. what : http://urltocontroller?$select=__version&$orderby=__version &$filter=cast(__version,'edm.int64') ge cast(binary'00000000000009fd', 'edm.int64') but throw error function cast not implemented. any helps ? tried compare binary field on db if int?

excel vba - Work with the references of different workbooks -

the idea of code launch workbook called " my list.xlsx " , create list on sheet " fx " of list; list based on spreadsheet of opened workbook called " daily prices.xlsm ". when try play around, seems doesn't way reference list on other workbook copy it. here code: sub foreachws() dim ws worksheet, dest worksheet dim lastrow long dim lastrowdestination long dim exratewb workbook dim dailyprices workbook set exratewb = activeworkbook set dailyprices = workbooks("daily prices.xlsm") set dest = worksheets("fx") each ws in dailyprices.worksheets select case ws.name case "fx", "bbg prices", "prices" case else msgbox dailyprices.name lastrow = ws.usedrange.rows.count lastrowdestination = dest.usedrange.rows.count + 2 dailyprices.ws.range(cells(1, 1), cells(lastrow,

How do you make an algorithm that will return the number of elements in an array in C#? -

i have code think going in right direction, need filling in gap. please aware cannot use array.length here , have make algorithm perform same function array.length. here have far: public static int size(int[] s, int n) { (int = 0; < n; i++) { (s[i] } } this silly assignment c# arrays provide length using array.length property. think should make clear in delivery. however, stay within rules try this: int[] array = new int[10]; int count = 0; // iterate elements in array foreach(int item in array) { count++; } // count equal 10 return count;

python - Sys.stdout.write not working as expected -

i've got test script iterates through 2 string arrays, , want use sys.stdout.write provide user simple 'progress bar'. my current script: import sys time import sleep names = ['serv1', 'serv2', 'serv3', 'serv4', 'serv5'] states = ['running', 'stopped', 'running', 'running', 'stopped'] terminated=0 passed=0 in range (0, len(names)): if 'running' in states[i]: print " [*] stop if running {0} ".format(str(names[i])) #service_info(action, machine, names[i]) terminated+=1 else: print " [!] passing on {0} ".format(str(names[i])) passed+=1 sleep(2) sys.stdout.write(" [ ] {0}/{1} progress left\r".format(i+1, len(names))) the expected output sys.stdout.write keep updating, whilst print statements informing user of action. when run this, time sys.stdout.write shown @ end of script. e.g. [*] stop

imagemagick - How to make image background transparent? -

Image
i have 2 images: first http://www.eurocopter.in/contest/images/loader33.gif second if see first image has no background. background looks white. second image has black background. question 1 : call first type of picture? question 2 : how make type of picture? question 3 : how transform second type of picture first type of picture? they animated gifs , first transparent background. can separate image individual frames imagemagick (installed on linux distros , available free osx , linux) this: convert -coalesce type1.gif frame%02d.gif which give following 18 frames individual images frame00.gif frame04.gif frame08.gif frame12.gif frame16.gif frame01.gif frame05.gif frame09.gif frame13.gif frame17.gif frame02.gif frame06.gif frame10.gif frame14.gif frame03.gif frame07.gif frame11.gif frame15.gif frame00.gif you can see them @ once if make them montage this: convert -coalesce type1.gif miff:- | montage -tile x4 -frame 5 - montage.gif you can f

android - Setting a specific image/view to be displayed in the recent apps list -

i app show "splash" screen in recent apps list, how can this? i have tried set splash view first thin in onpause in activity (and set, can see before app goes background), still screenshot android takes of app before onpause called. have looked method: oncreatethumbnail , never called (it seems disabled ). what activitymanager , can somehow remove app activitymanager task list , add again addapptask , give bitmap way? thank søren