﻿ oipapio

### numpy - Plot an ellipse with python 2.7 knowing the equation

I have this equation, which define an ellipse. 7.91x^2 + -0.213xy + 5.46y^2 -0.031x -0.0896y = 1Of the general form: Ax^2 + Bxy + Cy^2 + Dx +Ey = 1I am using python 2.7 -- pythonxyOf course, I tried by trying to solve an array of points x and y but it doesn’t work. I used the approach from this question in the following code, but it does not show the desired ellipse.import numpy as npimport matplotlib.pyplot as pltz = -np.linspace(-0.5,+0.5,1000)x = np.linspace(-0.5,+0.5,1000)x,z = np.meshgrid(x,z)Z = -1 + 5.46*z**2X = 7.91*x**2plt.contour(x,z,...Read more

### python 2.7 - print_rows(num_rows=m, num_columns=n) in graphlab / turi not working

I using jupyter notebook and graphlab / turi for tfidf-nearest_neighbors model, which works fine so far.However, when I query the model like tfidf_model.query(Test_AD)I always just get the head - [5 rows x 4 columns]I am supposed to use "print_rows(num_rows=m, num_columns=n)" to print more rows and columns like:tfidf_model.query(Test_AD).print_rows(num_rows=50, num_columns=4)however, when I used it, I dont get any rows anymore, only the summary field:Starting pairwise querying.+--------------+---------+-------------+--------------+| Query point...Read more

### python 2.7 - How to just recieve timestamp, tweet-text and account name instead of this output I receive while working with twitter api?

This is my code. Instead of all the garbage values that I receive, how can I just output the text of the tweet, username and the timestamp?import oauth2 as oauthimport urllib2 as urllibaccess_token_key = "secret"access_token_secret = "secretconsumer_key = "secret"consumer_secret = "secret"_debug = 0oauth_token = oauth.Token(key=access_token_key, secret=access_token_secret)oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret)signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()http_method = "GET"http_handler = ur...Read more

### python 2.7 - Delete rows not present in all DataFrame in pandas

BackgroundThere is 5 DataFrames, I will call them b1, b2, b3, b4, b5.They have data structure which consists of the columns ['Date', 'Value'] I got the data from 2014 to 2015.ProblemEvery DataFrame has different date counting system. So, I want to get rid of the rows in the DataFrames which have non-matching dates.How can I do that?What I have triedSo, I will delete all the data if Date of the data is not included in all DataFrames: b1, b2, b3, b4, b5This works for the first timefor i in range(len(b2.index)): k = 0 for j in range(len(b1.i...Read more

### python 2.7 - label_keys type error on DNNCLassifier Tensorflow

I want to embed labels into a DNNClassifier model in Tensorflow.Unlike the documentation example, here , I get the following error message:label_keys_values = ["satan", "ipsweep", "nmap", "portsweep"] m = tf.contrib.learn.DNNClassifier(model_dir=model_dir, feature_columns=deep_columns, n_classes=4, hidden_units=[12, 4], label_keys=label_keys_values)m.fit(input_fn=train_input_fn, steps=200) File "embedding_model_p...Read more

### Python ConfigParser KeyError:

I am following an example to read a config file from the following https://wiki.python.org/moin/ConfigParserExamplesBut I get a keyError and can't figure out why. It is reading the files and I can even print the sections. I think I am doing something really stupid. Any help greatly appreciated.Here is the code...#!/usr/bin/env python# -*- coding: utf-8 -*-import ConfigParserimport loggingconfig_default=ConfigParser.ConfigParser()class Setting(object): def get_setting(self, section, my_setting): default_setting = self.default_section_m...Read more

### python 2.7 - KeyError Pandas Dataframe (encoding index)

I'm running the code below. It creates a couple of dataframes that takes a column in another dataframe that has a list of Conference Names, as its index. df_conf = pd.read_sql("select distinct Conference from publications where year>=1991 and length(conference)>1 order by conference", db) for index, row in df_conf.iterrows(): row[0]=row[0].encode("utf-8") df2= pd.DataFrame(index=df_conf['Conference'], columns=['Citation1991','Citation1992']) df2 = df2.fillna(0) df_if= pd.DataFrame(index=df_conf['Conference'], col...Read more

### python 2.7 - Attribute Dict -- TypeError raised when getting documentation

I wrote an "AttributeDict"-like object from the Alchin 'pro python' book, (below is taken almost directly from the book. My goal is to create a config object where the config fields are accessible as class attributes). class ADict(dict): def __setattr__(self,key,value): self[key] = value def __getattr__(self,key): return self[key]When I try to access the documentation I get a TypeError, related to a missing __name__ attribute (example below). >>> z = ADict()>>> help(z)line 1531, in docpager(render_doc(thing...Read more

### python 2.7 - obtaining the min value of time_diff for a Pandas Dataframe

I have a Pandas Dataframe which has a field txn['time_diff'] Send_Agent Pay_Agent Send_Time Pay_Time score \0 AKC383903 AXX100000 2014-08-19 18:52:35 2015-05-01 22:08:39 11 AWA280699 AXX100000 2014-08-19 19:32:18 2015-05-01 17:12:32 12 ALI030170 ALI030170 2014-08-26 10:11:40 2015-05-01 22:20:09 13 AKC403474 AXX100000 2014-08-19 20:35:53 2015-05-01 21:27:12 14 AED002616 AED002616 2014-09-28 18:37:32 2015-05-01 14:06:17 15 ALI030170 ALI030170 2014-08-20 05:08:03 20...Read more

### Multiprocessing a python function that contains a for loop

So I have a script that converts XML files to CSV, this script has a function that contains nested loops, juste 2 loop to be precise :FichList = [ f for f in os.listdir(FilenamePath) ]def SplitFichierR50 (l_FichList): for filename in FichList: if filename.count(".xml") ==1: print(filename) tree = etree.parse(FilenamePath+"/"+filename) for mes in tree.xpath("/R50/PRM/Donnees_Releve"): l_ID_PRM =mes.getparent()[0] EN_TETE=...Read more

### python 2.7 - Combining line plots (with data from DataFrames)

Cant figure out how to combine these two plots.Here is the relevant code:import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns%pylab inline #Jupyter Notebookdf_state.head()lm_orginal_plot.head()outputs for .head()df_state.loc['Alabama'][['month','total purchases', 'permit','permit_recheck']].plot(x='month',figsize=(6,3),linestyle='-', marker='o')lm_original_plot.plot(x='month',figsize=(6,3),linestyle=':');outputs for plots...Read more

### python 2.7 - Can numpy optimized code recieve significant increase in speed by rewriting it in Cython?

I have some python code doing numerical computations on 2d and 3d numpy arrays. The code is optimized in the way that it is not using any for loops, only numpy operations. All operations are done on float types.These are the numpy operations used: numpy.zeros, numpy.reshape, numpy.where, numpy.logical_or.reduce, numpy.put, numpy.add, numpy.subtract, numpy.true_devide, numpy.rintI ran some tests and the overhead lies within the numpy.where, numpy.put and numpy.rintoperations.My question is, since I already optimized the code in the sense that it...Read more

### amazon s3 - How to download a snappy.parquet file from s3 using Boto in Python

I'm new to this, and trying to download a snappy.parquet file from Amazon s3 I can later convert to CSV file. I tried working with the following example I've found online, and I get an empty folder. can anyone please help me? import botoimport sys, osfrom boto.s3.key import Keyfrom boto.exception import S3ResponseErrorDOWNLOAD_LOCATION_PATH =""BUCKET_NAME = ""AWS_ACCESS_KEY_ID= ""AWS_ACCESS_SECRET_KEY = ""conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_ACCESS_SECRET_KEY)bucket = conn.get_bucket(BUCKET_NAME)#goto through the list of filesbucket_l...Read more

### python 2.7 - Using ec2_snapshot getting error message "boto required for this module"

I am using Ubuntu Server 16.4 with ansible 2.4 on AWSMy playbook is trying to take snapshots of ec2 vol. See below- hosts: localhost connection: local become: yes become_method: sudo gather_facts: yes any_errors_fatal: True- name: Take snapshots of all volume" ec2_snapshot: volume_id: "{{item.id}}" description: "Taken on {{ ansible_date_time.date }}" snapshot_tags: frequency: hourly with_items: "{{ aws_ec2_vol_setting }}"I run the playbook with the following cmdansible-playbook -vvv pb_aws_backup_nw_us_sat.ymlUsi...Read more

### amazon web services - Scaling Instances in Elastic Beanstalk breaks dynamic image link of python flask app

The following code works brilliantly in local machine as well as in deployment at AWS Elastic BeanStalk - serves filxed image as well as dynamically created image. But, as soon as I scale the deployment to multiple EC2 instances, the dynamically created image becomes unavailable, even though I can find (by ssh) that dynamic image is present in the EC2 instance! I suspect, it has something to do with how I am referencing to the static images in html or the way the load balancer handles static images. But, have no clue where to begin the investig...Read more