Posts

Showing posts from January, 2013

oop - Python overriding getter without setter -

class human(object): def __init__(self, name=''): self.name = name @property def name(self): return self._name @name.setter def name(self, value): self._name = value class superhuman(human): @property def name(self): return 'super ' + name s = superhuman('john') print s.name # doesn't work :( "attributeerror: can't set attribute" s.name = 'jack' print s.name i want able override property able use super parent's setter without having override setter in child class. is pythonicaly possible? use just .getter decorator of original property: class superhuman(human): @human.name.getter def name(self): return 'super ' + self._name note have use full name reach original property descriptor on parent class. demonstration: >>> class superhuman(human): ... @human.name.getter ... def name(self): ... return

android - Cannot open navigationbar -

i click floatingactionbutton open navigation menu, not working drawerlayout drawer = (drawerlayout) findviewbyid(r.id.drawer_layout); floatingactionbutton fab = (floatingactionbutton) findviewbyid(r.id.fab); fab.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { drawer.isdraweropen(gravitycompat.start); } }); no errors in logcat. 1 help. your isdraweropen method checks if drawer open or not , not doing checks. can use in onclick method: if(drawer.isdraweropen(gravitycompat.start)) { closenavdrawer(); }else { drawer.opendrawer(gravitycompat.start); } closenavdrawer method: protected void closenavdrawer() { if (drawer != null) { drawer.closedrawer(gravitycompat.start); } }

c++ - Compilation errors with CImg -

i using cimg library first time , compilation errors simple test program includes cimg.h. why that? how can fix this? program code: #include "../headers/cimg.h" using namespace cimg_library; int main() { return 0; } compilation errors: in function 'file* cimg_library::cimg::fopen(const char*, const char*)': 5065|error: '_fileno' not declared in scope in function 'int cimg_library::cimg::fseek(file*, int_ptr, int)': 5093|error: '_fseeki64' not declared in scope in function 'int_ptr cimg_library::cimg::ftell(file*)': 5102|error: '_ftelli64' not declared in scope this done on pc 64 bit windows 8.1. command: g++.exe -wall -fexceptions -g -std=c++11 -c "d:\informatics\projects\image experiments\rectangle circle stretcher\sources\main.cpp" -o obj\debug\sources\main.o i tried without -std=c++11 part , 2 errors instead of 3. don't 5065|error: '_fileno' not declared in scope . same happens

sql - MySQL - Filter records which date is biggest -

i have mysql select query: select s.* campaign_statistic s inner join campaign c on s.campaign_id = c.campaign_id c.campaign_id = 51 , date(s.created_date) between date(c.start_date) , date(c.end_date) and getting result: id campaign_id instagram_id media_id has_tag comments_count likes_count created_date status ** *********** ************ **************************** ******** ************* *********** ******************* ****** 1 51 1230544324 957801995790641919_1230544324 1 16 2015-11-01 13:10:29 1 2 51 1230544324 957799073015065299_1230544324 2 11 2015-11-01 13:10:29 1 3 51 1230544324 957790310736521811_1230544324 5 20 2015-11-01 13:10:29 1 4 51 1230544324 957801995790641919_1230544324 1 16

dictionary - Swift MapKit Polygon overlay -

Image
i have polygon on mapview, want add 2 1 in different color. there way todo so? this mapview should 2. polygon overlay in different color func addboundry() { var points=[ cllocationcoordinate2dmake(51.711963, 8.738251), cllocationcoordinate2dmake(51.711963, 8.763717), cllocationcoordinate2dmake(51.718574, 8.763717), cllocationcoordinate2dmake(51.71855, 8.754448)] let polygon = mkpolygon(coordinates: &points, count: points.count) mapview.addoverlay(polygon) } func mapview(mapview: mkmapview!, rendererforoverlay overlay: mkoverlay!) -> mkoverlayrenderer! { if overlay mkpolygon { let polygonview = mkpolygonrenderer(overlay: overlay) polygonview.fillcolor = uicolor(red: 0, green: 0.847, blue: 1, alpha: 0.25) return polygonview } return nil } is there way todo so? solved via .title use in if

osx - How to run php files after upgrading OS X Yosemite to El Capitan? -

i've upgraded os x el capitan. created php file inside local server. newly created file displayed without error, previous files in same directory shows php code in browser. also, cannot access phpmyadmin , shows forbidden you don't have permission access /phpmyadmin/ on server. i have run ls -l see file permissions in folder working on, seems ok. don't see change previous files new file have created. how can fix this? upgrading el capitan reset apache config. need change enable modules requires in case mod_alias .

find - Capturing data between specific tag in python -

i getting url content in python... want capture between <h1> , </h1> . what tried is: mystring='''<h1>kgkgjgjgkjgkjgkj</h1> <h1>kdfgggggggggggggggggggkgjgjgkjgkjgkj</h1> dsfgdfgg <h1>kgkgjgjgkdfgdfgdgdfjgkjgkj</h1> dfgdffdgf <h1>kgkgjgjsdssssssssssssssssssssgkjgkjgkj</h1> dfgdfgdg <h1>kgkgjgjgkjgkjgkgggggggggggggggggggj</h1> ''' if '<h1>' in mystring: startstring='<h1>' endstring='</h1>' print mystring[mystring.find(startstring)+len(startstring):mystring.find(endstring)] i have multiple h1 tags. capture data between first h1 tag. how can capture data between h1 tags? i go beautifulsoup-- attempt from bs4 import beautifulsoup import requests url = 'http://accessibility.psu.edu/headingshtml/' respons = requests.get(url).content soup = beautifulsoup(respons,'lxml') h1tags = soup.find_all('h1&

git - How to delete commits from bitbucket -

i accidentally pushed files .idea directory in django project had in .gitignore file. trying delete commit bitbucket repository since there else im working on project , can't pull changes without affecting own .idea files. have seen other questions use git revert, remember there command pushed last commit made, , after deleted master branch. example commit history: 94ca48e 55fab05 3813803 i want delete 94ca48e, , 55fab05. there command found once make 3813803 current commit, , in remote repository after commit deleted, can't find anywhere. use git reset --hard 3813803 . can not undone , works locally remote. have @ git docu atlassian here . let me quote there: whereas reverting designed safely undo public commit, git reset designed undo local changes. because of distinct goals, 2 commands implemented differently: resetting removes changeset, whereas reverting maintains original changeset , uses new commit apply undo. git reset 1 used here,

sql - How can I get count of nulls per database on a MySQL server? -

i count of nulls on columns , tables each database on mysql server. result table should like: +---------------+------------+ | database_name | null_count | +---------------+------------+ | database1 | 0 | | database2 | 5643 | | database3 | 72 | +---------------+------------+ however, wasn't able beyond count of nulls single table: select concat('select', group_concat(' count(*) - count(', column_name, ') ' separator ' + '), 'from ', max(table_schema), '.', max(table_name)) @sql information_schema.columns table_schema = 'accidents' , table_name = 'nesreca'; prepare stmt @sql; execute stmt; deallocate prepare stmt; do have idea? ps: able result matlab code. however, solution within mysql preferred. i think on right track dynamic sql. because want entire database , not single table, structure of query like: select table_schema, sum(cnt) (select "table_sch

python - How to open files with an incremental numbers? -

right i'm doing this: filenames = ['ch01.md', 'ch02.md', 'ch03.md', 'ch04.md', 'ch05.md', 'ch06.md'] open('chall.txt', 'w') outfile: fname in filenames: but have many files written chxx.md (until ch24.md ). there modify script using ranges? don't have type in files names? you can use glob . it's easy way collect files use of wildcard characters. import glob filenames = glob.glob('/yourdirectory/ch*.md') # give list of file names open('chall.txt', 'w') outfile: fname in filenames:

Perl complaining of undefined subroutine, even though package in %INC -

perl's namespace magic frustrating.... have script relies on recipient.pm, donation.pm use lib '../bulkload'; use recipient; use donation; recipient.pm object-orientated class, , uses donation.pm (just bundle of functions). kinda recursive/redundant, know. my script - again relies on both - failing whenever tries gratuitously use sub donation.pm: my $city = donation::getcity($dbh, $cityname, $statename); perl complains: undefined subroutine &donation::getcity called @ ... "nice have", "best practices" refactoring out of scope :) thank in advance!! since don't provide source donation 1 can guess. might be that name of function different that forgot declare package "donation" in donation.pm maybe else (show code)

r - rbind lists to data.frame in for loop -

this (meaningless) truncated version of for-loop in r calculates land uses polygons. iterates nicely through data except when should bind calculations data.frame using plyr::rbind.fill() . desired result (thes same number of) additional unwanted columns filled na-values (i guess has column names). agri_coverage <- data.frame(matrix(rnorm(3), nrow=1)) set.seed(23) agri <- rnorm(10, 0.5) land_use <- null (i in seq_along(agri)) { name <- agri[i] if (name > 1) { wl <- as.list(unlist(agri_coverage[ ,1:3])) } else { wl <- as.list(rep(na, 3)) } land_use <- rbind.fill(land_use, data.frame(wl)) #combine output } what's best function/ method combine these lists 1 data frame , why these additional columns produced? i tried other functions rbind() , data.table::rbindlist() without being successfull. the reason getting additional unwanted columns filled nas because of fact list created in else condition not named same list in if condit

ios - Clarifications on managing orientations in UIViewController -

i have configuration following: uinavigationcontroller -> viewcontroller where viewcontroller root view controller navigation controller. viewcontroller can present modally view controller, modalviewcontroller , following. self.presentviewcontroller(modalviewcontroller, animated: true, completion: nil) within modalviewcontroller override following method. modal view controller in fact can presented in landscape mode. override func supportedinterfaceorientations() -> uiinterfaceorientationmask { return .landscape } i override viewcontroller 's method responding orientation changes. override func viewwilltransitiontosize(size: cgsize, withtransitioncoordinator coordinator: uiviewcontrollertransitioncoordinator) { super.viewwilltransitiontosize(size, withtransitioncoordinator: coordinator) print("size \(size)") } what noticed if modal view controller presented, print in viewcontroller logged if modalviewcontroller in

html - How to remove the text of webkitdirectory -

i added website webkitdirectory input (input type="file" id="ctrl" webkitdirectory directory multiple) everything work well, ui of button ugly. my site bootstrap-based, , new button isn't. moreover, text on button ("choose files") not own text (i write "choose directory"). tryed change basic-design, couldn't. does have idea problem? thanks! , sorry bad english. you can add class input , customize in css. example can make text on button invisible , make :after content. sorry english.

mysql - How can I prevent SQL injection in PHP? -

if user input inserted without modification sql query, application becomes vulnerable sql injection , in following example: $unsafe_variable = $_post['user_input']; mysql_query("insert `table` (`column`) values ('$unsafe_variable')"); that's because user can input value'); drop table table;-- , , query becomes: insert `table` (`column`) values('value'); drop table table;--') what can done prevent happening? use prepared statements , parameterized queries. these sql statements sent , parsed database server separately parameters. way impossible attacker inject malicious sql. you have 2 options achieve this: using pdo (for supported database driver): $stmt = $pdo->prepare('select * employees name = :name'); $stmt->execute(array('name' => $name)); foreach ($stmt $row) { // $row } using mysqli (for mysql): $stmt = $dbconnection->prepare('select * employees name = ?');

How to stop relaying in sendmail 8.14 -

this sendmail version: version 8.14.4 compiled with: dnsmap hesiod hes_getmailhost ldapmap log map_regex matchgecos milter mime7to8 mime8to7 named_bind netinet netinet6 netunix newdb nis pipelining saslv2 scanf socketmap starttls tcpwrappers userdb use_ldap_init canonical name: dynawebs.net uucp nodename: dynawebs.net a.k.a.: [xxxx9.226] ============ system identity (after readcf) ============ (short domain name) $w = xx (canonical domain name) $j = xx.net (subdomain name) $m = xx (node name) $k = xx.net ======================================================== and relay open right (with user auth), , not sure why. maybe because upgraded previous version. files need re-edit now, make sure block relaying , allow specific domains? i put in /etc/mail/access *.* reject but doesn't seem work. goal allow domains block , right thing seems work me put rejects in /etc/mail/access in 154.50

apache - Redirect URLs with a trailing slash to URLs with no trailing slash via htaccess rule with [QSA,L] -

recently broke ties wordpress , migrated of site's content own custom-made cms. works great except 1 thing. previous links site's blog posts have trailing slash. since none of current urls have trailing slash, previous links no longer work , seo non-existent. i've been attempting find htaccess rule redirect trailing slash urls urls no trailing slash, of now, nothing works. use redirect rule first rule remove trailing slash: rewriteengine on rewritecond %{request_filename} !-d rewriterule ^(.+)/$ /$1 [ne,r=301,l]

java - changing from Double ArrayList to Integer ArrayList -

in following program have coded program reads in 5 student names, along marks each 5 quizes each student. have loades names in arraylist of type string , quiz marks in arraylist of type double. need load these quiz marks integer , not sure how change this import java.util.scanner; import java.util.arraylist; public class onemoretime { public static final double max_score = 15 ; public static final int namelimit = 5; public static void main(string[] args) { arraylist<string> names = new arraylist<>(); arraylist<double> averages = new arraylist<>(); //line needs become integer arraylist scanner in = new scanner(system.in); (int = 0; < namelimit; i++) { string line = in.nextline(); string[] words = line.split(" "); string name = words[0] + " " + words[1]; double average = findaverage(words[2], words[3], words[4], words[5], words[6]); system.ou

mysqli - view works fine, but return 0 rows when call in php -

i created folowing view (select list of last active users): select u.login, u.name, u.surname sessions s left join user u on s.id_user = u.id_user u.id_user != 0 , unix_timestamp()-s.set_time < 300 order s.set_time desc select *from vonline; gives me(i call in phpmyadmin): login name surname admin chuck norris user2 john cena i trying same output in php: if ($stmt = $mysqli->prepare("select * vonline")) { $stmt->execute(); $result = $stmt->get_result(); echo "online users: $stmt->num_rows"; // shows "0" while ($row = $result->fetch_array(mysqli_num)) { echo "login: $row[1] name: $row[1] surname: $row[2]"; } } else { echo "select error"; } why no results, num_rows returns 0. the code above works selecting data other tables, not one. firstly, you're passing code inside string literal, rather executable. echo "online users: $stmt->

osx elcapitan - Python on OSX 10.11: Installation failed - no software found to install -

starting python course via udemy. trying install python 3.2.3 (used in course) 64-bit on osx 10.11.1, running dmg produces msg saying installation failed not find software install. goes wrong? have installed python (other versions , on earlier osx-version), , have never encountered problem. suggestions re how around this? picture of installation failure message

asp.net mvc - "The anti-forgery token could not be decrypted" -

i running iis 8.5 on load-balanced (two-node) web farm. getting sporadic errors: system.web.mvc.httpantiforgeryexception (0x80004005): anti-forgery token not decrypted.... i have tried/checked various solutions: at server-wide level, created explicit validation , decryption keys described here , , have synchronized them across both nodes. 1 thing note now, left "generate unique key each application" unchecked. the token generated once per page avoid problem described here . but errors persist. what can next troubleshoot? edit: controller code: [httpget] public actionresult index() { var model = new loginmodel(); return view(model); } relevant view code: @using (html.beginform()) { @html.antiforgerytoken() @html.validationsummary(true) <h1>log in</h1> <fieldset> <label>email</label> @html.textboxfor(model => model.username) <label>pass

c# - ASP.NET 5 MVC6 User.GetUserId() returns incorrect id -

Image
i have simple project in asp.net 5 1 registered user. have tried id of current logged user extension method getuserid() using system.security.claims namespace. unfortunately method returns me not existing id , don't know why. here simple code: var currentuserid = user.getuserid(); method result: database: more you're getting old auth ticket still valid or getting authentication ticket site running locally. clear browser cache , cookies , run again. also, try changing name of cookie, default set .aspnet.cookies can cause issues if you're running multiple apps locally. caught me while back. the cookie name can changed this app.usecookieauthentication(new cookieauthenticationoptions { authenticationtype = defaultauthenticationtypes.applicationcookie, loginpath = new pathstring("/account/login"), provider = new cookieauthenticationprovider { onvalidateidentity = securitystampvalidator.onvalidateidentity<us

php - Transfer cookies & session from CURL to header location -

i have curl request sending data external source. after post completed, extract destination url , redirect through header("location: $url");. problem : while redirect, data no longer present. cookie or session not being passed through header location. what best way of transferring header details header location? $ch = curl_init(); curl_setopt($ch, curlopt_url, $url); curl_setopt($ch, curlopt_post, true); curl_setopt($ch, curlopt_cookiesession, true); curl_setopt($ch, curlopt_header, true); curl_setopt($ch, curlopt_postfields, 'postdata=' . urlencode(xmldata())); curl_setopt($ch, curlopt_httpheader, array('content-type: application/x-www-form-urlencoded')); curl_setopt($ch, curlopt_followlocation, true); curl_setopt($ch, curlopt_fresh_connect, 10); curl_setopt($ch, curlopt_cookiejar, 'cookie.txt'); curl_setopt($ch, curlopt_cookiefile, 'cookie.txt'); // download given url, , return output $output = curl_exec($ch); // cookie match preg

How to handle variables correcly in C# composition? -

what correct implementation of composition here? have class cat, contains _gallonsofmilkeaten variable, because cats drink milk. have animal class age, because animals have age. now, need use age variable in both cat , dog classes. should this: class animal { public float age = 35; } class cat { private float _gallonsofmilkeaten; private animal _animal = new animal(); public void meow() { debug.log("this dog ate "+_gallonsofmilkeaten+" gallons of milk , " + _animal.age+" years old." )} } } class dog { private float _bonesburried; private animal _animal = new animal(); public void woof() { //... } } or this, each of them has own definiton of variable?: class animal { } class cat { private float _gallonsofmilkeaten; private animal _animal = new animal(); private float _age = 35; public void meow() { debug.log("this dog ate "+_gallonsofmilkea

Adding Identity to existing column with data in Sql Server -

this question has answer here: adding identity existing column 19 answers i have table 4 million records. want change orderid identity without losing data. is possible? assuming orderid have no duplicates, 1. can create new table orderid identity column , copy data. drop existing table 2. create new identity column , drop existing orderid column alter table (yourtable) add newcolumn int identity(1,1) alter table (yourtable) drop column orderid sp_rename 'yourtable.newcolumn', 'orderid', 'column'

c# - Louvain modularity implementation -

i want use louvain modularity algorithm in order find cliques in graphs. couldn't find library can in c#. know if such library exists , if not there open source graph library in c# easy implement such algorithm in. moreover, if there open source library in java or c++ implement louvain modularity algorithm know also. if knows please share. thank you! the original article implementation in c++: https://perso.uclouvain.be/vincent.blondel/research/louvain.html https://sites.google.com/site/findcommunities/ it implemented in open source libraries such igraph: http://igraph.org/c/doc/igraph-community.html#igraph_community_multilevel

javascript - return in an event function results in alert pop-up -

i following book on javascript. page puzzles me following: http://javascriptbook.com/code/c06/html5-events.html . when user pressed "next" button event fires. code specifies event listener: window.addeventlistener('beforeunload', function(event) { var message = 'you have changes have not been saved'; (event || window.event).returnvalue = message; return message; }) this code results in alert , offers me stay on page or leave . don't syntax here. thought alerts made alert() function. going or here? help this code returns message, browser takes care of confirming user navigation( or close) event, why browser specific alert. window.addeventlistener('beforeunload', function(event) { var message = 'you have changes have not been saved'; (event || window.event).returnvalue = message; return message; // alerts message. }); if try below code, doesnt returns message, won't confirmation alert box, can still c

php - Check If Folder Exists Is Not Working -

i'm trying function recognize if folder exists on server, it's not working. i've tried is_dir function no luck. this script trying utilized in wordpress plugin, it's using php-based function if file/folder exists. idea why it's not recognizing /docs folder exists? i've verified $filename pulling correct file path on server. function docs_settings_page() { $filename = get_stylesheet_directory_uri()."/docs/"; if(file_exists($filename)) { echo "the folder exists!"; } else { echo "sorry - file not exist."; } } function docs_create_menu() { // stuff here } add_action('admin_menu', 'docs_create_menu'); the get_stylesheet_directory_uri() function returns uri of document. in case need absolute path, not uri. clarification: uri: thing type browser. absolute path: path root directory of webspace / server. so 'docs' folder inside theme's directory

mocking - Nightwatch Mock HTTP Requests -

i try mocking http requests nock , other libs sinonjs without success. import nock "nock" const url = "http://localhost:8080/" const sign_in_path = "/fake/users/sign_in.json" export const signinrequest = (status, payload = {}) => { return nock(url).get(sign_in_path).reply(status, payload) } - import { signinrequest } "./../../utils/fakerequests" const dologin = (browser) => { return browser .url("http://localhost:8080") .waitforelementvisible('form', 1000) .setvalue('input[name=email]', 'foo@foo.com') .setvalue('input[name=password]', 'somepass') .click('button[type=submit]') .pause(500) } export default { "do login , shows error message": (browser) => { signinrequest(403) dologin(browser) .waitforelementvisible('.error', 1000) .end() } } its possible mock ht

yii2 - Editing a web application developed with yii -

i know might sound dumb, i'm new framework. client has application developed yii, needs few changes made, spellings, changing content of copyright on footer. tried editing using dreamweaver, don't seem locate of texts. please help! in advance. use text editor notepad++ ore sublimetext or notepad. php code..and html for footer @ source code of application. if version yii 1* can find part of code in layout. if use default theme find layout in yourapp/protected/view/layouts/ if application use specific theme layout in yourapp/theme/yourthemename/layouts/ look file need (normally main.php) if framework version 2.* layout in yourapp/view/layouts

java - JSON Infinite string when using hibernate one to many and many to one mapping REST web service -

i facing weird issue when using hibernate 1 many , many 1 mapping , returning data using json swing client rest web service. when web service returning salesorder object. have checked contains orderlines objects set. but, if open 1 of orderline object, again has sales order object. this chaining causing issue client side infinite string of json being returned. like below... [ { "salesordernumber":"1", "customercode":"1", "totalprice":50.0, orderlines": [ { "salesordernumber":"1", "productcode":"2", "quantity":1, "salesorder":{"salesordernumber":"1","customercode":"1","totalprice":50.0,"orderlines":[{"salesordernumber":"1","productcode":"2","quantity":1,"salesorder":{"salesordernumber":"1","customercode":"

Enabling/disabling fullscreen and maximize window with a keypress in Python 3.x -

i need enable/disable fullscreen , maximized window (--zoomed) in python 3.x using tkinter. code from tkinter import * tk = tk() def fullscreen_on(event): tk.attributes(--fullscreen, true), repr.event.f11 def fullscreen_off(event): tk.attributes(--fullscreen, false), repr.event.escape photo = photoimage(file="image.gif") image_label=label(tk, image=photo) image_label.grid(row=0, column=2) tk.mainloop() it shows image, can't zoom/enable fullscreen. you defining callbacks not binding them in application. callback react needs bound event (e.g. tk.bind ("<key>", callback) ) please have on documentation of event / event-binding. you can bind event shown in question . what want using repr.event.f11 / repr.event.escape? print something? please make sure fix indentation. you can bind f11 , escape callbacks using tk.bind("<f11>", fullscreen_on) tk.bind("<escape>", fullscreen_off)

json - How to convert java byte array to swift nsdata? -

i json response java rest webservice contains image binary data , can't convert binary data , show image in uiimageview i try in swift returns nil let image = [int]() let uintarray = intarray.map { uint(bitpattern: $0) } let dataimage = nsdata(bytes: uintarray, length: uintarray.count)

python - smtplib.SMTPRecipientRefused error while sending email -

i have basic email code looks this: #sendmail function send multiple attachments multiple users @ same time def sendmail(to, fro, subject, text, files=[], server="localhost"): assert type(to) == list assert type(files) == list msg = mimemultipart() msg['from'] = fro msg['to'] = commaspace.join(to) msg['date'] = formatdate(localtime=true) msg['subject'] = subject msg.attach(mimetext(text, 'html')) # print "obtained files:",files file in files: part = mimebase('application', "octet-stream") part.set_payload(open(file.strip(' '), "rb").read()) encoders.encode_base64(part) part.add_header('content-disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) smtp = smtplib.smtp(server) smtp.sendmail(fro, to, msg.as_string())

awk counting number of digits within a given range -

how can count number of times digit within given range of numbers in field occurs? for example, raw text foo.txt shown below: 2,3,4,2,4 2,3,4,32,4 2,3,4,12,4 2,3,4,4,4 2,3,4,,4 2,3,4,15,4 2,3,4,15,4 i want count number of times digit in field #4 falls between following ranges: [0,10) , [10,20), lower bound inclusive , upper bound not. the result should be: range 0-10: 2 range 10-20: 3 here awk code below, getting 8600001 both ranges, awk -f prog.awk foo.txt : #!/usr/range/awk # prog.awk begin { fs=","; $range1=0; $range2=0; } $4 ~ /[0-9]/ && $4 >= 0 && $4 < 10 { $range1 += 1 }; $4 ~ /[0-9]/ && $4 >= 10 && $4 < 20 { $range2 += 1 }; end { print $range1, "\t", $range2; } another awk $ awk -f, '$4>=0{a[int($4/10)]++} end{print "range 0-10:" a[0],"range 10-20:" a[1]}' file range 0-10:2 range 10-20:3 can expanded cover full range $ a

Connect to Azure IoT Hub with Java Paho -

we have started poc connect of our existing code azure iot hub via mqtt test azure’s support standard protocols , tools. using paho client getting connack return code of 5 – not authorized. we followed instructions on how setup iot hub , created 1 using f1 (free) scale tier. followed another azure document , downloaded device explorer, created device , generated sas token. plugged paho: public static void main( string[] args ) { string deviceid = "device-fcbd127a"; string sastoken = "sharedaccesssignature sr=coyoteiot.azure-devices.net%2fdevices%2fdevice-fcbd127a&sig=3acrhqxxxxxxxxxxx‌​zg%3d&se=1468067737"; string brokeruri = "ssl://coyoteiot.azure-devices.net:8883"; string clientid = deviceid; system.out.println( "connecting " + brokeruri +" "+clientid); mqttasyncclient client = null; try { client = new mqttasyncclient( brokeruri, clientid ); if ( client != null ) { mqttconnectoptions opti

Why does `git merge-base` prepares a hypothetical merge commit when more than 3 commits are supplied? -

when executing git merge-base b c , command calculates merge base a , m , m hypothesical merge commit of b , c . (refer: http://git-scm.com/docs/git-merge-base#_discussion ) why merge-base command behaves way? mean, thought more sensible if result merge-base of commits; didn't know behaviour , made operational accident. now, know "sensible" behaviour mentioned achievable giving --octopus option, wondered why not default behaviour. is there reason or use case of current default behaviour?

vba - Run Time error 13: Type Mismatch on code when I add certain lines of code -

so code working fine until tried add nested loop , started getting run time error 13. line error is surrounded *** this code before working: dim lr long dim colltr string dim ave double dim stdev double = 1 datetime_column colltr = replace(cells(1, i).address(true, false), "$1", "") ave = application.average(range(colltr & "1:" & colltr & lr)) ' based on values stdev = application.stdev(range(colltr & "1:" & colltr & lr)) ' based on values next and here code after gets error: dim lr long dim colltr string dim ave double dim stdev double dim q integer redim range(lr1) variant = 1 datetime_column sheets(1).select colltr = replace(cells(1, i).address(true, false), "$1", "") ***ave = application.average(range(colltr & "2:" & colltr & lr))*** ' based on values q = 1 lr1 range(q) = worksheetfunction.abs(cells(q + 1, colltr) - cells(q, collt

using awk to selectively change word order in a column -

i want change text: fred flintstone:father:male wilma flintstone:mother:female flintstone, pebbles:daughter:female barney rubble:father:male rubble, betty:mother:female bam bam rubble:son:male into: flintstone, fred:father:male flintstone, wilma:mother:female flintstone, pebbles:daughter:female rubble, barney:father:male rubble, betty:mother:female rubble, bam bam:son:male is possible in 1 line of awk? or better extract first column manipulate text , reimport column? here gawk 1 liner: awk -f: '$1=gensub(/([^,]+)[ ]+([^ ,]+)/,"\\2, \\1","1",$1)' yourfile it uses : delimiter -f option the gensub function used on $1 in pattern part: if replacement possible, expression true , modifies $1 the default action print used implicitly. if expression not match (due comma in $1 ) line implicitly printed

php - My poll has a 'back button' loophole -

have had couple questions answered nicely here , i've got more trouble can with: i have sql database holds poll question answer , user ip address. here (now working!) php code: // check see if user has voted $current_user = $_server['remote_addr']; $select_query = "select * w_poll_counter user_ip = '" . $current_user ."';"; $result = mysql_query($select_query); if($result) { $row = mysql_fetch_array($result); $user_from_db = $row['user_ip']; if($current_user === $user_from_db) { //user voted - show results page header("location: scripts/show_results.php"); exit(); } } the code works great, except there's 1 problem... after user votes , sees results page, can click browser's 'back' button , vote again, since code check ip address doesn't run in instance. what need fix issue? thanks! check if user has voted before executing update sta

android - Tablet Device Dimensions imply orientation? -

so out of box question .. i wanted know; dimensions of android tablet imply orientation ?? in other words have android tablet, x width, , y height. if x > y imply orientation of screen in landscape , x < y imply screen portrait?? i think case .. need confirmation ! yes. landscape defined width>height.

javascript - Angular js ng-repeat is getting duplicated on using $apply? -

Image
i developing simple angular , node js app.it uses twitter streaming api.on end using express , socket.io along "twit" library. now here server.js var express=require('express'); var http=require('http'); var app=express(); var server=http.createserver(app); var io=require('socket.io').listen(server); server.listen(8080); var twit=require('twit'); app.use(express.static(__dirname+'/public')); app.get('/',function (req,res) { console.log("awd"); res.sendfile(__dirname+'/index.html'); }); var target=['ferrari']; var api=new twit({ consumer_key:'xxxx', consumer_secret:'xxxx', access_token:'xxxx', access_token_secret:'xxxx' }); io.sockets.on('connection',function(socket){ var stream=api.stream('statuses/filter',{track:target}) stream.on('tweet',function(tweet){ console.log(tweet.text);

python - Improve accuracy of scaling down image -

Image
i'm using python 2.7 , pil (pillow) i have script takes rough images of maze , makes cleaner, smaller image. sample input , output: which generated image: in case, script didn't work perfectly, worked pretty well. however, another image of same maze produced result: that's less good. i'm generating images displayed side-by-side looking @ average values each square on 16x16 grid, deciding if square represents black or white pixels. however, since perspective transformation isn't perfect, squares aren't lined up. are there algorithms accuracy? way @ squares of grid aren't square chunks? a piece of code: #this image transformed , thresholded, first half of side-by-side images thresh = image.open('thresholded_image.jpg') pixsize = thresh.size[0]/16 segments = [] in range(16): j in range(16): box = (j*pixsize,i*pixsize,(j+1)*pixsize,(i+1)*pixsize) segments.append(thresh.crop(box)) def blackwhite(image):

py.test - How are python module paths translated to filesystem paths? -

this may seem simple question, haven't found answer explains behavior i'm seeing. hard provide simple repro case have package structure this: a.b.c a.b.utils i have 1 project has files in a.b.c. (let's call aux_project ) , has files in a.b.d , a.b.utils , etc (call main_project ). i'm trying import a.b.utils inside pytest tests in first project, using tests_require . not work because a.b reason sourced inside aux_project/a/b/__init__.pyc instead of virtualenv , shadows other package (i.e. a.b has c in it, not d or utils ). happens in test context. in ipython can load packages fine, , correctly loaded virtualenv. what's weirder if delete actual directory, tests load pycs virtualenv , works (i need directory, though) python==2.7.9 what going on? ok, problem cwd prepended pythonpath. sys.path.pop(1) (0 tests dir, prepended pytest) resolved behavior.

python - How to perform multiple replacements on string in Jinja2? -

i have pelican website bootstrap3 theme. theme uses font awesome place icons links social media accounts. font awesome class names determined making link text lowercase , substituting spaces dashes. the problem is, link texts not map font awesome class names . example, envelope icon provided envelope class, want email link text on website. i can change class names in font awesome stylesheet, won't able use bootstrap cdn , have make such modifications every time update font awesome new version. i decided modify pelican template instead , make necessary transformations before class name written. far, code looks this: {% set name_sanitized = name|lower|replace('+','-plus')|replace(' ','-')|replace('stackexchange', 'stack-exchange')|replace('rss-feed', 'rss')|replace('email', 'envelope') %} can substitute chain of replace calls using dict ? this: {% set replacements = dict('+' =

git - How to manage secrets in a Microservice / Container / Cloud environment? -

microservices , cloud thing. talking , writing about. thinking lot topics: how can used benefit from? possible challenges? how can speedup daily development? , how manage things? 1 question bothers me since few days "how manage secrets in microservice / cloud environment?". imagine company 150 software engineers , various teams various products. every team creating software , every service needs various amounts of secrets (api-keys, passwords, ssh-keys, whatever). "old fashion" way create few configuration files in ini / yaml / txt format , read from. 12factor apps say: per env vars. env vars can set per machine , config files can placed there well. works if got hand full of machines , deployment done few system admins. 1 of general rules say: "don`t store secrets in git repo.". now new world comes in. ever team responsible application produce itself. should deployed , run team. our company moving container , self-service way (e.g. mesos , marath

Visual Studio Spaces issue -

is there way(settings or extensions) spaces , tabs behave in following way: any long string of spaces or tabs treated single unit. if cursor @ end of string, removes spaces, if single unit. tired of having hit backspace remove spaces @ end of function. ); *<- cursor @ *, ton of space between ; , * takes repeated spaces clear when hitting tab, insert largest amount of space match previous lines columns indentation, excluding empty lines. so this test // , <tab> *// jumps here, rather having hit tab mulitple times. when hitting enter, cursor indents previous indentation amount, using tabs. when starting new block(with {) next line indented, when ending block de-indented. that's want. i've never been able these types of features in visual studio. want tabs 4 spaces default grow or shrink depending on context. backspace consumes whitespace possible on given line, , tab try ali

performance - Intel Distribution for Python and Spyder IDE -

i've installed new intel distribution python because need performance improvements skull canyon nuc, don't understand how use packages/modules modified intel. i use anaconda spyder main ide, how can "tell" spyder not use anaconda standard/included packages/modules instead of new intel ones? thank answers! in spyder menu choose preferences click console , click advanced settings tab. there choose python interpreter, came intel distribution.

hadoop - java.io.IOException: Not a data file -

i processing bunch of avro files stored in nested directory structure in hdfs. files stored in year/month/day/hour format directory structure. i wrote simple code process sc.hadoopconfiguration.set("mapreduce.input.fileinputformat.input.dir.recursive","true") val rootdir = "/user/cloudera/rootdir" val rdd1 = sc.newapihadoopfile[avrokey[genericrecord], nullwritable, avrokeyinputformat[genericrecord]](rootdir) rdd1.count() i exception have pasted below. biggest problem facing doesn't tell me file not data file. have go in hdfs , scan through 1000s of files see 1 not data file. is there more efficient way debug/solve this? 5/11/01 19:01:49 warn tasksetmanager: lost task 1084.0 in stage 14.0 (tid 11562, datanode): java.io.ioexception: not data file. @ org.apache.avro.file.datafilestream.initialize(datafilestream.java:102) @ org.apache.avro.file.datafilereader.<init>(datafilereader.java:97) @ org.apache.avro.mapreduce.avrorec

directory - Create Folders By File Name With Delimiter -

i'm trying modify script magoo posted create folders based on file names , move associated files directories. there 2-4 files each instance same name different extensions. names delimited - (hyphen). these music files , therefore there multiple sets should moved folders titles reflect before delimiter. @echo off setlocal set "sourcedir=f:\test" pushd "%sourcedir%" /f "delims=-" %%a in ( 'dir /b /a-d *.mp3 *.cdg *.plx ' ) ( set "filename=%%a" set "dirname=%%a" call :genmove ) popd goto :eof :genmove if "%dirname:~-1%" neq " " set "dirname=%dirname:~0,-1%"&goto genmove set "dirname=%dirname:~0,-1%" md "%dirname%" move "%filename%" ".\%dirname%\" goto :eof my issues far: if define delimiter folders created files aren't moved. if eliminate delimiter files moved each set moved unique folder entire file name. using *.* in

Scala: Copying a generic case class into another -

i have following setup, want copy instance of basedata of moredata : sealed trait basedata { def weight: int def priority: int } sealed trait moredata { def weight: int def priority: int def t: string def id: string } case class data1(override val weight: int, override val priority: int) extends basedata case class moredata1 (override val weight:int, override val priority: int, override val t: string, override val id: string)extends moredata so copying mydata otherdata below: val mydata = data1(1,1) val otherdata = moredata1 (2,2,"c","abcd") would yield: moredata1(1,1,"c","abcd") . to this, want use function following signature, because have more 1 case class extending both basedata , moredata : def copyover[a <:basedata, b <:moredata](from: a, to: b) = {} i'm sure can shapeless , haven't figured out how. there examples ( here ) on copying case classes extending same trait, , others ( here )

javascript - How do I implement a transition animation in React? -

i have react component displays multiple pages of content. clicking buttons elsewhere in application should change component displays, given transition. transition custom javascript transition, , not css one, can't use reactcsstransitiongroup . there 2 approaches can think of. both involve passing in transition prop, differ on how next page passed component. option a this option uses presence of transition prop indicate should animate. keeps page1 in it's internal state can still render until transition complete. when completes component dispatches action causes parent component remove transition prop. each of steps render of pager component parent component. // 1 <pager currentpage={page1} /> // 2 <pager currentpage={page2} transition={transition} /> // 3 <pager currentpage={page2} /> option b this option passes in both transition , nextpage explicitly. again component dispatches action when transition complete. // 1 <pager curre

data analysis - Shorter method to replace entries in R -

this question has answer here: change values in multiple columns of dataframe using lookup table 2 answers i have started learning r recently. here's source file working ( https://github.com/cosname/art-r-translation/blob/master/data/grades.txt ). there anyway can change letter grade from, say, 4.0, a- 3.7 etc. without using loop? i asking because if there 1m entries, "for" loop might not efficient way modify data. appreciate help. since 1 of posters told me post code, thought of running loop see whether able it. here's code: mygrades<-read.table("grades.txt",header = true) <- (i in 1:nrow(mygrades)) { #print(i) #for now, see whether replaced 4.0. if(mygrades[i,1]=="a") { mygrades[i,1]=4.0 } else if (mygrades[i,2]=="a") { mygrades[i,2]=4.0 } else if (mygrades[i,3]=="a"