text
stringlengths 226
34.5k
|
---|
How to get a list of Ostream or Oinfo in a variable from a repository path in gitpython?
Question: I currently have a valid git database with no packfile, but due to a bug
in`git-pack-objects` _(the process crashes with a stack dump file)_ I’m unable
to perform the`git repack`command.
I took a look at the error, and it’s linked to the C nature of the official
git project _(fixing would require changing core`struct`definitions)_ so, this
will takes a lot of time to fix.
The only alternative I found which don’t use C is gitdb _(part of gitpython)_.
However I wasn’t able to find how to use
the[`write_pack()`](http://gitdb.readthedocs.org/en/latest/api.html#gitdb.pack.PackEntity.write_pack)function.
Or more exactly, I have no idea on how to build
the[`object_iter`](http://gitdb.readthedocs.org/en/latest/api.html#gitdb.pack.PackEntity.create)parameter
from the database path from loose objects.
I don’t even know the exact class type used in
the[`object_iter`](http://gitdb.readthedocs.org/en/latest/api.html#gitdb.pack.PackEntity.create)list.
So, how to use gitdb for that purpose ?
Answer: Solved!
#/usr/bin/python
import os,sys,zlib,gitdb
from gitdb.db import LooseObjectDB
from gitdb.pack import PackEntity
from gitdb.util import bin_to_hex,hex_to_bin
ldb=LooseObjectDB(sys.argv[1]+'/.git/objects')
PackEntity.create((ldb.stream(sha) for sha in ldb.sha_iter()),sys.argv[1]+'/.git/objects/pack',object_count=ldb.size(),zlib_compression=zlib.Z_BEST_COMPRESSION)
|
Python if statement not working as expected. Code 'apparently' called twice
Question: I have this piece of code:
import bge
import GameLogic
import os
os.system("cls")
scene = GameLogic.getCurrentScene()
objects = scene.objects
objectCube = objects["Cube"]
visible = objectCube.visible
if visible == True:
objectCube.setVisible(False, True)
else:
objectCube.setVisible(True, True)
This code is supposed to toggle the visibility of an object but instead the
object disappears and immediately reappears in a split second. It looks as if
it just flickers. What am I doing wrong?
Also, don't worry about the other variables, they work fine. I have tested
them using some Console outputs.
Answer: **The problem:** The mouse sensor sends two signals per click, one for mouse
down and one for mouse up. Mouse down sends a positive signal while mouse up
sends negative.
You can test this by holding the mouse button down, the cube will disappear
and when you release the mouse it will return.
**The solution:** Use the sensor's `positive` property to determine if this is
a mouse up or down event.
import bge
import GameLogic
import os
os.system("cls")
scene = GameLogic.getCurrentScene()
objects = scene.objects
objectCube = objects["Cube"]
visible = objectCube.visible
# get the mouse sensor
cont = bge.logic.getCurrentController()
sens = cont.sensors['Mouse']
if sens.positive: # positive means a down button event
if visible == True:
objectCube.setVisible(False, True)
else:
objectCube.setVisible(True, True)
|
Python indentation error when creating a list
Question: I am getting an indentation error and I cant see why, I defined two lists of
dicts, the first one is fine, but the second one (which follows the same
format) is throwing an indentation error.
list one (no problems):
itemData = [{'id': 11, 'model': 'm1', 'serial': 'ser123', 'location': 3, 'distance': 2, 'loc': 3},
{'id': 12, 'model': 'm1', 'serial': 'ser456', 'location': 3, 'distance': 2, 'loc': 3}]
first version of list two:
itemData2 = [{'id': 11, 'model': 'm1', 'serial': 'ser123', 'location': 3, 'distance': 2, 'loc': 3},
{'id': 12, 'model': 'm1', 'serial': 'ser456', 'location': 3, 'distance': 2, 'loc': 3},
{'id': 13, 'model': 'm2', 'serial': 'ser678', 'location': 5, 'distance': 2, 'loc': 5}]
throws:
Traceback (most recent call last):
File "job_manager.py", line 1, in <module>
from NewJM import JobMonitor
File "C:\Users\Jonathan\Documents\Coding\Python\Logistics Code\NewJM.py", line 56
itemData2 = [{'id': 11, 'model': 'm1', 'serial': 'ser123', 'location': 3, 'distance': 2, 'loc': 3},
^
IndentationError: unindent does not match any outer indentation level
second version of list two:
itemData2 = [
{'id': 11, 'model': 'm1', 'serial': 'ser123', 'location': 3, 'distance': 2, 'loc': 3},
{'id': 12, 'model': 'm1', 'serial': 'ser456', 'location': 3, 'distance': 2, 'loc': 3},
{'id': 13, 'model': 'm2', 'serial': 'ser678', 'location': 5, 'distance': 2, 'loc': 5}
]
throws:
Traceback (most recent call last):
File "job_manager.py", line 1, in <module>
from NewJM import JobMonitor
File "C:\Users\Jonathan\Documents\Coding\Python\Logistics Code\NewJM.py", line 56
itemData2 = [
^
IndentationError: unindent does not match any outer indentation level
I am confused as to why this is happening, especially since the first version
of list two is a direct copy of list one only with the addition of another
dict. Any ideas?
Answer: It's look like you have tabs with spaces mix in your code. Symple copy-paste
of your code from your question works correctly.
|
Pythonic way to perform urljoin operation on each value of a column in Pandas dataframe (Python 3.4)
Question: I have Pandas dataframe where one of the columns "url" contains a relative url
path. The values in this column needs to be appended with the base url to be
converted into absolute url.
I am sure looping through each row of the column is not the best approach. I
am able to do this by using Lambdas operation. However the lambdas seem a bit
magic for me and I am not so comfortable with it.
Can you recommmenda better way of doing this? Thanks.
from urllib.parse import urljoin
import pandas as pd
.
base_url = "http://www.website.com"
.
my_df["relatie_url"] = my_df["relatie_url"].map(lambda x : urljoin(base_url, x))
Answer: IIUC you can just do:
my_df["relatie_url"] = base_url + my_df["relatie_url"]
This will be much quicker than calling `map`
Example:
In [12]:
df = pd.DataFrame({'site':['/home/index.html', '/images/src']})
df
Out[12]:
site
0 /home/index.html
1 /images/src
In [13]:
base_url = "http://www.website.com"
df['site'] = base_url + df['site']
df
Out[13]:
site
0 http://www.website.com/home/index.html
1 http://www.website.com/images/src
|
Simple pagination of Django class-based listview failing, template caching to blame?
Question: In a web-based social Django app I have, there's a feature that allows users
to see all unique users who had a session in the past 5 mins. For this, I'm
using [django user_sessions](https://pypi.python.org/pypi/django-user-
sessions), a plugin that
> makes session objects a first class citizen like other ORM objects.
These recent users are displayed as a list on a template. Each name generated
is clickable on this template - clicking it takes the clicker to the clickee's
profile page. To accomplish that, I've simply wrapped each username in this
tag: `<a href="{% url 'profile' slug=unique_session.user.username
%}#section0"></a>`. This template is **cached** , via using the template tags:
`{%load cache %}{%% cache 30 template_fragment_2 %}{% endcache %}`
Furthermore, the list of recent online users is paginated by 75 (accomplished
via adding `paginate_by = 75` in the `listview` that generates the said list).
Here is the problem: the list of recent users loads up fine in the template
(and clicked usernames lead to correct profiles), but once a user presses
"next page" (_i.e. there were more than 75 people to show_), I get the error:
**django.core.urlresolvers:NoReverseMatch: Reverse for 'profile' with
arguments '()' and keyword arguments '{u'slug': ''}' not found.** After a lot
of debugging, I still have no idea why this is happening. Is it because of
`cache` and `pagination`? Help!
* * *
The view that generates the list is as follows:
from user_sessions.models import Session
class OnlineView(ListView):
model = Session
template_name = "online.html"
paginate_by = 75
def get_queryset(self):
unique_user_sessions = Session.objects.filter(last_activity__gte=(timezone.now()-timedelta(minutes=5))).only('user').distinct('user')
return unique_user_sessions
And the code in the template is:
{% extends "base.html" %}
{% block content %}
{% load cache %}
{% cache 30 template_fragment2 %}
<div class="margin">
<ol>
{% for unique_session in object_list %}
<li>
<a href="{% url 'profile' slug=unique_session.user.username %}#section0">
{% if unique_session.user.userprofile.avatar %}
<img src="{{ unique_session.user.userprofile.avatar.url }}" alt="no pic" height="20" width="20"></img>
{% else %}
<img src="{{ STATIC_URL }}img/default-avatar.jpg" alt="no pic" height="20" width="20"></img>
{% endif %}
{{ unique_session.user.username }}
</a>
</li>
{% endfor %}
</ol>
</div>
{% endcache %}
{% endblock %}
{% block pagination %}
{% if is_paginated %}
<div class="pagination">
{% if page_obj.has_previous %}
<a href="?page={{ page_obj.previous_page_number }}#section0">back</a>
{% endif %}
{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}#section0">forward</a>
{% endif %}
</div>
{% endif %}
{% endblock %}
And here are relevant urlpatterns:
url(r'^users/(?P<slug>[\w.@+-]+)/$', UserProfileDetailView.as_view(), name='profile'),
url(r'^online/$', auth(OnlineView.as_view()), name='online'),
* * *
Lastly,
Stack trace
Traceback (most recent call last):
File "/app/.heroku/python/bin/gunicorn", line 11, in <module>
File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 74, in run
File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/base.py", line 189, in run
File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/base.py", line 72, in run
File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 174, in run
File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 477, in manage_workers
File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 540, in spawn_workers
File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 507, in spawn_worker
File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/base.py", line 124, in init_process
File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 119, in run
File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 66, in run_for_one
File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 30, in accept
File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 130, in handle
File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 176, in handle_request
File "/app/.heroku/python/lib/python2.7/site-packages/newrelic-2.56.0.42/newrelic/api/web_transaction.py", line 704, in __iter__
File "/app/.heroku/python/lib/python2.7/site-packages/newrelic-2.56.0.42/newrelic/api/web_transaction.py", line 1080, in __call__
File "/app/.heroku/python/lib/python2.7/site-packages/dj_static.py", line 83, in __call__
File "/app/.heroku/python/lib/python2.7/site-packages/newrelic-2.56.0.42/newrelic/api/web_transaction.py", line 1208, in _nr_wsgi_application_wrapper_
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 255, in __call__
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py", line 140, in get_response
File "/app/.heroku/python/lib/python2.7/site-packages/django/template/response.py", line 105, in render
File "/app/.heroku/python/lib/python2.7/site-packages/django/template/response.py", line 82, in rendered_content
File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py", line 140, in render
File "/app/.heroku/python/lib/python2.7/site-packages/newrelic-2.56.0.42/newrelic/api/function_trace.py", line 98, in dynamic_wrapper
File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py", line 134, in _render
File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py", line 830, in render
File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py", line 844, in render_node
File "/app/.heroku/python/lib/python2.7/site-packages/django/template/loader_tags.py", line 124, in render
File "/app/.heroku/python/lib/python2.7/site-packages/newrelic-2.56.0.42/newrelic/api/function_trace.py", line 98, in dynamic_wrapper
File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py", line 134, in _render
File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py", line 830, in render
File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py", line 844, in render_node
File "/app/.heroku/python/lib/python2.7/site-packages/newrelic-2.56.0.42/newrelic/hooks/framework_django.py", line 702, in wrapper
File "/app/.heroku/python/lib/python2.7/site-packages/django/template/loader_tags.py", line 63, in render
File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py", line 830, in render
File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py", line 844, in render_node
File "/app/.heroku/python/lib/python2.7/site-packages/django/templatetags/cache.py", line 34, in render
File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py", line 830, in render
File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py", line 844, in render_node
File "/app/.heroku/python/lib/python2.7/site-packages/django/template/defaulttags.py", line 195, in render
File "/app/.heroku/python/lib/python2.7/site-packages/django/template/defaulttags.py", line 424, in render
Answer: The pagination code itself is fine. I think the issue is that some of the
`user` objects that is being returned on the second page of results have an
empty `username`, which is what causes the `NoReverseMatch` error.
The most likely cause of this is that `user` object being returned is an
[anonymous
user](https://docs.djangoproject.com/en/1.8/ref/contrib/auth/#anonymous-users)
\- the `username` is always an empty string in this case.
To verify try modifying your template by wrapping that block in this check:
{% if not unique_session.user.is_anonymous %}
<li>
<a>...
</a>
</li>
{% endif %}
|
Disable menu item unless exactly one item is selected with PySide
Question: Working with a [`QMenu`](http://doc.qt.io/qt-4.8/qmenu.html) in PySide, I want
to disable a menu item based on a
[`QListWidget`](http://doc.qt.io/qt-4.8/qlistwidget.html) selection count. If
the selection count is exactly one then the 'Edit Item' action should be
enabled, otherwise it should be disabled. How can I do this?
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Modules
# ------------------------------------------------------------------------------
import sys
from PySide import QtGui, QtCore
# Variables
# ------------------------------------------------------------------------------
listItems = ["A","B","C","D","E","F","G"]
# widget
# ------------------------------------------------------------------------------
class Example(QtGui.QWidget):
def __init__(self,):
super(Example, self).__init__()
self.initUI()
def initUI(self):
# formatting
self.setGeometry(300, 300, 250, 300)
self.setWindowTitle("Input List")
# widgets
self.itemList = QtGui.QListWidget()
self.itemList.addItems(listItems)
self.itemList.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
# context menu
self.edit_menu = QtGui.QMenu()
removeItem = self.edit_menu.addAction('Remove Item')
removeItem.triggered.connect(self.RemoveItem)
editItem = self.edit_menu.addAction('Edit Item')
editItem.triggered.connect(self.EditItem)
self.itemList.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.itemList.customContextMenuRequested.connect(self.on_context_menu)
self.itemList.itemDoubleClicked.connect(self.EditItem)
# layout
self.mainLayout = QtGui.QGridLayout(self)
self.mainLayout.addWidget(self.itemList, 0, 0)
self.show()
def on_context_menu(self, pos):
self.edit_menu.exec_(self.mapToGlobal(pos))
def EditItem(self):
print "Edit Item"
def RemoveItem(self):
print "Remove Item"
# Main
# ------------------------------------------------------------------------------
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Answer: There are a few changes you need to make, but you can do this by disabling the
[`QAction`](http://doc.qt.io/qt-4.8/qaction.html#enabled-prop).
First change, make your `editItem` variable accessible throughout the class.
self.editItem = self.edit_menu.addAction('Edit Item')
self.editItem.triggered.connect(self.EditItem)
(You may want to do this to the `remoteItem` as well, for consistency)
Next, in `on_context_menu`, you need to check how many items you have
selected. Then you enable/disable your menu option based on that logic:
def on_context_menu(self, pos):
if len(self.itemList.selectedItems()) == 1:
self.editItem.setEnabled(False)
else:
self.editItem.setEnabled(True)
self.edit_menu.exec_(self.mapToGlobal(pos))
* * *
Examples:
With only one item selected:
[](http://i.stack.imgur.com/2qJO1.png)
With more than one item selected:
[](http://i.stack.imgur.com/EJsbC.png)
|
Postgres says key already exists although it doesn't
Question: My Python application uses Psycopg2 to insert content from a web scraper to a
PostgreSQL database. Psycopg2 complains that a certain primary key already
exists even though it clearly doesn't.
Error:
psycopg2.IntegrityError: duplicate key value violates unique constraint "my_table_pkey"
DETAIL: Key (id)=(12345) already exists.
Query:
SELECT * FROM my_table where id=12345;
-- 0 rows returned
What is going on here?
**Edit for background:**
Basically, what the code does is scrape a discussion forum, loops over each
page in each discussion thread and inserts some data from each thread into
Postgres. The general structure of the code is outlined below. Note that `get`
returns a well formatted data structure for each thread.
import psycopg2
base_url 'http://someforum.com'
conn = psycopg2.connect('dbname=mydb user=me')
for i in range(10000):
thread = get('{}/'{}.format(base_url, i)
for page in thread:
sql = 'INSERT INTO my_table (id, foo, bar) VALUES(%s, %s, %s);'
values = [page['id'], page['foo'], page['bar']]
cur.execute(sql, values)
conn.commit()
cur.close()
conn.close()
Answer: After some digging, I discovered that the forum I'm scraping sometimes returns
an erroneous number of pages for a given thread. So when the app tries to
scrape page number 5 (which does not exist), it is instead redirected to page
number 4 and tries to insert the same posts again. Hence the integrity error.
|
Python-tkinter: For loop supposed to collect entries from an array and pass to text box, only passes last entry
Question: I'm new to coding, so apologies if this question is a little base. Anyways,
this GUI im making in python is supposed to collect several user entries, and
pass them to a text box in the GUI. Right now though, the for loop at the end
of the code is only putting the last entry into the text box. Why?
from Tkinter import *
class Application(Frame):
""" A SPC program that takes user input and saves the file """
def __init__(self,master):
""" initializes the frame """
Frame.__init__(self,master)
self.grid()
#creates an array to store entries into
self.entry_list = [None]*7
self.create_widgets()
def create_widgets(self):
"""create widgets for user inputted data"""
# creates a text widget next to the entries that displays what the user has input
Label(self, text = "Do these values you entered seem correct?").grid(row = 0, column = 4, sticky = W, padx = 5, pady = 5)
self.checktext = Text(self, width =15, height = 42, wrap = WORD)
self.checktext.grid(row = 1, rowspan = 10, column = 4, sticky = W, padx =5, pady =5)
# get name
Label(self, text = "First Name:").grid(row = 0, column = 0, sticky = W, padx=5, pady=5)
self.entry_list[0] = Entry(self)
self.entry_list[0].grid(row = 0, column = 1)
Label(self, text = "Last Name:").grid(row = 1, column = 0, sticky = W, padx=5, pady=5)
self.entry_list[1] = Entry(self)
self.entry_list[1].grid(row = 1, column = 1)
# get work order
Label(self, text = "Work Order Number:").grid(row = 2, column = 0, sticky = W, padx=5, pady=5)
self.entry_list[2] = Entry(self)
self.entry_list[2].grid(row = 2, column = 1)
# get todays date
Label(self, text = "Todays Date:").grid(row = 3, column = 0, sticky = W, padx=5, pady=5)
self.entry_list[3] = Entry(self)
self.entry_list[3].grid(row = 3, column = 1)
# get bubble number
Label(self, text = "Bubble Number:").grid(row = 4, column = 0, sticky = W, padx=5, pady=5)
self.entry_list[4] = Entry(self)
self.entry_list[4].grid(row = 4, column = 1)
# get USL and LSL
Label(self, text = "USL:").grid(row = 5, column = 0, sticky = W, padx=5, pady=5)
self.entry_list[5] = Entry(self)
self.entry_list[5].grid(row = 5, column = 1)
Label(self, text = "LSL:").grid(row = 6, column = 0, sticky = W, padx=5, pady=5)
self.entry_list[6] = Entry(self)
self.entry_list[6].grid(row = 6, column = 1)
# button to submit user entered values up to the input data values portion of the gui
self.button = Button(self)
self.button["text"] = "Submit"
self.button["command"] = self.submit
self.button.grid(row = 5, column = 2, sticky = W, padx=5, pady=5)
# creates a spot to dictate whether USL and LSL are correct
self.checklimits = Text(self, width = 20, height = 3, wrap = WORD)
self.checklimits.grid(row = 6, column = 3, sticky = W, padx = 5)
"""# get User Input Data values
Label(self, text = "Enter Results:").grid(row = 7, column = 0, sticky = W, padx=5, pady=5)
self.entry_list8 = Text(self, width = 15, height = 30)
self.entry_list8.grid(row = 7, column = 1) """
def submit(self):
""" submits user data up to input data section of GUI and checks USL vs LSL"""
# checks to make sure limits were imput properly
USL = int(self.entry_list[5].get())
LSL = int(self.entry_list[6].get())
if USL > LSL:
message = "Limits are good"
else:
message = "USL can't be less than LSL, please re-enter USL and LSL"
self.checklimits.delete(0.0, END)
self.checklimits.insert(0.0, message)
# puts entries into text box
for x in self.entry_list:
entry = x.get()
if entry:
self.checktext.delete(0.0, END)
self.checktext.insert(END, entry + "\n")
root = Tk()
root.title("SPC Input Program")
root.geometry("700x750")
app = Application(root)
Answer: The problem is here:
for x in self.entry_list:
entry = x.get()
if entry:
self.checktext.delete(0.0, END)
self.checktext.insert(END, entry + "\n")
You're deleting everything in the widget before putting the next string into
it, every time. To fix the issue, simply don't delete everything every time.
If you want to clear the widget before repopulating it, move the deletion out
of the loop:
self.checktext.delete(0.0, END)
for x in self.entry_list:
entry = x.get()
if entry:
self.checktext.insert(END, entry + "\n")
|
PermissionError when moving image after being opened in Pillow
Question: I have a small script for tallying pagecounts in multi-page TIFFs before
moving them to another drive; but whether or not I explicitly close the images
after opening them with Pillow, I keep getting a PermissionError when
subsequently trying to move the file:
Traceback (most recent call last):
File "C:\Python34\lib\shutil.py", line 522, in move
os.rename(src, real_dst)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'c:/users/barry/desktop/bort.tiff' -> 'c:/users/barry/desktop/bart.tiff'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#75>", line 1, in <module>
shutil.move('c:/users/barry/desktop/bort.tiff', 'c:/users/barry/desktop/bart.tiff')
File "C:\Python34\lib\shutil.py", line 535, in move
os.unlink(src)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'c:/users/barry/desktop/bort.tiff'
I've tried each of the following methods, plus other variations I've already
forgotten:
import os
import shutil
from PIL import Image
name1 = 'C:/Users/Barry/Desktop/bort.tiff' # This file exists.
name2 = 'C:/Users/Barry/Desktop/bart.tiff' # This file doesn't.
# Attempt 1:
img = Image.open(name1)
pgs = img.n_frames
img.close() # Tried both with and without this in each attempt.
shutil.move(name1, name2) # Tried both shutil.move and os.rename
# Attempt 2:
with Image.open(name1) as img:
pgs = img.n_frames
img.close()
shutil.move(name1, name2)
# Attempt 3:
with Image.open(name1) as img:
pgs = img.n_frames
img.close()
shutil.move(name1, name2)
# Attempt 4:
with open(name1, 'rb') as file:
with Image.open(file) as img:
pgs = img.n_frames
img.close()
shutil.move(name1, name2)
Even containing each distinct operation in different functions made no
difference.
Where am I going wrong?
I'm using Pillow v3.0.0 with Python v3.4.2 on both Win7 and Win10.
Answer: What you are facing over here is [Sharing Violation
Error](https://mail.python.org/pipermail/python-win32/2011-August/011738.html)
to avoid that you should use Win32file.movefile for further information you
should [go
to](https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=8&cad=rja&uact=8&ved=0CEYQFjAHahUKEwiM_fDr0_3IAhVHk3IKHY4NBrM&url=https%3A%2F%2Fmsdn.microsoft.com%2Fen-
us%2Flibrary%2Fwindows%2Fdesktop%2Faa365239\(v%3Dvs.85\).aspx&usg=AFQjCNFzN2v3_4rAKs7M37jkzjGqAuZrPw&sig2=k24rYo93ne19Lm2_1Ub-
Fw&bvm=bv.106923889,d.d24)
win32file.MoveFile(source, target)
will do the work.
|
Python BeautifulSoup find_all 'ascii' codec can't decode byte
Question: I'm using BeautifulSoup for extraction of the links to different electoral
subregions outcomes from [Krasnodar krai
elections](http://www.krasnodar.vybory.izbirkom.ru/region/region/krasnodar?action=show&root=1&tvd=2232000821586&vrn=2232000821581®ion=23&global=&sub_region=23&prver=2&pronetvd=1&vibid=2232000821586&type=381).
The links from html could be detected using word 'option'. html snippet:
<form name="go_reg">Нижестоящие избирательные комиссии: <select name="gs"><option val="">---</option>
<option value="http://www.krasnodar.vybory.izbirkom.ru/region/krasnodar?action=show&root=123400103&tvd=2232000821616&vrn=2232000821581&prver=2&pronetvd=1&region=23&sub_region=23&type=381&vibid=2232000821616">1 Абинская</option>
<option value="http://www.krasnodar.vybory.izbirkom.ru/region/krasnodar?action=show&root=123402603&tvd=2232000821591&vrn=2232000821581&prver=2&pronetvd=1&region=23&sub_region=23&type=381&vibid=2232000821591">2 Анапская</option>
Here is my code:
import urllib2
from bs4 import BeautifulSoup
contenturl = "http://www.krasnodar.vybory.izbirkom.ru/region/region/krasnodar?action=show&root=1&tvd=2232000821586&vrn=2232000821581®ion=23&global=&sub_region=23&prver=2&pronetvd=1&vibid=2232000821586&type=381"
soup = BeautifulSoup(urllib2.urlopen(contenturl).read(), 'html.parser', from_encoding = 'windows-1252')
soup.find_all('option')
However, I got following error:
UnicodeDecodeError:'ascii' codec can't decode byte 0xc3 in position 283: ordinal not in range(128)
I tried to find the answer, and one of suggestions was to set the encoding
manually using "from_encoding" option, but this did not resolve the issue
Answer: If you change your beautiful soup open, you can avoid the error.
from bs4 import BeautifulSoup
from urllib.request import urlopen
url = "http://www.krasnodar.vybory.izbirkom.ru/region/region/krasnodar?action=show&root=1&tvd=2232000821586&vrn=2232000821581®ion=23&global=&sub_region=23&prver=2&pronetvd=1&vibid=2232000821586&type=381" #/air-jordan-1-retro-high-og-unc-white-dk-powder-blue-012304"
page=urllib.request.urlopen(url)
soup = BeautifulSoup(page.read())
for myValue in soup.find_all('option'):
try:
print(myValue.get_text() + " : " + myValue.get("value"))
except:
print("")
It generates
1 Àáèíñêàÿ : http://www.krasnodar.vybory.izbirkom.ru/region/krasnodar?action=show&root=123400103&tvd=2232000821616&vrn=2232000821581&prver=2&pronetvd=1®ion=23&sub_region=23&type=381&vibid=2232000821616
2 Àíàïñêàÿ : http://www.krasnodar.vybory.izbirkom.ru/region/krasnodar?action=show&root=123402603&tvd=2232000821591&vrn=2232000821581&prver=2&pronetvd=1®ion=23&sub_region=23&type=381&vibid=2232000821591
3 Àïøåðîíñêàÿ : http://www.krasnodar.vybory.izbirkom.ru/region/krasnodar?action=show&root=123400203&tvd=2232000821617&vrn=2232000821581&prver=2&pronetvd=1®ion=23&sub_region=23&type=381&vibid=2232000821617
....etc
|
How do I use file descriptors other than std[in/out/err] in python?
Question: I need to pipe two streams of data to an external program from a Python (3.4)
script. One can go to STDIN, and I'm ok on that:
from subprocess import check_output
data1 = b'This is the data to pass on stdin'
check_output(['externalprogram'], input=data1)
The program can accept the other piece on a file descriptor given on the
command line, but how do I tell python to send data on another fd?
data2 = b'This is the data to pass on fd 3'
check_output(['externalprogram', '-data2fd', '3'], input=data1, ???)
I imagine I may need to go a layer deeper and use `Popen`, but I still don't
see how to do it.
Answer: On linux at least, you can use `os.pipe` to create a pipe. When the child is
called, it inherits the parent pipe. The parent should close the read end to
avoid spurious signals, then write to the write side of the pipe. The child
can then read from the read end of the pipe.
|
Simple Matplotlib animate not working
Question: I am trying to run this code below but it is not working properly. I've
followed the documentation from matplotlib and wonder what is wrong with this
simple code below. I am tryting to animate this into jupyter notebook with
anaconda distro. My python version is 2.7.10.
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
fig = plt.figure()
def init():
m = np.zeros(4800)
m[0] = 1.6
return m
def animate(i):
for a in range(1,4800):
m[a] = 1.6
m[a-1] = 0
return m
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)
plt.show()
Answer: You need to create an actual plot. Just updating a NumPy array is not enough.
Here is an example that likely does what you intend. Since it is necessary to
access the same objects at multiple places, a class seems better suited as it
allows to access instance attributes via `self`:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
class MyAni(object):
def __init__(self, size=4800, peak=1.6):
self.size = size
self.peak = peak
self.fig = plt.figure()
self.x = np.arange(self.size)
self.y = np.zeros(self.size)
self.y[0] = self.peak
self.line, = self.fig.add_subplot(111).plot(self.x, self.y)
def animate(self, i):
self.y[i - 1] = 0
self.y[i] = self.peak
self.line.set_data(self.x, self.y)
return self.line,
def start(self):
self.anim = animation.FuncAnimation(self.fig, self.animate,
frames=self.size, interval=20, blit=False)
if __name__ == '__main__':
ani = MyAni()
ani.start()
plt.show()
|
Python 2.7 mediainfo --inform outputs full info rather than one string
Question: Using the following in powershell produces the expected output of
`01:22:02:03`:
MediaInfo --Language=raw --Full --Inform="Video;%Duration/String4%" filename
My following python 2.7 script always gives the full mediainfo output with
every piece of metadata, not just the Duration String that I specified.. I've
tried escaping the semi colons but it has no effect. What am I doing wrong?
import sys
import subprocess
filename = sys.argv[1]
test = subprocess.check_output(['MediaInfo', '--Language=raw', '--Full', '--inform="Video;%Duration/String4%"', filename])
print test
Answer: Lose the double-quotes in the `--Inform` argument. I can reproduce your
problem with this code:
import subprocess
args = [
'mediainfo',
'--Language=raw',
'--Full',
'--inform="Video;%Duration/String4%"',
'tests/reference.mp4'
]
bad_output = subprocess.check_output(args)
line_count_bad = len(bad_output.splitlines())
args[3] = args[3].replace('"', '')
good_output = subprocess.check_output(args)
line_count_good = len(good_output.splitlines())
print(line_count_bad, line_count_good, sep='\t')
print(good_output)
The output is:
204 1
b'00:00:07:08\n'
|
Error: name "blue" not defined
Question: When the user chooses option 4 on `hall()`, it should run `blue()`, but when I
try to run it I get an error saying that `blue()` is not defined. How do I fix
this?
import time
import sys
name = input ("Name: ")
print ("Hello", (name), ", and welcome to my game that i made to learn python.")
print ("How to play the game, just type the number its not that hard.")
time.sleep(5)
def intro():
print ("You are in a room, to the south there is a torch on the wall and to the north there is a door.")
time.sleep(5)
print ("Your options are: ")
time.sleep(3)
print ("1. Do nothing")
print ("2. Go south and pick up the torch")
print ("3. Go north, open and go through the door")
print ("4. You decide to build an orphanage in the room, makes sense.")
choice = input(">>> ")
if choice == "1":
print("You decide to curl into a ball and go to sleep, you never wake up again. --GAME OVER--")
print("I guess you could try again if you must.")
time.sleep(5)
intro()
elif choice == "2":
print("You walk southwards towards the wall, grab the torch off the wall and hold it in your hands.")
print("You walk over towards the door and open it")
time.sleep(5)
elif choice == "3":
print("You walk over towards the door and open it, on the other side there is a dark corridor, you step forward and the door closes behind you. You get surrounded in darkness and die. --GAME OVER--")
print("I guess you could try again if you must.")
time.sleep(5)
intro()
elif choice == "4":
print("You can't build an orphanage in a room with nothing there idiot, you wasted your whole life attempting. --GAME OVER--")
print("I guess you could try again if you must.")
time.sleep(5)
intro()
else:
print("Type the correct number idiot")
intro()
intro()
def hall():
print ("As you open the door a strong gust of cold air comes through making the torch flicker")
time.sleep(3)
print ("You continue up the corridor with the torch illuminating your surroundings, you feel like your being watched")
time.sleep(3)
print ("You keep walking for what seems like hours and you finally come across a part where the corridor splits off into 3 different ones")
print ("What do you do?")
print ("1. Go north.")
print ("2. Go east.")
print ("3. Go back the way you came.")
print ("4. Go west.")
time.sleep(5)
hall()
choice = input(">>> ")
if choice == "1":
print("You head north but as soon as you do the ground under you crumbles and you fall. And die. --GAME OVER--")
print("I guess you could try again if you must.")
time.sleep(5)
hall()
elif choice == "2":
print("You go down the east corridor and get a glimpse of a dark red light before it disappears.")
print("You continue to walk")
time.sleep(5)
red()
elif choice == "3":
print("Well done, you just went back to the place you wanted to get out from, your legs are tired and your torch has gone out. idiot. --GAME OVER--")
print("I guess you could try again if you must.")
time.sleep(5)
hall()
elif choice == "4":
print("You go down the west corridor and get a glimpse of a dark blue light before it disappears.")
print("You continue to walk")
time.sleep(5)
blue()
else:
print("Type the correct number idiot")
time.sleep(5)
hall()
def red1():
print ("As you continue to walk down the corridor the air around you seems to head up more and more.")
time.sleep(3)
print ("You come around a little podium and on it is a piece of paper with the numbers 264 894 written on it")
time.sleep(3)
print ("You go to pick it up but it crumbles into dust and under the dust are the words blue carved into the podium")
time.sleep(3)
print ("you continue walking")
time.sleep(3)
print ("After a while you come across a shiny iron door with a keypad by the side on the keypad it spells the words red on it.")
time.sleep(3)
print ("You attempt to enter the correct code.")
red1()
code1 = input(">>> ")
if code1 == "362 682":
print ("The door slides open without making a noise, you step into the door and continue walking")
else:
print ("Incorrect code. Hint:RED")
print ("restarting...")
time.sleep(10)
intro()
def blue1():
print ("As you continue to walk down the corridor the air around you seems to get colder and colder more and more.")
time.sleep(3)
print ("You come around a little podium and on it is a piece of paper with the numbers 362 682 written on it")
time.sleep(3)
print ("You go to pick it up but it crumbles into dust and under the dust are the words red carved into the podium")
time.sleep(3)
print ("you continue walking")
time.sleep(3)
print ("After a while you come across a rusty iron door with a keypad by the side on the keypad it spells the words red on it.")
time.sleep(3)
print ("You attempt to enter the correct code.")
blue1()
code2 = input(">>> ")
if code2 == "264 894":
print ("The door slides open without making a noise, you step into the door and continue walking")
else:
print ("Incorrect code. Hint:BLUE")
print ("restarting...")
time.sleep(10)
intro()
Answer: nice story btw). anyway to the problem. you call function blue() that is not
defined in your code - there is no such function ). if you meant to call
blue1() you will get an error and that's because you first need to **declare
the function before using it** for example:
1.this will not work:
blue()
def blue(): ...
2. this will work:
def blue(): ...
blue()
any way for good practice its good to maintain a simple code structure, all
functions above and the main is the last one that calls other function.
|
IOError: [Errno 2] No such file or directory on Mac
Question: I've tried to open a file that does exist but I keep getting an error message
of:
No such file or directory on Mac
I have made sure it is in the same directory as the python code. I've also
tried changing the name of the excel doc and whether the doc is `.xls` and
`.xlsx` but it has not worked.
Here are several versions I've tried, but so far they all give me the same
result.
import os.path
book = open(os.path.expanduser("~/Desktop/Crimes.xlsx"))
or
import xlrd
import os.path
book = xlrd.open_workbook(os.path.join("/Users/caitlinwesterfield",'Crime.xls')
or
import xlrd
book = xlrd.open_workbook('Crime.xls')
or
import xlrd
book = open('/Users/caitlinwesterfield/Desktop/Crime.xls', "r")
or
import xlrd
book = open("~/Crime.xls", "r")
or
import xlrd
book = open(os.path.expanduser(r"~/Desktop/Crime.xls"))
or
import xlrd
book = open('Crime.xls')
or
import xlrd
book = open(os.path.expanduser("/Users/caitlinwesterfield/Desktop/Crime.xls"))
or
import xlrd
import os
book = xlrd.open_workbook(os.path.join("/Users/caitlinwesterfield","TypesOfCrime.xls"))
or
import xlrd
book = xlrd.open_workbook("typesofcrime.xls")
Answer: Have you tried checking if there was a permissions issue?
Open up your terminal and cd to the right directory
cd -l
Here is what those permissions mean:
rwxrwxrwx <-- r refers to read, w to write, and x to execute
--------- <-- a hyphen refers to the permission not existing
[](http://i.stack.imgur.com/xpdbm.png)
Try running:
chmod 777 Crimes.xlsx
# you might need to add sudo if you get permission error:
sudo chmod 777 Crimes.xlsx
[image source and more info](http://www.techradar.com/how-
to/computing/apple/terminal-101-file-permissions-1305647)
[how to use the terminal](http://www.macworld.co.uk/feature/mac-software/get-
more-out-of-os-x-terminal-3608274/)
|
Perl Command Line Arguments Used In Regular Expressions
Question: Given various strings in a text file that are in this format:
199.72.81.55 - - [01/Jul/1995:00:00:01 -0400] "GET /history/apollo/ HTTP/1.0" 200 6245
I am trying to read in a number from the command line like this:
type small_access_log_Jul95_01.txt | perl FLTR_WLOG_STATUS_CODES.pl 200
The "small_access_log" txt file contains a line of the format before given on
each line. I am having trouble reading in and using the argument "200" in a
search, because it assigns 200 to be the first argument, it seems. Here is the
code that I'm working on:
use strict;
use warnings;
while ( <> ) {
if ($_ =~ /"[$ARGV[1]]"/){
print $_;}
}
It is only supposed to print the lines that contain that "200" or whatever is
input through the command line.
Here is the working version in python:
import sys
import re
TEXT = sys.argv[1]
for n in [x for x in sys.stdin.readlines() if re.search(".*?"+re.escape(TEXT) +"\s([0-9]+)$",x)]:
print n
So what do I need to do differently with the command line in perl to make this
work?
Answer: The first parameter to a Perl program is in `$ARGV[0]`, and the empty diamond
operator reads data from the files named in `@ARGV`
You need to write your program like this. It removes the pattern parameter
from the end of `@ARGV` before using it in the loop, and takes advantage of
Perl's `$_` variable being the default parameter to many operators
The `\Q` in the regex forces all following non-alphanumeric characters to be
escaped, and hence taken literally. That includes the square brackets and the
_contents_ of `$pattern`, which may otherwise be taken as regex metacharacters
with a special meaning
use strict;
use warnings;
my $pattern = pop @ARGV;
while ( <> ) {
print if /\Q[$pattern]/;
}
and you should run it like this
perl FLTR_WLOG_STATUS_CODES.pl small_access_log_Jul95_01.txt 200
### Update
If you're forced to accept the data input from STDIN instead of from a
command-line file name, then you need to do this
use strict;
use warnings;
my $pattern = pop @ARGV;
while ( <STDIN> ) {
print if /\Q[$pattern]/;
}
and you should run it like this
type small_access_log_Jul95_01.txt | perl FLTR_WLOG_STATUS_CODES.pl 200
|
How Do you Pass a String Variable to an Exe(Made in Python) in VBS
Question: I am trying to use the following script:
E=inputbox("What do you want me to search?")
Set sh = CreateObject("WScript.Shell")
sh.Run "search.exe "+E, 0, True
and for some reason I cannot discern, it will just quit automatically without
any error message. The Exe, made in Python has the following script:
import webbrowser as w
e=raw_input()
E=e.replace(" ","+")
print(e+" has been searched.")
w.open("http://stackoverflow.com/search?q="+E)
I assume it's crashing because `E=inputbox("What do you want me to search?")`
has multiple words, but I'm not sure. Any help would be greatly appreciated.
EDIT: When I tried to convert the python file to an exe again in hopes of
doing.....ANYTHING good, I saw the following message:
`The following modules appear to be missing: ['IronPythonConsole', 'System',
'System.Windows.Forms.Clipboard', '_scproxy', 'clr', 'modes.editingmodes',
'startup']`
Any help regarding this too would be very welcome.
Answer: [InputBox Function](https://msdn.microsoft.com/en-
us/library/3yfdhzk5\(v=vs.84\).aspx) is ok. Maybe that system can't find your
program. For debugging purposes (to see starting directory and all system
messages), change `run` line as follows:
sh.Run "cmd /C search.exe " & E & " & cd & pause", 1, True
or
sh.Run "cmd /K search.exe " & E, 1, True
Resource: [Run Method (Windows Script Host)](https://msdn.microsoft.com/en-
us/library/d5fk67ky\(v=vs.84\).aspx) reference.
|
Python version conflict. Jhbuild not reading Jhbuildrc?
Question: I was about to set up pygobject for gtk+3. This <http://python-
gtk-3-tutorial.readthedocs.org/en/latest/install.html#id2> page says I need
Jhbuild. I went ahead and installed that. But, it gives me traceback
Traceback (most recent call last):
File "/usr/bin/jhbuild", line 6, in <module>
import __builtin__
ImportError: No module named '__builtin__'
Which obviously is due to wrong version of python(my default is python3).
So, I found this page
<https://wiki.gnome.org/Projects/Jhbuild/Dependencies/ArchLinux>
Which suggests to add
os.environ['PYTHON'] = '/usr/bin/python2'
line to ~/.config/jhbuildrc which I did. When I run jhbuild again it spews the
same traceback.
I tried putting the file as ~/.jhbuildrc. Doesn't work either.
So, I'm stuck here. Any help would be appreciated.
I'm on Arch Linux, fwiw.
Answer: You probably want to set `PYTHON=/usr/bin/python2` when you `./autogen.sh
--simple-install` for jhbuild itself. The `jhbuildrc` file is only used for
things it builds.
See also: <https://wiki.archlinux.org/index.php/JHBuild>
|
Most efficient method of getting possible sum from list in python
Question: Similar to knapsack problem. If I have
list = [5,7,9,12,6]
targetValue = 15
Since 6+9 = 15, what is the most efficient way of getting
[6,9]
Does python have a built in method for such a problem?
Answer: Here's a quick solution. Note, however, that you could get duplicate solutions
if your list contains duplicate values.
from itertools import *
s = [5, 7, 9, 12, 6]
m = 15
c = chain(*[combinations(s, i) for i in range(len(s)+1)])
r = [n for n in c if sum(n) == m]
print r
Here's a more complicated version that handles duplicate values in the list:
from itertools import *
from collections import *
s = [5, 7, 9, 12, 6]
m = 15
c = Counter(s)
u = list(c)
ul = len(u)
t = [c[x] for x in u]
p = product(*[xrange(i+1) for i in t])
e = ([a for b in [[u[i]] * x[i] for i in range(ul)] for a in b] for x in p)
r = [n for n in e if sum(n) == m]
print r
|
Cython c++ example fails, why?
Question: When I tried to run the example on
<http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html>, I got the
following error on the mac terminal:
Error compiling Cython file:
distutils: language = c++
distutils: sources = Rectangle.cpp
cdef extern from "Rectangle.h" namespace "shapes":
cdef cppclass Rectangle:
rect.pyx:5:0: Expected an increase in indentation level
Traceback (most recent call last):
File "setup.py", line 8, in <module>
language="c++", # generate and compile C++ code
File "/usr/local/lib/python2.7/site-packages/Cython/Build/Dependencies.py", line 877, in cythonize
cythonize_one(*args)
File "/usr/local/lib/python2.7/site-packages/Cython/Build/Dependencies.py", line 997, in cythonize_one
raise CompileError(None, pyx_file)
Cython.Compiler.Errors.CompileError: rect.pyx
* * *
I am not sure what is wrong with my code. Could you please tell me why I am
getting the error message?
I have Cython 0.23.4 and Python 2.7.10 in my machine. I do not have any
problem running the python/c++ codes. I also installed boost and boost-python
on my computer.
Briefly, I created the following files:
1-Rectangle.h
2-Rectangle.cpp
3-setup.py
4-rect.pyx
Then, I did "python setup.py build_ext --inplace"
**Rectangle.h**
#include <stdio.h>
namespace shapes {
class Rectangle {
public:
int x0, y0, x1, y1;
Rectangle(int x0, int y0, int x1, int y1);
~Rectangle();
int getLength() const;
int getHeight() const;
int getArea() const;
void move(int dx, int dy);
};
}
**Rectangle.cpp**
#include "Rectangle.h"
using namespace shapes;
Rectangle::Rectangle(int X0, int Y0, int X1, int Y1) {
x0 = X0;
y0 = Y0;
x1 = X1;
y1 = Y1;
}
Rectangle::~Rectangle() {}
int Rectangle::getLength() const {
return (x1 - x0);
}
int Rectangle::getHeight() const {
return (y1 - y0);
}
int Rectangle::getArea() const {
return getLength() * getHeight();
}
void Rectangle::move(int dx, int dy) {
x0 += dx;
y0 += dy;
x1 += dx;
y1 += dy;
}
**setup.py**
from distutils.core import setup, Extension
from Cython.Build import cythonize
setup(ext_modules = cythonize(Extension(
"rect", # the extesion name
sources=["rect.pyx", "Rectangle.cpp"], # the Cython source and
# additional C++ source files
language="c++", # generate and compile C++ code
)))
I tried the following, too:
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize(
"rect.pyx", # our Cython source
sources=["Rectangle.cpp"], # additional source file(s)
language="c++", # generate C++ code
))
**rect.pyx**
# distutils: language = c++
# distutils: sources = Rectangle.cpp
cdef extern from "Rectangle.h" namespace "shapes":
cdef cppclass Rectangle:
Rectangle(int, int, int, int) except +
int x0, y0, x1, y1
int getLength() const
int getHeight() const
int getArea() const
void move(int, int)
cdef class PyRectangle:
cdef Rectangle *thisptr
def __cinit__(self, int x0, int y0, int x1, int y1):
self.thisptr = new Rectangle(x0, y0, x1, y1)
def __dealloc__(self):
del self.thisptr
def getLength(self):
return self.thisptr.getLength()
def getHeight(self):
return self.thisptr.getHeight()
def getArea(self):
return self.thisptr.getArea()
def move(self, dx, dy):
self.thisptr.move(dx, dy)
Answer: Thanks so much, swenzel! Now, it works!
**rect.pyx**
# distutils: language = c++
# distutils: sources = Rectangle.cpp
cdef extern from "Rectangle.h" namespace "shapes":
cdef cppclass Rectangle:
Rectangle(int, int, int, int) except +
int x0, y0, x1, y1
int getLength()
int getHeight()
int getArea()
void move(int, int)
cdef class PyRectangle:
cdef Rectangle *thisptr
def __cinit__(self, int x0, int y0, int x1, int y1):
self.thisptr = new Rectangle(x0, y0, x1, y1)
def __dealloc__(self):
del self.thisptr
def getLength(self):
return self.thisptr.getLength()
def getHeight(self):
return self.thisptr.getHeight()
def getArea(self):
return self.thisptr.getArea()
def move(self, dx, dy):
self.thisptr.move(dx, dy)
|
Either the server is overloaded or there was an error in a CGI script
Question: I am beginner in CGI and trying to pass input from HTML to python (html file
input to python file). i dont know where i am doing wrong. I am following
tutorial from
<http://www.tutorialspoint.com/python/python_cgi_programming.htm> and for
extra help i also looked at [Posting html form values to python
script](http://stackoverflow.com/questions/15965646/posting-html-form-values-
to-python-script) but failed. I am using windows 8 OS.
Here is my code: **test.py**
#!C:\Python27\python
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
first_name = form.getvalue('first_name')
last_name = form.getvalue('last_name')
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello %s %s</h2>" % (first_name, last_name)
print "</body>"
print "</html>"
**test.html**
<html>
<body>
<form name="search" action="/cgi-bintest.py" method="get">
Search: <input type="text" name="searchbox">
<input type="submit" value="Submit">
</form>
</form>
</body>
</html>
On chrome: when i write `"http://localhost/cgi-bin/test.html"` it gives:
Server error!
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there was an error in a CGI script.
If you think this is a server error, please contact the webmaster.
Error 500
localhost
Apache/2.4.16 (Win32) OpenSSL/1.0.1p PHP/5.6.12
Note: I have placed both files i.e test.py and test.html in "cgi-bin" is that
correct? as i am coming from php, javascript etc background.
Kindly help plz if am doing wrong?
Answer: You've configured your apache setup incorrectly (AND you have a typo in your
html file). Put the HTML file in your document root (see your docroot setting)
and the CGI in the `/cgi-bin/` directory.
Then in chrome, go to `http://localhost/test.html`
fyi -- the typo in your HTML file does not correctly reference your cgi-bin.
Line 3 is missing a forward slash. It should be:
<form name="search" action="/cgi-bin/test.py" method="get">
|
NodeJS 5 errors while installing npm packages
Question: Since I installed node 5.0.0, I start getting errors while installing most of
npm packages. it never happened before when I had node 4.x.
after
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "C:\Program Files\Python27\python.exe", you can set the PYTHON env variable.
gyp ERR! stack at failNoPython (c:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\configure.js:116:14)
gyp ERR! stack at c:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\configure.js:71:11
gyp ERR! stack at FSReqWrap.oncomplete (fs.js:82:15)
gyp ERR! System Windows_NT 10.0.10240
gyp ERR! command "c:\\Program Files\\nodejs\\node.exe" "c:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\Murhaf\AppData\Roaming\npm\node_modules\ember-cli\node_modules\bufferutil
gyp ERR! node -v v5.0.0
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok
npm ERR! Windows_NT 10.0.10240
basically there's 2 main errors.
* The first is asking for python.
* The second is asking for .Net SDK 2.0.
after getting python 2.7.10 installed the first error disappeared. but I
couldn't pass the MSbuild.exe error even after installing .Net SDK.
Is this happening with everyone? Do I have to install Visual Studio to get
node.js and NPM to work?
I prefer not to. Any alternative way?
I tried a clean installation, restarted my PC and installed it again, same
errors.
# Update
Now I installed both Python and VS2015, the previous errors are gone but I
have this error
c:\Users\Murhaf\Desktop\sage\node_modules\bufferutil\build\bufferutil.vcxproj(20,3): error MSB4019: The imported projec
t "C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V110\Microsoft.Cpp.Default.props" was not found. Confirm that the
path in the <Import> declaration is correct, and that the file exists on disk.
gyp ERR! build error
gyp ERR! stack Error: `msbuild` failed with exit code: 1
gyp ERR! stack at ChildProcess.onExit (c:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:270:23)
gyp ERR! stack at emitTwo (events.js:87:13)
gyp ERR! stack at ChildProcess.emit (events.js:172:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Windows_NT 10.0.10240
gyp ERR! command "c:\\Program Files\\nodejs\\node.exe" "c:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd c:\Users\Murhaf\Desktop\sage\node_modules\bufferutil
gyp ERR! node -v v5.0.0
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok
npm WARN install:bufferutil [email protected] install: `node-gyp rebuild`
npm WARN install:bufferutil Exit status 1
Answer: you need Visual Studio and Python to install modules with binary components on
windows, which probably means the module you are trying to install has binary
components, so try to install it after Visual studio and Python.
|
Class name not defined even after stating it
Question: I'm new to python GUI programming and went through this tutorial stating
Tkinter uses
I tried the following code
import Tkinter
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent=parent
self.initialize()
def initialize(self):
pass
if __name__=="__main__":
app=simpleapp_tk(None)
app.title('my application')
app.mainloop()
I expected a blank window but instead got this
Traceback (most recent call last):
File "C:/Users/vedev/Desktop/python/app1.py", line 3, in <module>
class simpleapp_tk(Tkinter.Tk):
File "C:/Users/vedev/Desktop/python/app1.py", line 12, in simpleapp_tk
app=simpleapp_tk(None)
NameError: name 'simpleapp_tk' is not defined
How do i debug it?
Answer: It's a problem with your indentation. Just don't indent
if __name__ == "__main__":
app = simpleapp_tk(None)
app.title('my application')
app.mainloop()
In your current code the if statement is executed while `simpleapp_tk` is
being defined, thus `name 'simpleapp_tk' is not defined`.
See
[Indentation](https://docs.python.org/2/reference/lexical_analysis.html#indentation)
> Leading whitespace (spaces and tabs) at the beginning of a logical line is
> used to compute the indentation level of the line, which in turn is used to
> determine the grouping of statements.
|
Python- checking for letters, numbers, and underscore character.
Question: I have to write a program that checks if a user's variable name is valid.
These are the rules I am checking for: Only letters, numbers, and the
underscore character are allowed. The first character cannot be a number.
I am not sure what I am doing wrong. Every time I run the program, it tells me
that it's a valid variable, even for invalid inputs.
Here is my program:
import string
def valid(name):
for character in (name):
if name[0].isdigit():
name==False
break
else:
if character.isalnum() and character is ('_'):
name==True
else:
name==False
return
def main():
name=input("Enter your Python variable name: ")
while name != "done":
valid(name)
if True:
print("This is a valid variable name.")
else:
print("This is not a valid variable name.")
name=input("Enter your Python variable name or 'done': ")
main()
Here is a sample output (if done right):
Enter your Python variable name: high_temp
This is a valid variable name.
Enter your Python variable name or "done": highTemp2
This is a valid variable name.
Enter your Python variable name or "done": 2_high_temp
This is not a valid variable name.
Enter your Python variable name or "done": done
Thank you in advance!
Answer: I'd write it this way:
def valid(name):
return not name[0].isdigit() and all(c.isalnum() or c == '_' for c in name)
But perhaps this would make more sense now:
def valid(name):
if name[0].isdigit():
return False
for c in name:
if not (c.isalnum() or c == '_'):
return False
return True
def main():
while True:
name = input("Enter your Python variable name or 'done': ")
if name == "done":
break
if valid(name):
print("This is a valid variable name.")
else:
print("This is not a valid variable name.")
main()
|
function returns tuple with nothing in it
Question:
#!/usr/bin/python3.5
import os, sys
from time import strftime
from os.path import join
path = '/home/william/.btrfs-snapshots/'
age = 24
todaytuple = (int(strftime("%y")),int(strftime("%m"))int(strftime("%d")))
def get_date_tuple(filename):
numberstr = ('1', '2', '3', '4', '5', '6', '7', '8', '9', '0')
filename = ''
datelist = []
global datepart
datepart = ''
for i in filename:
for n in numberstr:
if i == n:
datepart += i
if len(datepart) == 2:
y = int(datepart)
datelist.append(y)
datepart = ''
else:
pass
snapshotbirthtuple = tuple(datelist)
return snapshotbirthtuple
for fname in os.listdir(path):
snapshotbirthtupleinscope = get_date_tuple(fname)
print(snapshotbirthtupleinscope)
if snapshotbirthtupleinscope[0] <= todaytuple[0]:
`print(snapshotbirthtupleinscope)` prints `()` just empty parentheses, i'm
expecting a tuple of pairs of numbers. i'm fairly certain that the function
gives the right output, but i think i might not be passing the return variable
correctly from the function.
() #the tuple returning nothing
Traceback (most recent call last):
File "./snapshotfinal.py", line 38, in <module>
if snapshotbirthtupleinscope[0] <= todaytuple[0]:
IndexError: tuple index out of range
why is snapshotbirthtupleinscope != snapshotbirthtuple?
Answer: It looks like your could use some work. First based on your variable names,
you will want to assign something to filename for example:
filename = r"C:\MyFile.txt"
Once you have that, you will want to open the file and parse its contents:
with open( filename, "r") as fp:
data = fp.read()
# Process Data In File where datelist is set
# end with automatically closes file for you
snapshotbirthtuple = tuple(datelist)
return snapshotbirthtuple
The reason your original code returns no answer is because the line:
for i in filename:
filename is an empty string, there is nothing to iterate over, so there are
never any values assigned to i. As such your loop is skipped entirely so
datelist never gets assigned
|
Python: Functionally Merging Two Iterators Where One is Recursive
Question: The related question [How do I merge two python
iterators?](http://stackoverflow.com/questions/243865/how-do-i-merge-two-
python-iterators) works well for two independent iterators. However, I haven't
been able to find or think of the tools necessary for merging two iterators
where one is recursive and takes the other as an input. I have iterator
`stuff` that is a simple list. Then I have iterator `theta` that takes a
function `func` and yields x, func(x), func(func(x)), where one of the inputs
to `func` is an element of `stuff`. I've solved this with mutable state as
follows:
theta = some_initial_theta
for thing in stuff:
theta = update_theta(theta, thing)
return theta
A concrete example in this format:
def update_theta(theta, thing):
return thing * 2 + theta
stuff = [100, 200, 300, 400]
def my_iteration():
theta = 0
for thing in stuff:
theta = update_theta(theta, thing)
print(theta)
# This prints 2000
I'm sure there's an elegant way of doing this without the mutable state and
the for loop. A simple zip doesn't do it for me because the `theta` iterator
uses its previous element as an input to the next element.
One elegant way of expressing theta is using the `iterate` method available in
the [more_itertools package](https://pythonhosted.org/more-
itertools/api.html#more_itertools.iterate):
iterate(lambda theta: update_theta(theta, thing), some_initial_theta)
However, the problem with this is that `thing` will be fixed throughout the
iteration. It would be possible to deal with this by passing in the entire
list `stuff` and then return the remainder of it from the update_theta method:
iterate(lambda theta: update_theta(theta[0], theta[1]), (some_initial_theta, stuff))
However, I'd really rather not modify the `update_theta` method to take an
entire list it's not interested in and deal with the mechanics of returning
the tail of that list. While it's programmatically not difficult, it's poor
separation of concerns. `update_theta` shouldn't know anything about or care
about the entire list `stuff`.
Answer: As Peter Wood suggests in the comments, this is **exactly** what the built-in
function [`reduce`](https://docs.python.org/2/library/functions.html#reduce)
does:
result = reduce(update_theta, stuff, some_initial_theta)
In Python 3, `reduce` has been moved to
[`functools.reduce`](https://docs.python.org/3/library/functools.html#functools.reduce),
so you'd need to import that:
from functools import reduce
If you want an iterator of all the intermediate values, Python 3 provides
`itertools.accumulate`. There's no argument to specify an initial value, so
you'd need to put the initial value in the iterator:
from itertools import accumulate, chain
result_iterator = accumulate(chain([some_initial_theta], stuff), update_theta)
Python 2 doesn't have `itertools.accumulate`, but you could copy the
equivalent code from the Python 3 documentation. There's no easy way to
formulate it in terms of the Python 2 standard tools, which is why people
wanted it added to Python 3 in the first place.
|
Adding Project Path to Python PATH in Sublime Text
Question: I'm collaborating on a Python project using Sublime Text with another person
who uses PyCharms. PyCharms automatically adds the project path to allow easy
import of modules using relative path (relative to the root of the project).
**Question:** In Sublime Text using the Anaconda IDE (a Sublime Text package),
is there a setting we can set (ie. in a .`sublime-project` file) so that the
project path is added to the Python PATH?
Answer: From the [Anaconda configuration
docs](http://damnwidget.github.io/anaconda/anaconda_settings/#toc_5),
> your Anaconda plugin will be able to lint, complete and analyze any package
> and module that your configured python interpreter is able to see.
So, if you're importing local files like so:
from ..lib import module
for example, you don't need to add anything special to the configuration,
because as soon as you import the package Anaconda will analyze it (within
several seconds, depending on size) and be ready to offer autocomplete.
However, if you have a path like `/opt/company/modules/python` that is not
already in Python's `PYTHONPATH`, you can add it to Anaconda using the
`"extra_paths"` list:
"extra_paths":
[
"/opt/company/modules/python"
]
and any modules contained therein will be seen and processed.
|
Separate list by entries
Question: I have a Python list that I know contains the entries `1`, `2`, and `7`, e.g.,
data = [1, 7, 2, 1, 1, 1, 2, 2, 7, 1, 7, 7, 2]
I would now like to get all of the indices of each entry, i.e.,
g1 = [0, 3, 4, 5, 9]
g2 = [2, 6, 7, 12]
g7 = [1, 8, 10, 11]
The `data` array can be long, so efficiency matters. How do I achieve this?
Answer: You could use a
[`defaultdict`](https://docs.python.org/3/library/collections.html#defaultdict-
examples) in order to collect indices of elements per group:
In [1]: from collections import defaultdict
In [2]: data = [1, 7, 2, 1, 1, 1, 2, 2, 7, 1, 7, 7, 2]
In [3]: indices = defaultdict(list)
In [4]: for i, d in enumerate(data):
...: indices[d].append(i)
...:
In [5]: indices
Out[5]: defaultdict(<class 'list'>, {1: [0, 3, 4, 5, 9], 2: [2, 6, 7, 12], 7: [1, 8, 10, 11]})
|
Python Parse file with Regex
Question: I am hoping someone might be able to get me on the right track here. I need to
parse nmap output with Python. I think using regex is going to be the right
method for this, but I have never worked with regex. Here is a sample of the
text I need to parse --> <http://pastebin.com/QhG86D7D>
What I need to do with this file is:
1. I need the IP addresses.
2. I need the open ports.
The trick is I need to obviously keep the IP and ports tied together as I will
be importing them into a database that will show what ports are open for each
IP.
I am also thinking I should write the logic into a function so I can parse
different files with larger numbers of hosts.
I do know how to read the file into my script and put the data into my
database. Where I am stuck is with the regex to parse out the data I need. Can
someone help me out?
Thanks in advance!
Answer: The following approach should get you started:
import re
nmap = """Host: 127.0.0.1 () Status: Up
Host: 127.0.0.1 () Ports: 22/open/tcp//ssh///, 80/open/tcp//http///, 443/open/tcp//https/// Ignored State: closed (65532)
Host: 127.0.0.2 () Status: Up
Host: 127.0.0.2 () Ports: 21/open/tcp//ftp///, 22/open/tcp//ssh///, 25/open/tcp//smtp///, 53/filtered/tcp//domain///, 80/open/tcp//http///, 110/open/tcp//pop3///, 143/open/tcp//imap///, 443/open/tcp//https///, 465/filtered/tcp//smtps///, 993/open/tcp//imaps///, 995/open/tcp//pop3s///, 5222/filtered/tcp//xmpp-client/// Ignored State: closed (65523)
# Nmap done at Sat Nov 7 10:40:36 2015 -- 2 IP addresses (2 hosts up) scanned in 32.07 seconds"""
entries = []
for line in nmap.split('\n'):
re_host = re.match(r'Host\: ([0-9.]+?)\s+', line)
if re_host:
host = re_host.group(1)
ports = re.findall('(\d+)\/open', line)
if len(ports):
entries.append((host, ports))
for host, ports in entries:
print '{:16} {}'.format(host, ports)
This would display the following output:
127.0.0.1 ['22', '80', '443']
127.0.0.2 ['21', '22', '25', '80', '110', '143', '443', '993', '995']
You would want to replace the `split` with reading from your file.
|
Python Numpy - Matrix memory error and limits
Question: after I have been searching this topic on the web, I saw that I was not the
only one to have this problem but I can't understand if there is a way to
overcome the problem or not.
I have 5036 text files and a word list of 15985 words. For each word of the
word list found on the text file, I would like to put a 1 on my matrix. But I
get the error : _MemoryError_.
I tried also just to create the matrix and make a print (in case of a bug in
my python code).. I got the same error. Any suggestions?
matrix = np.zeros(shape=(5036,15985))
Edit: That's my code maybe there are some errors.. It should work in this way:
1. create the dictionary from a file (each word on the text file is names as "1_word1 2_word2 " etc, so splitting each line of the text file I will have in split_[0] the position in matrix, in split_[1] the word itself)
2. for each text file it saves the number of the file in order to put the right document on the matrix (each text file is named “1_1A_out.txt 2_1A_out.txt etc”)
3. finally it prints the matrix.
import os
import re
import fileinput
import numpy as np
matrix = np.zeros(shape=(6000,16000))
def dictionary_creation (filepath):
fileopen = open(filepath, "r")
dictionary = fileopen.read().split('\n')
fileopen.close()
return dictionary
def find_doc_matrix_position (filename):
regex = re.compile('(\d)_(.*)')
find_regex = regex.search(file)
if find_regex:
pos_doc = int(find_regex.group(1))-1
return pos_doc
def put_nbdoc_nbword_in_matrix (filename, dictionary, nb_file):
for line in fileinput.input([filename]):
line = line.replace("\n", "")
for w in range(0,len(dictionary)-1):
split_ = dictionary[w].split('_',1)
if line == split_[1]:
# print ("nb_file is: "+str(nb_file))
# print ("nb_word is : "+str(split_[0]))
# print ("line is: "+line+" word is: "+split_[1])
# print '####'
matrix[nb_file,split_[0]] = 1
dictionary = dictionary_creation('C:\\Users\\KP\\Desktop\\FSC_lemmes_sort.txt')
for file in os.listdir('C:\Users\KP\Desktop\FSC_Treetag\out'):
fin = open(file, 'r')
filename = file
nb_file = find_doc_matrix_position(file)
put_nbdoc_nbword_in_matrix(filename, dictionary, nb_file)
print "this is the final matrix\n"
print matrix
Answer: You are getting a memory error probably because your matrix is too big, or you
don't have enough available RAM memory in your computer.
You can try to iterate across all your text files, so you just need to create
a matrix like:
matrix = np.zeros(shape=(15985))
and then save the result to a file for every of your texts.
|
Setting up a distributed ipython/ipyparallel MPI cluster
Question: I'm struggling to understand how to setup a distributed MPI cluster with
ipython/ipyparallel. I don't have a strong MPI background.
I've followed the following instructions in the ipyparallel docs [(Using
ipcluster in mpiexec/mpirun
mode)](https://ipyparallel.readthedocs.org/en/latest/process.html#using-
ipcluster-in-mpiexec-mpirun-mode) and this works fine for distributing
computation on a single node machine. So creating an `mpi` profile,
configuring it as per the instructions above, and starting the cluster
$ ipython profile create --parallel --profile=mpi
$ vim ~/.ipython/profile_mpi/ipcluster_config.py
Then on host **A** I start a controller and 4 MPI engines:
$ ipcontroller --ip='*' --profile=mpi
$ ipcluster engines --n=4 --profile=mpi
Running the following snippet:
from ipyparallel import Client
from mpi4py import MPI
c = Client(profile='mpi')
view = c[:]
print("Client MPI.COMM_WORLD.Get_size()=%s" % MPI.COMM_WORLD.Get_size())
print("Client engine ids %s" % c.ids)
def _get_rank():
from mpi4py import MPI
return MPI.COMM_WORLD.Get_rank()
def _get_size():
from mpi4py import MPI
return MPI.COMM_WORLD.Get_size()
print("Remote COMM_WORLD ranks %s" % view.apply_sync(_get_rank))
print("Remote COMM_WORLD size %s" % view.apply_sync(_get_size))
yields
Client MPI.COMM_WORLD.Get_size()=1
Client engine ids [0, 1, 2, 3]
Remote COMM_WORLD ranks [1, 0, 2, 3]
Remote COMM_WORLD size [4, 4, 4, 4]
Then on host **B** I start 4 MPI engines. I run the snippet again which yields
Client MPI.COMM_WORLD.Get_size()=1
Client engine ids [0, 1, 2, 3, 4, 5, 6, 7]
Remote COMM_WORLD ranks [1, 0, 2, 3, 2, 3, 0, 1]
Remote COMM_WORLD size [4, 4, 4, 4, 4, 4, 4, 4]
It seems that the engines from each `ipcluster` command are grouped into
separate communicators or size 4, hence the duplicate ranks. And there's only
one MPI process for the client.
Questions:
1. ipython/ipyparallel doesn't seem to be making the MPI connections between hosts. Should ipyparallel be handling the MPI setup, or should I, as a user be creating MPI setup, as ["IPython MPI with a Machinefile"](http://stackoverflow.com/questions/30768872/ipython-mpi-with-a-machinefile) suggests? I guess my assumption was that ipyparallel would automatically handle things but this doesn't seem to be the case.
2. Is there any documentation on how to set up distributed MPI with ipyparallel? I've googled around but found nothing obvious.
3. Depending on the above, is ipython/ipyparallel only designed to handle local MPI connections, in order to avoid data transfers between the controller and engines?
**EDIT**
1. The answer to the first question seems to be that all MPI nodes have to be brought up at once. This is because:
* [Dynamic Nodes in OpenMPI](http://stackoverflow.com/questions/6913940/dynamic-nodes-in-openmpi) suggests that it is not possible to add nodes post-launch.
* [MPI - Add/remove node while program is running](http://stackoverflow.com/questions/26878521/mpi-add-remove-node-while-program-is-running) suggests that child nodes can be added through _MPI_Comm_spawn_. However, according to [MPI_Comm_spawn](https://www.open-mpi.org/doc/v1.8/man3/MPI_Comm_spawn.3.php)
> MPI_Comm_spawn tries to start maxprocs identical copies of the MPI program
> specified by command, establishing communication with them and returning an
> intercommunicator. The spawned processes are referred to as children. The
> children have their own MPI_COMM_WORLD, which is **separate from that of the
> parents**.
A quick grep through the ipyparallel code suggests that this functionality
isn't employed.
2. A partial answer to the second question is that a machinefile needs to be used so that MPI knows which remote machines it can create processes on.
The implication here is that the setup on each remote is _homogenous_ , as
provided by a cluster system like Torque/SLURM etc. Otherwise, if one is
trying to use random remotes, one is going to have to do work to ensure that
the environment mpiexec is executing on is homogenous.
3. A partial answer to the third question is no, ipyparallel can presumably work with remote MPI process, but one needs to create one ipyparall engine per MPI process.
Answer: When you start engines with MPI in IPython parallel, it ultimately boils down
to a single call of:
mpiexec [-n N] ipengine
It does no configuration of MPI. If you start multiple groups of engines on
different hosts, each group will be in its own MPI universe, which is what you
are seeing. The first thing to do is to make sure that everything's working as
you expect with a single call to `mpiexec` before you bring IPython parallel
into it.
As mentioned in [IPython parallel with a machine
file](http://stackoverflow.com/questions/30768872/ipython-mpi-with-a-
machinefile), to use multi-host MPI, you typically need a machinefile to
specify launching multiple engines on multiple hosts. For example:
# ~/mpi_hosts
machine1 slots=4
machine2 slots=4
You can use a simple test script for diagnostics:
# test_mpi.py
import os
import socket
from mpi4py import MPI
MPI = MPI.COMM_WORLD
print("{host}[{pid}]: {rank}/{size}".format(
host=socket.gethostname(),
pid=os.getpid(),
rank=MPI.rank,
size=MPI.size,
))
And run it:
$ mpiexec -machinefile ~/mpi_hosts -n 8 python test_mpi.py
machine1[32292]: 0/8
machine1[32293]: 1/8
machine1[32294]: 2/8
machine1[32295]: 3/8
machine2[32296]: 4/8
machine2[32297]: 5/8
machine2[32298]: 6/8
machine2[32299]: 7/8
Once that's working as expected, you can add
c.MPILauncher.mpi_args = ["-machinefile", "~/mpi_hosts"]
to your `~/.ipython/profile_default/ipcluster_config.py` and start your
engines with
ipcluster start -n 8
|
Creating a class-based reusable application
Question: I am trying to create a re-usable application in python 2.6.
I am developing server-side scripts for listening GPS tracking devices. The
script are using sockets.
I have a base class that defines the basic methods for handling the data sent
by device.
class MyDevice(object):
def __init__(self, db)
self.db = db # This is the class that defines methods for connecting/using database
def initialize_db(self):
...
def handle_data(self):
self.initialize_db()
...
self.process_data()
def process_data(self):
...
self.categorize_data()
def categorize_data(self):
...
self.save_data()
def save_data(self):
...
This base class serves for many devices since there are only some minor
differences between the devices. So I create a class for each _specific_
device type and make arrangements which are specific to that device.
class MyDeviceType1(Mydevice):
def __init__(self, db):
super(MyDeviceType1, self).__init__(db)
def categorize_data(self):
super(MyDeviceType1, self).categorize_data(self)
self.prepopulate_data()
... # Do other operations specific to device
def prepopulate_data(self):
"""this is specific to Type1 devices"""
...
class MyDeviceType2(Mydevice):
def __init__(self, db):
super(MyDeviceType1, self).__init__(db)
def categorize_data(self):
super(MyDeviceType1, self).categorize_data(self)
self.unpopulate_data()
... # Do other operations specific to device
def unpopulate_data(self):
"""this is specific to Type2 devices"""
...
And I have socket listeners that listens specific sockets, and call related
class (`MyDeviceType1` or `MyDeviceType2`) like:
conn, address = socket.accept()
...
thread.start_new_thread(MyDeviceType1(db_connector).handle_data, ())
That structure is all fine and useful to me. One device (_MyDevice_) may have
many subtypes (_MyDeviceType1_ , _MyDeviceType2_) which inherits the base
class.
And there are more than one type of base devices. So there is _OtherDevice_
with subtypes _OtherDeviceType1_ etc.
`MyDevice` and `OtherDevice` works quite differently, so they are the base
types and underlying code is quite different in all of them.
I also have some add-on functionalities. These functionalities are usable by
one or two subtypes of nearly all device base types.
So I want to prepare a single reusable (plug-able) class that can be inherited
by any subtype that needs those functionalities.
class MyAddOn(object):
def remove_unusable_data(self):
...
def categorize_data(self):
super ???
self.remove_unusable_data()
And here is the part that I stuck. Since this is an independent module, it
should not be inherited from `MyDevice` or `OtherDevice` etc, but not all sub
device types are using these functionalities, I can not inherit `MyDevice`
from `MyAddOn` too.
Only logical method looks like, inheriting the subtype `MyDeviceSubType1` from
both `MyDevice` and `MyAddOn`
class MyDeviceType1(Mydevice, MyAddOn):
def __init__(self, db):
super(MyDeviceType1, self).__init__(db)
def categorize_data(self):
>> super(MyDeviceType1, self).categorize_data(self) <<
self.prepopulate_data()
... # Do other operations specific to device
def prepopulate_data(self):
"""this is specific to Type1 devices"""
`super(MyDeviceType1, self).categorize_data(self)` is the problem part.
`super` is triggering the `Mydevice.categorize_data` but not
`MyAddOn.categorize_data`
Is there any way to trigger `MyAddOn` methods using `super` call or in a such
fashion that I do not need to call that class method seperately? Both
`MyDevice.categorize_data` and `MyAddOn.categorize_data` should be called.
Answer: This is called cooperative multiple inheritance in python and works just fine.
What you refer to as an "Addon" class, is generally called a "Mixin".
Just call the `super` method in your Mixin class:
class MyAddOn(object):
def remove_unusable_data(self):
...
def categorize_data(self):
super(MyAddon,self).categorize_data()
self.remove_unusable_data()
I'd like to note some things:
* The method resolution order is left to right
* You have to call super
* You should be using **kwargs for cooperative inheritance
* * *
It seems counterintuitive to call `super` here, as the parent of `MyAddon`
does not have an attribute called `categorize_data`, and you would expect this
notation to fail.
This is where the `super` function comes into play.
[Some](https://rhettinger.wordpress.com/2011/05/26/super-considered-super/)
consider this behaviour to be the best thing about python.
Unlike in _C++_ or _Java_ the `super` function does not necessarily call the
class' parent class. In fact it is impossible to know in advance which
function will be called by `super` because it will be decided at run-time
based on the [method resoltion
order](https://www.python.org/download/releases/2.3/mro/).
`super` in python should really be called `next` because it will call the next
method in the inheritance tree.
For Mixins it is especially important to call super, even if you're inheriting
from `object`.
For further information I advise to watch Raymond Hettinger's excellent talk
on [Super considered Super](https://www.youtube.com/watch?v=EiOglTERPEo) from
pycon 2015.
* * *
It's an excellent pattern to use in python. Here is a pattern I encounter
often when programming structured applications obeying the [open-closed
principle](https://en.wikipedia.org/wiki/Open/closed_principle):
I have this library class which is used in production:
class BaseClassA(object):
def __init__(self, **kwargs):
... Do something that's important for many modules
def ...
class BaseClassB(object):
def __init__(self, **kwargs):
... Do something that's important for many modules
def ...
Now you get a feature request that in a particular case both `BaseClassA` and
`BaseClassB` should implement feature X.
According to open-close you shouldn't have to touch existing code to implement
the feature, and according to DRY you shouldnt repeat the code.
The solution is to create a `FeatureMixin` and create empty child classes
which inherit from the base class and the mixin:
class FeatureMixin(object):
def __init__(self,**kwargs):
...do something specific
return super(FeatureMixin,self).__init__(**kwargs)
class ExtendedA(FeatureMixin,BaseClassA):
pass
class ExtendedB(FeatureMixin,BaseClassB):
pass
|
Python - Word Count script
Question: Down below is Python word count script that I found online, I am having
difficulty understanding how you would run this though. Would I need to create
a file and open it in Python before running this program for it to work?
#!/usr/bin/env python
import sys
if __name__ == '__main__':
data = sys.stdin.read()
chars = len(data)
words = len(data.split())
lines = len(data.split('\n'))
print ("{0} {1} {2}".format(lines, words, chars))
Thanks for any help!
Answer: `sys.stdin.read()` reads data from the console. Just run the python program
and type whatever you want. When you're done press `Ctrl + D`.
|
Python socketserver, how to get my own tcp port number
Question: I need to use socketserver to build a tcp server. According to their document,
I need to inherit the class TCPServer, and pass it a subclass of class
BaseRequestHandler where I rewrite the method handle().
Right now I need to build two server on different port, is there a way that in
handle() function, (otherwise I have to setup two almost identical handler
class, which is not I want), I can get my own port number?
Answer: Don't do it in the `handle()` method, pass the port number in (from this
<https://docs.python.org/2/library/socketserver.html#socketserver-tcpserver-
example>):
#!/usr/bin/env python
import SocketServer, argparse
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.server.server_address is a tuple (IP, port) the server is listening on
(host, port) = self.server.server_address
print 'port # is: {}'.format(port)
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print "{} wrote:".format(self.client_address[0])
print self.data
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--port', required=True, help='the TCP port to listen on')
args = parser.parse_args()
HOST, PORT = "localhost", int(args.port)
# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
In this example, you must provide the port number as an argument when you
start the program using the `-p` command line switch.
|
Cannot get url using urllib2
Question:
I'm learning Python, and the case for today is download text from a webpage.
This code works fine:
import urllib2
from bs4 import BeautifulSoup
base_url = "http://www.pracuj.pl"
url = urllib2.urlopen(base_url+"/praca/big%20data;kw").read()
soup = BeautifulSoup(url,"html.parser")
for k in soup.find_all('a'):
if "offer__list_item_link_name" in k['class']:
link = base_url+k['href']
print link
So it prints all links like this:
http://www.pracuj.pl/praca/inzynier-big-data-cloud-computing-knowledge-discovery-warszawa,oferta,4212875
http://www.pracuj.pl/praca/data-systems-administrator-krakow,oferta,4204109
http://www.pracuj.pl/praca/programista-java-sql-python-w-zespole-bigdata-krakow,oferta,4204341
http://www.pracuj.pl/praca/program-challenging-projektowanie-i-tworzenie-oprogramowania-katowice,oferta,4186995
http://www.pracuj.pl/praca/program-challenging-analizy-predyktywne-warszawa,oferta,4187512
http://www.pracuj.pl/praca/software-engineer-r-language-krakow,oferta,4239818
When add one line to assign new address, to fetch each lines content :
url2 = urllib2.urlopen(link).read()
I get an error:
Traceback (most recent call last):
File "download_page.py", line 10, in <module>
url2 = urllib2.urlopen(link).read()
NameError: name 'link' is not defined
What is wondering, it doesn't work only when in `for` loop. When I add the
same line outside the loop it works.
Can you point what I'm doing wrong?
Pawel
Answer: I assume your line `url2 = urllib2.urlopen(link).read()` is not in the same
scope as your `link` variable. The `link` variable is local to the scope of
the `for` loop, so it will work if you move your call inside of the for loop.
for k in soup.find_all('a'):
if "offer__list_item_link_name" in k['class']:
link = base_url+k['href']
url2 = urllib2.urlopen(link).read()
If you want to process the url outside of the for loop, save your links in a
list:
links = []
for k in soup.find_all('a'):
if "offer__list_item_link_name" in k['class']:
link = base_url+k['href']
links.append(link)
for link in links:
#do stuff with link
|
I can't make PypeR run anymore
Question: I can't run the wonderful [PypeR](http://www.webarray.org/softwares/PypeR/) (r
to python interface) anymore. I can import it, but as I try to run it it
crashes.
I suspect it is because I installed El Capitan OSX.
I tried to install update `pypeR` with no success.
when I run it with:
e.g.
r = R()
that's the error that I get.
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
a = R()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pyper.py", line 600, in __init__
self.__dict__['prog'] = Popen(RCMD, stdin=PIPE, stdout=PIPE, stderr=return_err and _STDOUT or childstderr, startupinfo=info)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
does anyone have a clue on how to solve this problem?
* * *
update:
if I run it from a shell instead of Idle it works. I really can't see why.
Python's version is exactly the same, built at the same time.
Answer: It looks like `PypeR` cannot find `R` to run. Most likely the `R` command is
not in the search path for `command ($PATH)` when you are using idle. One way
is to explicitly point out which `R` command to use, e.g., if the `R` command
is located in `/usr/local/bin`, you may use
r = R(RCMD="/usr/local/bin/R")
Of course, it is best if you can add `R`'s path for idle environment.
|
How can I get a startIndex for each match in my RegExp
Question: I'm struggling a bit with a RegExp result. Basically what I want to have, is a
`startIndex` which gives me the exact position for each match related to the
source string. So instead of an array with strings
var regex = /(?:\w*) from "(\w*)"/g
var result = regex.exec('import foo from "foo"');
console.log(result.slice(1)) // => ["foo"]
I would like to have an object something like this:
[{
value: 'foo',
startIndex: 17
}]
I don't think this is possible without using a special library, so my question
is:
Do you know any library which returns a more precise match information or any
other solution how I can solve it?
Note this is just an example RegExp. In the real application I will have more
than 10 completely different RegExp. Therefore, a dynamic approach is
preferred.
**Addition**
I need this for the next major version of the [GitHub
Linker](https://github.com/github-linker/chrome-extension). Currently the link
replacement is done with a jquery selector, which isn't that flexible and
sometimes wrong. A RegExp will hopefully decrease the overhead so other
developers can easily extend the [GitHub Linker](https://github.com/github-
linker/chrome-extension) with other languages like Ruby, Python .... Currently
just JavaScript is supported.
That's the reason why I'm looking for a solid and flexible solution.
– Thanks
Answer: The accepted answer [here](http://stackoverflow.com/questions/3410464/how-to-
find-all-occurrences-of-one-string-in-another-in-javascript) seems to be
close. I've adapted it somewhat below, and it appears to get near to what was
required.
var str = 'import foo from "foo" import bar from "bar"'
var regex = /(?:\w*) from "(\w*)"/g;
var output = [];
while ((result = regex.exec(str))) {
var offset = result[0].lastIndexOf(result[1]);
output.push('Value: ' + result[1] + ', startIndex: ' + (result.index+offset));
}
document.getElementById('results').innerHTML = output;
<div id="results"></div>
|
Webscraping with mechanize and beautifulsoup - cannot write output file
Question: I need to get lots of data specific to rivercruising, so I am working with
alteryx, and for scraping I want to use python from the command line. I need
to write the output file to json or to csv. The output file is empty. The
hashtags in the code are for processing the output file in alteryx, as the
scraped text already contains ",". Preferably I would love to map the output
to Json. My code is as follows:
from mechanize import Browser
from bs4 import BeautifulSoup
import lxml
mech = Browser()
url = 'http://www.cruiseshipschedule.com/viking-river-cruises/viking-aegir-schedule/'
page = mech.open(url)
html = page.read()
html.replace('charset="ISO-8859-1"','charset=utf-8')
s = BeautifulSoup(html, "lxml")
content = s.findAll('div', id="content")
link = s.findAll("a")
h1 = s.findAll("h1")
table = s.findAll("table", border="1")
for link in s.findAll("a"):
linktext = link.text
linkhref = link.get("href")
for h1 in s.findAll("h1"):
ship = h1.text
h2_1 = s.h2
h2_1.text
h2_2 = h2_1.find_next('h2')
itinerary_1 = h2_2.text
h2_3 = h2_2.find_next('h2')
itinerary_2 = h2_3.text
h2_4 = h2_3.find_next('h2')
itinerary_3 = h2_4.text
for table in content:
table0 = s.findAll("table", border='0')
for tr in s.findAll("table", border='1'):
trs1 = s.findAll("tr")
table1 = tr.text.replace('\n','|')
tds1 = s.findAll('td')
uls1 = s.findAll('ul')
lis1 = s.findAll('li')
for tr in s.findAll("table", border='0'):
trs2 = s.findAll("tr")
table2 = tr.text.replace('\n','|')
tds2 = s.findAll('td')
uls2 = s.findAll('ul')
lis2 = s.findAll('li')
all_data=ship+"#"+table1+"#"+table2+"#"+itinerary_1+"#"+itinerary_2+"#"+itinerary_3
all_data = open("Z:/txt files/all_data.txt", "w")
print all_data >> "Z:/txt files/all_data.txt"
Answer: To get output to your file, try something like instead of the last 2 lines in
your code above:
with open('all_data_txt, 'w') as f:
f.write(all_data.encode('utf8'))
|
fail to load arff file in python
Question: I am quite sure that my arff files are correct, for that I have downloaded
different files on the web and successfully opened them in Weka.
But I want to use my data in python, then I typed:
import arff
data = arff.load('file_path','rb')
It always returns an error message: _Invalid layout of the ARFF file_ , at
line 1.
Why this happened and how should I do to make it right?
Answer: If you change your code like in below, it'll work.
import arff
data = arff.load(open('file_path'))
|
sorting python list according to given texts
Question: I have the following list:
l = ['fig_1.png', 'fig_10.png', 'fig_4.png', 'fig_2.png']
Expected after sort:
result = ['fig_1.png', 'fig_2.png', 'fig_4.png', 'fig_10.png']
I tried as:
result = sorted(l)
But,
`['fig_1.png', 'fig_10.png', 'fig_2.png', 'fig_4.png']`
Answer: You cannot print `l.sort()` as it is in place sorting.
Use
l = ['fig_1.png', 'fig_3.png', 'fig_4.png', 'fig_2.png']
l.sort() #this will print none as it is in place and does not return anything
print l
Output:`['fig_1.png', 'fig_2.png', 'fig_3.png', 'fig_4.png']`
import re
l = ['fig_1.png', 'fig_10.png', 'fig_4.png', 'fig_2.png']
l.sort(key=lambda x:int(re.findall(r"(?<=_)\d+(?=\.)",x)[0]))
print l
|
Can't import namespace package "c4d" but any other name for it works
Question: I've built myself a collection of Python libraries which I collect under the
`nr` namespace. Now for a Python plugin in an application called C4D, I want
to use the `nr.c4d` module, but it can't be imported. Strangely, if I rename
it to anything else (eg. `nr.c4dlib`), it works!
+ nr.c4d\
+ nr\
* __init__.py # < pkgutil.extend_path() in here
+ c4d\
* __init__.py
* gui.py
* ...
This is the code that is in each namespace `__init__.py`
# This is a namespace package.
try:
import pkg_resources
pkg_resources.declare_namespace(__name__)
except ImportError:
import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
The `nr.__path__` list seems fine, too.
['C:\\maxon\\Cinema 4D R16 Dev\\plugins\\procedural\\python\\nr',
'C:\\maxon\\Cinema 4D R16 Dev\\plugins\\cloudui_frontend_r16\\devel\\nr.strex\\nr',
'C:\\maxon\\Cinema 4D R16 Dev\\plugins\\cloudui_frontend_r16\\devel\\nr.concurrency\\nr',
'C:\\maxon\\Cinema 4D R16 Dev\\plugins\\cloudui_frontend_r16\\devel\\nr.cli\\nr',
'C:\\maxon\\Cinema 4D R16 Dev\\plugins\\cloudui_frontend_r16\\devel\\nr.c4d\\nr']
But I get
Traceback (most recent call last):
File "'cloudui_frontend.pyp'", line 176, in <module>
ImportError: No module named c4d
It might be relevant that there is a built-in module called `c4d` in the
environment. What is the source of this error? How to fix it?
* * *
_Update_ The problem seems to come from another namespace module called
`nr.procedural`. It does `import c4d` at the top of the file. If that line is
commented out, importing `nr.c4d` works! Also, instead of commenting out the
line, I can add `from __future__ import absolute_import`.
Answer: Relative imports caused a `None`-entry to be created for `nr.c4d` in
`sys.modules` before `nr.__path__` was extended a second time. This is the
issue I opened on my `localimport` repository:
> **Scenario** : `nr.procedural` does `import c4d`. If `nr.c4d` does not
> exist, the module will be added as a None-entry to `sys.modules`. If then
> `_localimport` is used to import `nr.c4d`, the module will not be found as
> the module cache says that the module does not exist (by the None-entry).
>
> **Solution** : `_localimport` must delete None-entries for namespace
> packages on `__enter__()`.
The
[fix](https://github.com/NiklasRosenstein/localimport/commit/842d2aee2b37782441c53143d46864a597e080d4)
was relatively easy.
I will need to add `from __future__ import absolute_import` to all `nr.` sub-
packages that `import c4d` though.
|
Is regex the best approach for this?
Question: Im looking to match an item from a list and place that item into a variable.
Below is what I have put together so far, but currently Im not sure how to
create the regex I need to match just the 1 item and I am not sure if this is
the best approach. I am trying to match the item in the list with '/site-
packages' on the end.
**Test Data** (output from sites)
['/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages', '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/site-python', '/Library/Python/2.7/site-packages']
**Code**
import site
import re
sites = site.getsitepackages()
print sites
site = re.compile('*/site-packages')
for item in sites:
m = site.search(item)
if m:
print m
Answer: In this case you could also use the string `in` operator in a list
comprehension
m = [i for i in sites if r'/site-packages' in i]
Similarly you could use `endswith`
m = [i for i in sites if i.endswith(r'/site-packages')]
**Edit**
To get the smallest element (by length) once the list comprehension has
executed you can do
min(m, key=len)
|
Find amount of times that the chosen letters appear
Question: I have a script where im reading from a file and taking the first two
characters from each word in the line, what i am trying to do is find out
which two letters shows up the most often, do i have to convert my output here
into a list and do it that way ?
here is what i have
#!/usr/bin/python
import string
import re
import random
import sys
file = raw_input("Enter path to filename :")
text_file= open(file,'r')
data=text_file.readlines()
firsttwo =[]
lines = []
def first2():
for line in data:
firsttwo = line[:2]
print firsttwo
print first2()
Answer: You can use `Counter` that counts the appearances of a item in a list.
from collections import Counter
text_file= open("C:/test.txt",'r')
firsttwo = [line[:2] for line in text_file.readlines()]
print Counter(firsttwo)
If the content of `test.txt` is:
first line
second line
second line
third line
The output of the code provied would be:
Counter({'se': 2, 'fi': 1, 'th': 1})
If you want to convert this output to a list, you can do:
list(Counter(firsttwo).items())
This outputs:
[('fi', 1), ('th', 1), ('se', 2)]
**EDIT (without collections):**
text_file= open("C:/test.txt",'r')
firsttwo = [line[:2] for line in text_file.readlines()]
l_items = set(firsttwo)
l_counts = [(firsttwo.count(x), x) for x in set(firsttwo)]
l_counts.sort(reverse=True)
print l_counts[0][1]
|
How to cleanup asyncio.sleep() in a coro when te coro finishes before the sleep timeout
Question: I'am not able to cleanup the count_timer (sleep) below, when this counter is
interrupted and finished by another timer event (the stop_future).
import asyncio
import datetime
from concurrent.futures import FIRST_COMPLETED
DISPLAY_DT_TIMEOUT = 7
MAX_DISPLAY_COUNT = 3
COUNT_TIMEOUT = 4
def stop(stop_future, display_count):
print('stop', display_count, datetime.datetime.now())
stop_future.set_result('Done!')
async def display_dt1():
display_count = 0
stop_future = asyncio.Future()
stop_handle = loop.call_later(DISPLAY_DT_TIMEOUT, stop, stop_future, display_count)
# loop until
while not stop_future.done() and display_count < MAX_DISPLAY_COUNT:
print('dt1-1', display_count, datetime.datetime.now())
count_timer = asyncio.sleep(COUNT_TIMEOUT) # cleanup ??
await asyncio.wait([count_timer, stop_future], return_when=FIRST_COMPLETED)
print('dt-2', display_count, datetime.datetime.now())
display_count += 1
if not stop_future.done():
# cleanup stop future
stop_handle.cancel()
stop_future.cancel()
async def wait_before_loop_close():
await asyncio.sleep(10)
loop = asyncio.get_event_loop()
coro = display_dt1()
loop.run_until_complete(coro)
# this print shows the count_timer is still pending
print('tasks-1', asyncio.Task.all_tasks())
# wait for the count_timer to finish
loop.run_until_complete(wait_before_loop_close())
loop.close()
print('tasks-2', asyncio.Task.all_tasks())
print('finished', datetime.datetime.now())
Result:
dt1-1 0 2015-11-10 15:20:58.200107
dt-2 0 2015-11-10 15:21:02.201654
dt1-1 1 2015-11-10 15:21:02.201654
stop 0 2015-11-10 15:21:05.186800 # stop interrupt
dt-2 1 2015-11-10 15:21:05.186800 # results in stop counting
tasks-1 {<Task pending coro=<sleep() running at D:\Python\Python35-32\lib\asyncio\tasks.py:495> wait_for=<Future pending cb=[Task._wakeup()]>>}
>>> tasks-2 set()
finished 2015-11-10 15:21:15.193669
**Update-1: cancel count_timer (wrapped in a future)**
async def display_dt1():
count_timer_task = None
display_count = 0
stop_future = asyncio.Future()
stop_handle = loop.call_later(DISPLAY_DT_TIMEOUT, stop, stop_future, display_count)
while not stop_future.done() and display_count < MAX_DISPLAY_COUNT:
print('dt1-1', display_count, datetime.datetime.now())
count_timer = asyncio.sleep(COUNT_TIMEOUT) # cleanup ??
count_timer_task = asyncio.ensure_future(count_timer)
await asyncio.wait([count_timer_task, stop_future], return_when=FIRST_COMPLETED)
print('dt-2', display_count, datetime.datetime.now())
display_count += 1
if count_timer_task and not count_timer_task.cancelled():
count_timer_task.cancel()
print('check-1', datetime.datetime.now(), count_timer_task)
if not stop_future.done():
stop_handle.cancel()
stop_future.cancel()
print('check-2', datetime.datetime.now(), stop_future)
Result:
dt1-1 0 2015-11-10 16:44:29.180372
dt-2 0 2015-11-10 16:44:33.180908
dt1-1 1 2015-11-10 16:44:33.180908
stop 0 2015-11-10 16:44:36.181062
dt-2 1 2015-11-10 16:44:36.181062
check-1 2015-11-10 16:44:36.181062 <Task pending coro=<sleep() running at D:\Python\Python35-32\lib\asyncio\tasks.py:495> wait_for=<Future cancelled>>
tasks-1 set()
>>> tasks-2 set()
finished 2015-11-10 16:44:46.181965
Answer: [`asyncio.wait_for`](https://docs.python.org/3/library/asyncio-
task.html#asyncio.wait_for) implements much of what you are trying to do.
Combine it with [`asyncio.shield`](https://docs.python.org/3/library/asyncio-
task.html#asyncio.shield) to prevent your Future from being cancelled when the
timeout expires:
await asyncio.wait_for(asyncio.shield(stop_future), COUNT_TIMEOUT)
Edit: In case it wasn't clear, this goes in the `while` loop, replacing the
call to `asyncio.wait`.
**Update** by voscausa: showing the code
async def display_dt1():
display_count = 0
stop_future = asyncio.Future()
stop_handle = loop.call_later(DISPLAY_DT_TIMEOUT, stop, stop_future, display_count)
while not stop_future.done() and display_count < MAX_DISPLAY_COUNT:
print('dt-1', display_count, datetime.datetime.now())
try:
await asyncio.wait_for(asyncio.shield(stop_future), COUNT_TIMEOUT)
except asyncio.TimeoutError:
print('timeout', datetime.datetime.now())
print('dt-2', display_count, datetime.datetime.now())
display_count += 1
if not stop_future.done():
stop_handle.cancel()
stop_future.cancel()
print('check-2', datetime.datetime.now(), stop_future)
With:
DISPLAY_DT_TIMEOUT = 10
MAX_DISPLAY_COUNT = 3
COUNT_TIMEOUT = 4
Result:
dt-1 0 2015-11-10 21:43:04.549782
timeout 2015-11-10 21:43:08.551319 # count timeout
dt-2 0 2015-11-10 21:43:08.551319
dt-1 1 2015-11-10 21:43:08.551319
timeout 2015-11-10 21:43:12.552880 # count timeout
dt-2 1 2015-11-10 21:43:12.552880
dt-1 2 2015-11-10 21:43:12.552880
stop 0 2015-11-10 21:43:14.554649 # stop timeout
dt-2 2 2015-11-10 21:43:14.555650
tasks-1 set()
tasks-2 set()
finished 2015-11-10 21:43:24.558510
|
ImportError: Cython and gcc-5
Question: I want to use some C-functions in Python by using Cython. Here I noticed that
if I use GCC-5 for compiling the C-code (in order to use Cilk) `nm` lists a
lot less entrances in the resulting *.so-function:
0000000000201030 B __bss_start
0000000000201030 b completed.6973
w __cxa_finalize@@GLIBC_2.2.5
00000000000005c0 t deregister_tm_clones
0000000000000630 t __do_global_dtors_aux
0000000000200df8 t __do_global_dtors_aux_fini_array_entry
0000000000201028 d __dso_handle
0000000000200e08 d _DYNAMIC
0000000000201030 D _edata
0000000000201038 B _end
00000000000006a8 T _fini
0000000000000670 t frame_dummy
0000000000200df0 t __frame_dummy_init_array_entry
00000000000006b8 r __FRAME_END__
0000000000201000 d _GLOBAL_OFFSET_TABLE_
w __gmon_start__
0000000000201031 B __gnu_lto_slim
0000000000201032 B __gnu_lto_v1
0000000000000570 T _init
w _ITM_deregisterTMCloneTable
w _ITM_registerTMCloneTable
0000000000200e00 d __JCR_END__
0000000000200e00 d __JCR_LIST__
w _Jv_RegisterClasses
00000000000005f0 t register_tm_clones
0000000000201030 d __TMC_END__
and all my self-writen functions are missing. Furthermore I get the error
ImportError: dynamic module does not define init function (initcython_wrapper)
How can I fix that, and why is that?
The content of the `pyx`-file:
from libcpp cimport bool as bool_t
cdef extern from "complex.h":
pass
cimport numpy as np
# if you want to use the Numpy-C-API from Cython
# (not strictly necessary for this example, but good practice)
np.import_array()
# cdefine the signature of our c function
cdef extern from "GNLSE_RHS.h":
void compute(int size, double *a, double *b)
void speedcompute(int size, double *a, double *b)
void test_fft(int size, double complex *a, double complex *b)
# create the wrapper code, with numpy type annotations
def compute_func(np.ndarray[double, ndim=1, mode="c"] in_array not None,
np.ndarray[double, ndim=1, mode="c"] out_array not None):
compute(in_array.shape[0], <double*> np.PyArray_DATA(in_array),
<double*> np.PyArray_DATA(out_array))
def speedcompute_func(np.ndarray[double, ndim=1, mode="c"] in_array not None,
np.ndarray[double, ndim=1, mode="c"] out_array not None):
speedcompute(in_array.shape[0], <double*> np.PyArray_DATA(in_array),
<double*> np.PyArray_DATA(out_array))
def fft_func(np.ndarray[complex, ndim=1, mode="c"] in_array not None,
np.ndarray[complex, ndim=1, mode="c"] out_array not None):
test_fft(in_array.shape[0], <complex*> np.PyArray_DATA(in_array),
<complex*> np.PyArray_DATA(out_array))
and the command line options in the setup.py-file:
os.environ["CC"] = "gcc-5"
os.environ["CXX"] = "g++-5"
# The configuration object that hold information on all the files
# to be built.
config = Configuration('', parent_package, top_path)
config.add_extension(name='cython_wrapper',
sources=['cython_wrapper.pyx', 'GNLSE_RHS.c'],
# libraries=['m'],
include_dirs=[numpy.get_include(), "/opt/intel/compilers_and_libraries_2016.0.109/linux/mkl/include"],
#libraries=["m", "pthread", "gsl", "gslcblas"],
depends=['GNLSE_RHS.c'],
extra_compile_args=["-DMKL_ILP64 -mavx -msse4.2 -msse3 -msse2 -m64 -Ofast -flto -march=native -funroll-loops -std=gnu99"],
extra_link_args=["-Wl,--start-group /opt/intel/compilers_and_libraries_2016.0.109/linux/mkl/lib/intel64/libmkl_intel_ilp64.a /opt/intel/compilers_and_libraries_2016.0.109/linux/mkl/lib/intel64/libmkl_core.a /opt/intel/compilers_and_libraries_2016.0.109/linux/mkl/lib/intel64/libmkl_sequential.a -Wl,--end-group -lpthread -lm -ldl -lfftw3 -lfftw3_threads"])
Answer: I could solve my problem: The reason behind was not the compiler, but the
option `-flto` which generated strange code when using it with `gcc-5`.
Removing this option generated usable code.
|
why is "any()" running slower than using loops?
Question: I've been working in a project that manage big lists and pass the lists trough
a lot of tests in order to validate or not each word of the list. The funny
thing is that each time that I've used the "faster" tools or generators (like
the `itertools` module) and I make some tests, they seem to be slower.
Finally I decided to ask the question because it is possible that I be doing
something wrong. The following code will try to test the performance of the
`any()` function vs `loops`.
#!/usr/bin/python3
#
import time
from unicodedata import normalize
"""
Import a large list of tests (like 300Mb). The list contains words each one separated in a line.
"""
PATH='./tests'
start=time.time()
with open(PATH, encoding='utf-8', mode='rt') as f:
tests_list=f.read()
print('File reading done in {} seconds'.format(time.time() - start))
start=time.time()
tests_list=[line.strip() for line in normalize('NFC',tests_list).splitlines()]
print('String formalization, and list strip done in {} seconds'.format(time.time()-start))
print('{} strings'.format(len(tests_list)))
"""
test to check if "any()" is faster.
"""
print('Testing the performance of any()')
unallowed_combinations=['ab','ac','ad','ae','af','ag','ah','ai','af','ax','ae','rt','rz','bt','du','iz','ip','uy','io','ik','il','iw','ww','wp']
def combination_is_valid(string):
if any(combination in string for combination in unallowed_combinations):
return False
return True
def combination_is_valid2(string):
for combination in unallowed_combinations:
if combination in string:
return False
return True
start=time.time()
for string in tests_list:
combination_is_valid(string)
print('combination_is_valid ended in {} seconds'.format(time.time()-start))
start=time.time()
for string in tests_list:
combination_is_valid2(string)
print('combination_is_valid2 ended in {} seconds'.format(time.time()-start))
The code I posted is pretty representative of the kind of tests I do with my
program. And if we take a look to the results:
File reading done in 0.22988605499267578 seconds
String formalization, and list strip done in 6.803032875061035 seconds
38709922 strings
Testing the performance of any()
combination_is_valid ended in 80.74802565574646 seconds
combination_is_valid2 ended in 41.69514226913452 seconds
File reading done in 0.24268722534179688 seconds
String formalization, and list strip done in 6.720442771911621 seconds
38709922 strings
Testing the performance of any()
combination_is_valid ended in 79.05265760421753 seconds
combination_is_valid2 ended in 42.24800777435303 seconds
I find kinda amazing that using the function with loops its half faster than
using `any()`. What would be the explanation to this? Am I doing something
wrong?
I interpret the results as if `any()` generated a list of all the results and
check if they are True or False at the end. In the other hand the function
that uses loops, after a result is created it is tested so it can exit earlier
without generating UN-usefull tests.
What do you think?
(I used python3.4 under GNU-Linux)
Answer: Actually the
[`any()`](https://docs.python.org/3/library/functions.html?highlight=enumerate#any)
function is equal to following function :
def any(iterable):
for element in iterable:
if element:
return True
return False
which is like your second function, but since the `any()` returns a boolean
value by itself, you don't need to check for the result and then return a new
value, So the difference of performance is because of that you are actually
use a redundant return and `if` conditions,also calling the `any` inside
another function.
So the advantage of `any` here is that you don't need to wrap it with another
function because it does all the things for you.
Also as @interjay mentioned in comment it seems that the most important reason
which I missed is that you are passing a generator expression to `any()` which
doesn't provide the results at once and since it produce the result on demand
it does an extra job.
Based on [PEP 0289 -- Generator
Expressions](https://www.python.org/dev/peps/pep-0289/)
> The semantics of a generator expression are equivalent to creating an
> anonymous generator function and calling it. For example:
g = (x**2 for x in range(10))
print g.next()
is equivalent to:
def __gen(exp):
for x in exp:
yield x**2
g = __gen(iter(range(10)))
print g.next()
So as you can see each time that python want to access the next item it calls
the `iter` function and the `next` method of a generator.And finally the
result is that it's overkill to use `any()` in such cases.
|
Is there a limit on tuple size in python?
Question: I would like to assemble a training set for a neural network. I have a large
csv file with 1017209 rows and 7 columns. I need to extract certain features
from this file, and put them into a tuple. I do it the following way:
import pandas as pd
data = pd.read_csv('data.csv', index_col=False, header=0)
matrix = data.as_matrix()
training_data = ()
for x in range(1017209):
a = np.ndarray((3,1), buffer=np.array([matrix[x][0],matrix[x][1],matrix[x][5]]), dtype=float)
b = np.ndarray((1,1), buffer=np.array(matrix[x][3]), dtype=float)
training_data = training_data + ((a,b),)
It works when I loop for about 100000:
for x in range(100000)
But not with the full set:
for x in range(1017209)
I run it in spyder. It does not break, but does not seem to finish either.
When I set to 100000 it finishes in about a minute. When I set to 1017209 it
does not finish even in 45 minutes.
What might be happening? Why do I not receive an error message? Is there a
better way to create the same tuple?
Answer: I think C32 hit on the problem (although he answered it in a comment for some
reason). Since tuples are immutable, you have to create a new tuple each time
rather than appending to an existing tuple. This gives you quadratic
behaviour, and if you make your tuple 10 times longer it'll take 100 times as
long. Your code probably would have finished in about 100 minutes or so. For
example:
def build_tup(n):
td = ()
for i in range(n):
td = td + ((1,2),)
return td
def add_to_list(n):
td = []
for i in range(n):
td += (1,2),
return td
gives quadratic behaviour for `build_tup`:
>>> %timeit build_tup(100)
10000 loops, best of 3: 21.7 µs per loop
>>> %timeit build_tup(1000)
1000 loops, best of 3: 1.7 ms per loop
>>> %timeit build_tup(10000)
10 loops, best of 3: 165 ms per loop
but effectively linear behaviour for `add_to_list`:
>>> %timeit add_to_list(100)
100000 loops, best of 3: 3.64 µs per loop
>>> %timeit add_to_list(1000)
10000 loops, best of 3: 35 µs per loop
>>> %timeit add_to_list(10000)
The slowest run took 4.96 times longer than the fastest. This could mean that an intermediate result is being cached
1000 loops, best of 3: 348 µs per loop
|
When calling Python as a subprocess, can I force it to run in interactive mode?
Question: I'm on a mac using Scala, and I want to create a Python interpreter as a
subprocess that my program interacts with. I've been using Process with a
ProcessIO, but python insists on running in non-interactive mode. So it only
does anything after I close down its input and kill the process. Is there a
way to force it to run in interactive mode, so that I can keep the Python
process alive and interact with it? This sample code (which I'm pasting into a
Scala repl) shows the problem:
import scala.sys.process._
import scala.io._
import java.io._
import scala.concurrent._
val inputStream = new SyncVar[OutputStream];
val process = Process("python").run(pio)
val pio = new ProcessIO(
(stdin: OutputStream) => {
inputStream.put(stdin)
},
(stdout: InputStream) => {
while (true) {
if (stdout.available > 0){
Source.fromInputStream(stdout).getLines.foreach(println)
}
}
},
stderr => Source.fromInputStream(stderr).getLines.foreach(println),
daemonizeThreads=true
)
def write(s: String): Unit = {
inputStream.get.write((s + "\n").getBytes)
inputStream.get.flush()
}
def close(): Unit = {
inputStream.get.close
}
write("import sys")
write("try: print 'ps1:', sys.ps1")
write("except: print 'no ps1'")
close // it's only here that output prints to the screen
Answer: Invoke Python with the `-i` flag.
When no script is specified, this causes Python to run in interactive mode
whether or not stdin appears to be a terminal. When a script is specified,
this causes Python to enter interactive mode after executing the script.
|
Implementing Logistic Regression with Scipy: Why does this Scipy optimization return all zeros?
Question: I am trying to implement a one versus many logistic regression as in Andrew
Ng's [machine learning class](https://www.coursera.org/learn/machine-
learning/home/week/5), He uses an octave function called `fmincg` in his
implementation. I have tried to use several functions in the
[`scipy.optimize.minimize`](http://docs.scipy.org/doc/scipy-0.14.0/reference/optimize.html),
but I keep getting all zeros in the classifier output, no matter what I put
in.
In the last many hours, I've checkout out a ton of resources, but the most
helpful have been [this stack overflow
post](http://stackoverflow.com/questions/18801002/fminunc-alternate-in-numpy),
and [this blog post](http://aimotion.blogspot.com/2011/11/machine-learning-
with-python-logistic.html).
Is there any obvious or not so obvious place where my implementation has gone
astray?
import scipy.optimize as op
def sigmoid(z):
"""takes matrix and returns result of passing through sigmoid function"""
return 1.0 / (1.0 + np.exp(-z))
def lrCostFunction(theta, X, y, lam=0):
"""
evaluates logistic regression cost function:
theta: coefficients. (n x 1 array)
X: data matrix (m x n array)
y: ground truth matrix (m x 1 array)
lam: regularization constant
"""
m = len(y)
theta = theta.reshape((-1,1))
theta = np.nan_to_num(theta)
hypothesis = sigmoid(np.dot(X, theta))
term1 = np.dot(-y.T,np.log(hypothesis))
term2 = np.dot(1-y.T,np.log(1-hypothesis))
J = (1/m) * term1 - term2
J = J + (lam/(2*m))*np.sum(theta[1:]**2)
return J
def Gradient(theta, X, y, lam=0):
m = len(y)
theta = theta.reshape((-1,1))
hypothesis = sigmoid(np.dot(X, theta))
residuals = hypothesis - y
reg = theta
reg[0,:] = 0
reg[1:,:] = (lam/m)*theta[1:]
grad = (1.0/m)*np.dot(X.T,residuals)
grad = grad + reg
return grad.flatten()
def trainOneVersusAll(X, y, labels, lam=0):
"""
trains one vs all logistic regression.
inputs:
- X and Y should ndarrays with a row for each item in the training set
- labels is a list of labels to generate probabilities for.
- lam is a regularization constant
outputs:
- "all_theta", shape = (len(labels), n + 1)
"""
y = y.reshape((len(y), 1))
m, n = np.shape(X)
X = np.hstack((np.ones((m, 1)), X))
all_theta = np.zeros((len(labels), n + 1))
for i,c in enumerate(labels):
initial_theta = np.zeros(n+1)
result, _, _ = op.fmin_tnc(func=lrCostFunction,
fprime=Gradient,
x0=initial_theta,
args=(X, y==c, lam))
print result
all_theta[i,:] = result
return all_theta
def predictOneVsAll(all_theta, X):
pass
a = np.array([[ 5., 5., 6.],[ 6., 0., 8.],[ 1., 1., 1.], [ 6., 1., 9.]])
k = np.array([1,1,0,0])
# a = np.array([[1,0,1],[0,1,0]])
# k = np.array([0,1])
solution = np.linalg.lstsq(a,k)
print 'x', solution[0]
print 'resid', solution[1]
thetas = trainOneVersusAll(a, k, np.unique(k))
Answer: The problem lies in your `Gradient` function. In `numpy` assignment is **not
copying objects** , so your line
reg = theta
makes `reg` a reference to `theta`, so each time you compute gradient you
actually modify your current solution. It should be
reg = theta.copy()
I would also suggest starting from random weights
initial_theta = np.random.randn(n+1)
Now solution is no longer zeros (although I did not check each formula, so
there still might be mathematical error). It is also worth noting, that for
linearly separable problems, logistic regression without regularization is
ill-posed (its objective is unbounded), so I suggest testing with `lam>0`.
|
python PIL save image different size original
Question: I´m working on a project with PIL in python. Simply by opening and saving an
image makes the output image bigger (in Bytes) than the original, maintaining
the same resolution, and i don´t know why...
from PIL import Image
img = Image.open("photo.png")
img.save("photo2.png", "PNG")
[result from code above](http://i.stack.imgur.com/23Mba.png)
Does any one have any idea why this happens? i need them to be exactly the
same.
Answer: PNG is a compressed lossless format. The original image was probably saved
with different compression settings.
Looking at the
[documentation](http://pillow.readthedocs.org/en/3.0.x/handbook/image-file-
formats.html#png) you could try:
img.save("photo2.png", "PNG", optimize=True)
or
img.save("photo2.png", "PNG", compress_level=9)
By default, `compress_level=6` is used.
Note that the `optimize` option _includes_ setting the compression level to 9.
But it also tries to find optimal encoder settings.
|
Calling a function from another function for calculation (Python)
Question: My problem is I'm trying to call the function cost from the other function
area to do all the value return from the main function call. This is a
homework and I'm stuck. The problem would be easy for me if I did not have to
call the cost function from the area function and just do my calculations.
import math
def cost(price, area):
return price / area
def area(size):
radius = size / 2
area = (radius**2) * math.pi
finalprice = cost(price, area) / area
return finalprice
def main():
size = int(input("How big is your pizza?: "))
price = float(input("How much does the whole pizza cost?: "))
answer = area(size)
print("${0:0.3f}".format(answer))
main()
Answer: why would you divide the area twice? I guess you trying to compute what each
unit square area costs for the pizza?
import math
def area(diameter , price):
radius = diameter / 2
area = (radius**2) * math.pi
finalprice = price/ area
return finalprice
def main():
size = int(input("How big is your pizza?: "))
price = float(input("How much does the whole pizza cost?: "))
answer = area(size, price)
print("${0:0.3f}".format(answer))
main()
|
Remove elements from nested list - Python
Question:
data = [['A', 'B', 'C', 'D'],
['E', 'F', 'G'],
['I', 'J'],
['A', 'B', 'C', 'E', 'F']]
I would like to remove unpopular elements (appearing only once) from the
lists. So the results should look like this:
data = [['A', 'B', 'C'],
['E', 'F'],
['A', 'B', 'C', 'E', 'F']]
I was able to count the frequency of each element using the following codes:
from collections import Counter
Counter(x for sublist in data for x in sublist)
#output
Counter({'A': 2, 'C': 2, 'B': 2, 'E': 2, 'F': 2, 'D': 1, 'G': 1, 'I': 1, 'J': 1})
However, I am not sure how to use this count information to remove unpopular
elements from the list. Any help?
Answer: Generate the new list based on the frequency information.
The following code uses [nested list
comprehension](https://docs.python.org/3/tutorial/datastructures.html#nested-
list-comprehensions) to do that:
from collections import Counter
freq = Counter(x for sublist in data for x in sublist)
data = [[x for x in row if freq[x] > 1] for row in data] # Remove non-popular item
data = [row for row in data if row] # Remove empty rows
# data => [['A', 'B', 'C'], ['E', 'F'], ['A', 'B', 'C', 'E', 'F']]
|
How to integrate code into application in python
Question: This is my application code:
#GUI
from tkinter import *
#Create the window
root = Tk()
#Modify root window
root.title("Simple Bot")
root.geometry("500x400")
#Kick off the event loop
root.mainloop()
This is the bot code:
botName = input("Bot: Hello User, my name is ______ please name me: ");
botName = botName + ": ";
print(botName + "Thankyou for naming me.");
firstName = input(botName + "What is your name? ");
print(botName + "Hello, " + firstName);
favourite = input(botName + "Tell us what you like doing the most? ");
print(botName + "Nice, I like to do that as well.");
print(botName + "If you have any Questions just ask.");
How do I get the bot code to work inside of the application I have created,
and what other code do I have to add for the bot code to work in the
application.
P.S. I am new to python and trying out different things.
Answer: As a simple example to begin, try this:
from Tkinter import *
import tkMessageBox
root = Tk()
root.title("Simple Bot")
root.geometry("500x80")
def msg(ev=None):
tkMessageBox.showinfo("Message", v.get() + " Thank you for naming me.")
root.bind('<Return>', msg)
L = Label(root, text="Bot: Hello User, my name is ______ please name me: ", font=("Helvetica", 14))
v = StringVar()
E = Entry(root, textvariable=v, font=("Helvetica", 16))
L.pack()
E.pack(side=BOTTOM, fill=BOTH, expand=1)
root.mainloop()
print is replaced with `tkMessageBox` and input with `Entry`
Use `v.get()` to get text from `Entry` and v.set() to change Entry content.
I hope it will be useful.
|
np.random.dirichlet with small parameter: embed future solution in current numpy
Question: There is an ongoing discussion about the current `np.random.dirichlet`
function, as it does not function for small parameters:
In [1]: import numpy as np
In [2]: np.random.dirichlet(np.ones(3)*.00001)
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-2-464b0fe9c6c4> in <module>()
----> 1 np.random.dirichlet(np.ones(3)*.00001)
mtrand.pyx in mtrand.RandomState.dirichlet (numpy/random/mtrand/mtrand.c:25213)()
mtrand.pyx in mtrand.RandomState.dirichlet (numpy/random/mtrand/mtrand.c:25123)()
ZeroDivisionError: float division
The discussion can be read [here](https://github.com/numpy/numpy/pull/5872)
and [here](https://github.com/numpy/numpy/issues/5851) and points out, that it
is a normalization error. Currently the proposed enhancement to switch
samplers for small parameters cannot be merged into master of numpy for
several reasons.
**Question** : Can someone suggest a different way to draw dirichlets in
python or point me to a solution to use the new sampler without recompile my
numpy and/or working on an unreleased branch?
Answer: Ok, lets try the following. Here is Beta(alpha,beta) variate sampling which
should work for any small numbers.
import math
import random
def sample_beta(alpha, beta):
x = math.log( random.random() )
y = math.log( random.random() )
return x / (x + y*alpha/beta)
# some testing
import matplotlib.pyplot as plt
bins = [0.01 * i for i in range(102)]
plt.hist([sample_beta(0.00001, 0.1) for k in range(10000000)], bins)
plt.show()
Using it, you might try to sample Dirichlet via Beta variate as described in
the wikipedia
<https://en.wikipedia.org/wiki/Dirichlet_distribution#Random_number_generation>
params = [a1, a2, ..., ak]
xs = [sample_beta(params[0], sum(params[1:]))]
for j in range(1,len(params)-1):
phi = sample_beta(params[j], sum(params[j+1:]))
xs.append((1-sum(xs)) * phi)
xs.append(1-sum(xs))
If it works, it could be optimized to have all partial sums precomputed.
UPDATE
Sampling above relies on the fact, that Dirichlet could be sampled via beta
variate, and that is better (but slower) choice if case of small parameters.
In turn, beta variate could be sampled as pair of gamma variates:
beta(a, b) = gamma(1, a) / (gamma(1, a) + gamma(1, b))
So small parameters are moved from being first in gamma (if you sample
Dirichlet directly via gamma variates) to being second. And 1 (one) being
first in gamma-variates means they are just exponential distribution, sampled
as -log(U(0,1)). Please check if my math is ok, but that way sampling might
work
|
Substitution of subprocess.PIPE in Python?
Question: I am using subprocess module to interact with output of the linux commands.
below is my code.
import subprocess
import sys
file_name = 'myfile.txt'
p = subprocess.Popen("grep \"SYSTEM CONTROLLER\" "+ file_name, stdout=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
print output.strip()
p = subprocess.Popen("grep \"controller\|worker\" "+ file_name, stdout=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
lines = output.rstrip().split("\n")
print lines
My program hangs while executing second subprocess i.e.
p = subprocess.Popen("grep \"controller\|worker\""+ file_name,stdout=subprocess.PIPE, shell=True)
I got to know that the reason of process hang is buffer redirected to
subprocess.PIPE is getting filled, which blocks the process from writing
further.
I want to know if there is any way to avoid the buffer full situation so that
my program keeps on executing without any hang issue ?
Answer: The actual issue is that there is a whitespace missing between the pattern and
the filename and therefore `grep` waits for input on the standard input
(stdin).
_"buffer full"_ (`.communicate()` is not susceptible) or `p.stdout.read()` (it
fixes nothing: it loads the output into memory and unlike `.communicate()` it
fails if more than one pipe is used) are a red herring here.
Drop `shell=True` and use a list argument for the command:
#!/usr/bin/env python
from subprocess import Popen, PIPE
p = Popen(["grep", r"controller\|worker", file_name], stdout=PIPE)
output = p.communicate()[0]
if p.returncode == 0:
print('found')
elif p.returncode == 1:
print('not found')
else:
print('error')
|
alligment of objects in wxpython
Question: I added some buttons to BoxSizer. This I what I wanted: [](http://i.stack.imgur.com/HN4T5.png)
This is what I go: [](http://i.stack.imgur.com/uXkQR.png)
This is the code for the 2nd Box:
self.approveItem = wx.Button(self.panel_1, -1, "Approve Item")
self.changeQty = wx.Button(self.panel_1, -1, "Change Qty")
sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
sizer_2.Add(self.approveItem, 0, wx.ALIGN_RIGHT | wx.RIGHT, 0)
sizer_2.Add(self.changeQty, 0, wx.ALIGN_RIGHT| wx.RIGHT, 0)
self.sizer_item_staticbox = wx.StaticBox(self, -1, "")
sizer_item = wx.StaticBoxSizer(self.sizer_item_staticbox, wx.HORIZONTAL)
sizer_item.SetMinSize((600,-1))
sizer_item.Add(sizer_2, 0, wx.EXPAND, 0)
how do I fix it?
Answer: There are quite a few ways to achieve what you want, including using a
flexgridsizer, a gridsizer and just normal horizontal and vertical boxsizers,
here is a gridsizer example.
I have made it 5 columns wide, so that you can insert extra buttons on the
left hand side if you so wish.
See: <http://wxpython.org/Phoenix/docs/html/GridSizer.html>
#!/usr/bin/env python
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, ID, title):
wx.Frame.__init__(self, parent, ID, title, wx.DefaultPosition)
Buttons = []
Buttons.append(wx.Button(self,-1, "Approve Location"))
Buttons.append(wx.Button(self,-1, "Approve Item"))
Buttons.append(wx.Button(self,-1, "Change Qty"))
Buttons.append(wx.Button(self,-1, "Approve"))
sizer = wx.GridBagSizer(5,3)
sizer.Add(Buttons[0], (0, 5), (1,1), wx.EXPAND)
sizer.Add(Buttons[1], (1, 4), (1,1), wx.EXPAND)
sizer.Add(Buttons[2], (1, 5), (1,1), wx.EXPAND)
sizer.Add(Buttons[3], (2, 5), (1,1), wx.EXPAND)
self.SetSizerAndFit(sizer)
self.Centre()
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, "Gridbagsizer")
frame.Show(True)
self.SetTopWindow(frame)
return True
if __name__ == "__main__":
app = MyApp(0)
app.MainLoop()
|
Why is my code coming up with the 'expected a character buffer object' python error when i try and write a file?
Question: I have been trying to write my attributes into a file like so:
def player1():
name1=raw_input("what would you like to call the first player?")
diceroll()
print name1,"has:"
time.sleep(1)
z = strength()
time.sleep(1)
x = skill()
f = open('attributes.txt','w+')
f.write(name1)
f.write("has")
f.write(x)
f.write("strength and")
f.write(z)
f.write("skill")
However when I come to run my code it come up with:
Traceback (most recent call last):
File "H:\GCSE\Computing\Programming\shorterversion.py", line 83, in <module>
loop()
File "H:\GCSE\Computing\Programming\shorterversion.py", line 77, in loop
player1()
File "H:\GCSE\Computing\Programming\shorterversion.py", line 37, in player1
f.write(x)
TypeError: expected a character buffer object
How do I fix this? here is my entire code:
import random
import time
def loop():
global lol
def intro():
print "welcome to an attribute simulator game!"
time.sleep(1)
print "Today we will be calculating the strength and skill of virtual characters!"
def strength():
dice12 = random.randint(1,12)
dice04 = random.randint(1,4)
strfinalstats = dice12/dice04+10
print ">",strfinalstats,"strength"
def skill():
dice12 = random.randint(1,12)
dice04 = random.randint(1,4)
skfinalstats = dice12/dice04+10
print ">",skfinalstats,"skill!"
def diceroll():
print ("The dice of fate are being rolled!!")
def player1():
name1=raw_input("what would you like to call the first player?")
diceroll()
print name1,"has:"
time.sleep(1)
z = strength()
time.sleep(1)
x = skill()
f = open('attributes.txt','w+')
f.write(name1)
f.write("has")
f.write(x)
f.write("strength and")
f.write(z)
f.write("skill")
def player2():
name2=raw_input("what would you like to call the first player?")
diceroll()
print name2,"has:"
time.sleep(1)
strength()
time.sleep(1)
skill()
f = open('attributes.txt','w+')
f.write(name2)
f.write("has")
f.write(x)
f.write("strength and")
f.write(z)
f.write("skill")
def player3():
name3=raw_input("what would you like to call the first player?")
diceroll()
print name3,"has:"
time.sleep(1)
strength()
time.sleep(1)
skill()
f = open('attributes.txt','w+')
f.write(name3)
f.write("has")
f.write(x)
f.write("strength and")
f.write(z)
f.write("skill")
intro()
time.sleep(1)
player1()
player2()
player3()
lol=raw_input("would you like to run the program again? Say yes or press any letter/number key to exit!")
repeat = True
while repeat==True:
loop()
time.sleep(1)
if lol=="yes":
print "ok lets start again!"
repeat = True
else:
print "thankyou for playing!"
time.sleep(1)
print "exiting..."
exit()
Answer: You need to think about the difference between printing something and
returning it. Your function here:
def skill():
dice12 = random.randint(1,12)
dice04 = random.randint(1,4)
skfinalstats = dice12/dice04+10
print ">",skfinalstats,"skill!"
...doesn't explicitly return anything, which is the same as returning `None`.
The error you receive is exactly what you get if you attempt to write `None`
into a file:
>>> f = open('test.txt', 'wt')
>>> f.write(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected a character buffer object
>>>
Change the skill() function to something like:
def skill():
dice12 = random.randint(1,12)
dice04 = random.randint(1,4)
skfinalstats = dice12/dice04+10
return "> {} skill!".format(skfinalstats)
|
Python Matplotlib: plot text will not align left
Question: I am trying to get the values for red dots (for values of 'y2') to plot to the
left of the dots. I'm using ha='left' but to no avail. I tried the following
two aproaches:
for a,b in zip(ind, y2):
plt.text(a, b, str(b), fontsize=14, color='black', va='center', ha='left)
#OR:
for i, text in enumerate(y2):
ax.annotate(str(text), (ind[i],y2[i]), ha='left')
Here is the code in its entirety:
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
df0=pd.read_csv('sample1.csv')
import matplotlib.pyplot as plt
# You typically want your plot to be ~1.33x wider than tall.
# Common sizes: (10, 7.5) and (12, 9)
fig, ax = plt.subplots(1, 1, figsize=(12, 9))
plt.xticks(ind, x_axis, fontsize=14)
#Set y-axis font size
plt.yticks(fontsize=12)
x_axis = ['a','b','c']
y_axis = [2,8,10]
y2 = [3, 5, 9.5]
# Remove the plot frame lines. They are unnecessary here.
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
#0 = 'a', 1 = 'b, 2 = 'c'
ind = np.arange(len(x_axis))
#remove axis ticks save for left (y-axis):
plt.tick_params(
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom='off', # ticks along the bottom edge are off
top='off') # ticks along the top edge are off
plt.tick_params(
axis='y', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
right='off')
plt.title('Super Awesome Title Goes Here\n'
'and Is Continued Here', fontsize=18, va='center')
#Plot dots, cyan circles, no edges, transparency = 0.7 (1 is opaque))
# larger circles
plt.plot(ind, y_axis, 'co', markeredgecolor='none', alpha=1, markersize=40)
#plt.axis(0,10,0,3)
plt.plot(ind, y2, 'ro', markeredgecolor='none', alpha=.7, markersize=40)
#a and b are "where" to plot the label, str(b) is what to plot for the label
#add spaces to put label to the right
for a,b in zip(ind, y_axis):
plt.text(a, b, " "+str(b), fontsize=14, color='black', va='center')
for a,b in zip(ind, y2):
plt.text(a, b, str(b), fontsize=14, color='black', va='center', ha='left')
#Cell padding between categories
plt.xlim([min(ind) - 0.25, max(ind) + 0.25])
plt.ylim([0, max(y_axis) + 2])
plt.show()
Answer: The `ha` and `va` arguments specify which edges of the text bounding box will
be aligned to the specified x,y coordinates. If you want your text to appear
to the _left_ of your dot, you need to align it according to the _right hand_
edge of the bounding box:
from matplotlib import pyplot as plt
fig, ax = plt.subplots(1, 1)
ax.hold(True)
ax.plot(0, 0, '+', ms=60)
ax.text(0, 0, 'align by top right corner', ha='right', va='top', fontsize=22)
ax.text(0, 0, 'align by bottom left corner', ha='left', va='bottom', fontsize=22)
ax.set_axis_off()
plt.show()
[](http://i.stack.imgur.com/mrWHl.png)
|
Ipython notebook cannot start up (Windows 8.1)
Question: I'm using a Japanese version of windows 8.1 installed on my computer. The
problem is that my windows is in japanese as such I'm not able to use ipython
to open up .pynb files...Do anyone have similar issues? I will appreciate all
help provided. Thank you.
The error message is as shown below. [C 23:46:56.016 NotebookApp] Bad config
encountered during initialization: [C 23:46:56.016 NotebookApp] Could not
decode 'C:\Users\x83\x86\x81[\x83W\x81 [\x83\x93.jupyter' for unicode trait
'config_dir' of a NotebookApp instance.
Answer: Python 2.7 have issues with non-ascii environment variable values. Jypyter
uses environment variables to get "home" and "appdata" directories. Good thing
Jypyter have it's own environment variables to override defaults (you can
check it in `C:\Python27\Lib\site-packages\jupyter_core\paths.py` and
`C:\Python27\Lib\site-packages\jupyter_core\migrate.py`):
`JUPYTER_CONFIG_DIR`, `JUPYTER_DATA_DIR`, `JUPYTER_RUNTIME_DIR`,`IPYTHONDIR`.
You need to set them to existing non-unicode destinations. Create symlink to
C:\users\\.ipython in C:\data run `mklink /J C:\data\.ipython
"%USERPROFILE%\.ipython"` in console. I wrote script for that (`C:\data` must
exist (assuming you have Python 2.7 and it is in `C:\Python27`)). I run this
script instead of `ipython notebook`. (You also need to create symlink to
C:\users\\.ipython in `C:\data`, run `mklink /J C:\data\.ipython
"%USERPROFILE%\.ipython"` in console (cmd.exe))
import os
import subprocess
base = 'C:\\data'
jupyter_dir = os.path.join(base,'.jupyter')
if not os.path.exists(jupyter_dir):
os.mkdir(jupyter_dir)
dirs = {'JUPYTER_CONFIG_DIR' : jupyter_dir, 'JUPYTER_RUNTIME_DIR' : os.path.join(jupyter_dir,'runtime'),'JUPYTER_DATA_DIR' : os.path.join(jupyter_dir,'data')}
for k,v in dirs.iteritems():
if not os.path.exists(v):
os.mkdir(v)
os.environ[k] = v
ipython_dir = os.path.join(base,'.ipython')
os.environ['IPYTHONDIR'] = ipython_dir
subprocess.call(['C:\\Python27\\Scripts\\jupyter-notebook.exe'])
I know, butchering directory tree is not elegant solution, but it works.
|
Python Lifetimes Module Error
Question: I was trying to load the Lifetimes Module on my Linux AMI server. I installed
it just fine and everything seemed to work with no error.
However when I went to use it I got the error below. (tried to do a few things
that I thought would fix it but nothing has worked)
import lifetimes
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "lifetimes/__init__.py", line 1, in <module>
from .estimation import BetaGeoFitter, ParetoNBDFitter, GammaGammaFitter
File "lifetimes/estimation.py", line 2, in <module>
from collections import OrderedDict
ImportError: cannot import name OrderedDict
Answer: <http://linuxconfig.org/how-to-change-from-default-to-alternative-python-
version-on-debian-linux>
This is what worked for me but I did have to re-install the modules that were
on 2.6 into 2.7
|
How do I find the wss URL for a meteor-deployed app?
Question: I'm trying to connect via DDP to my meteor-deployed website at
<http://testsock.meteor.com> . [This other
answer](http://stackoverflow.com/questions/18857665/how-to-access-app-hosted-
on-meteor-com-by-ddp-websocket-protocol) has been very helpful, but I'm having
trouble finding what my URL is, which according to that answer should have the
following structure:
> ws://ddp--xxxx-{host name}.meteor.com
How do you find out?
My meteor.js file is:
if (Meteor.isClient) {
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
Meteor.methods({
test: function(){
return 5;
}
});
}
I'm using [pyddp](https://github.com/foxdog-studios/pyddp), and my python file
to ddp into mywebsite is:
import ddp
import time
import sys
client = ddp.ConcurrentDDPClient('wss://testsock.meteor.com:443/websocket')
client.start()
while True:
try:
time.sleep(1)
future = client.call('test')
result_message = future.get()
if result_message.has_result():
print 'Result:', result_message.result
if result_message.has_error():
print 'Error:', result_message.error
except KeyboardInterrupt:
sys.exit()
client.stop()
client.join()
break
Answer: When connecting to an app that is deployed to meteor.com, you can use the
following URL scheme:
> wss://myapp.meteor.com:443/websocket
`wss` denotes the encrypted WebSocket protocol URI scheme, and it is run on
port 443.
|
How to run tensor flow seq2seq demo
Question: I tensor flow installed and successfully went through the MNIST demo. Now, I
am trying to run the [seq2seq
demo](http://www.tensorflow.org/tutorials/seq2seq/index.md#), but this is not
working for me.
I cloned a version of their github repo and attempted to run some of the
listed commands from the repo root.
$ bazel run -c opt ./tensorflow/models/rnn/translate/translate.py
ERROR: Bad target pattern './tensorflow/models/rnn/translate/translate.py': package names may contain only A-Z, a-z, 0-9, '/', '-' and '_'.
INFO: Elapsed time: 0.115s
ERROR: Build failed. Not running target.
No surprise here, as it doesn't really make sense to have bazel execute a
python script.
Later in the tutorial,
$ bazel run -c opt //tensorflow/models/rnn/translate:translate \
--data_dir ./data_dir --train_dir ./checkpoints_directory \
--en_vocab_size=40000 --fr_vocab_size=40000
Unrecognized option: --data_dir
If I remove the parameters from the invocation above, it will attempt (and
fail) to build the entire tensor flow project before it executes `translate`.
This is not what I want as I have already successfully installed tensor flow
with pip.
The last thing I tried running,
$ python ./tensorflow/models/rnn/translate/translate.py
Traceback (most recent call last):
File "./tensorflow/models/rnn/translate/translate.py", line 28, in <module>
from tensorflow.models.rnn.translate import data_utils
ImportError: No module named translate
Environment info: OS X 10.11.1, Python 2.7.10 (anaconda)
Answer: There are two ways to run the script:
1) separate the script arguments with -- as part of bazel run
bazel run -c opt //tensorflow/models/rnn/translate:translate -- \
--data_dir ./data_dir --train_dir ./checkpoints_directory \
--en_vocab_size=40000 --fr_vocab_size=40000
2) build and then run from `./bazel-bin/`:
bazel build -c opt //tensorflow/models/rnn/translate:translate
./bazel-bin/tensorflow/models/rnn/translate/translate \
--data_dir ./data_dir --train_dir ./checkpoints_directory \
--en_vocab_size=40000 --fr_vocab_size=40000
|
How to use pyserial expect on a string from serial console, then send a charater
Question: I'm a new to python, hoping someone knows something about the issue I have. I
want to control a device using serial console. A command will be sent to
reboot the device, while the device is rebooting, a string is printed. I want
to catch the string and then send a character "h" which will abort the reboot.
Code looks like this
#! /bin/env python
import serial
import sys
import pexpect
from time import sleep
from serial import SerialException
ser = serial.Serial()
ser.baudrate = 9600
ser.port="/dev/ttyUSB0"
ser.stopbits=serial.STOPBITS_ONE
ser.xonxoff=0
try:
ser.open()
except:
sys.exit ("Error opening port")
print "Serial port opened"
ser.write('rebootnow\r')
temp = ser.expect('press h now to abort reboot..')
if i == 0:
print ('Gotcha, pressing h')
ser.sendline('h')
print ('Reboot aborted')
else:
print ('Ouch, got nothing')
time.sleep(1)
ser.close()
exit()
When I run the code, I get the error
AttributeError: 'Serial' object has no attribute 'expect'
at line
temp = ser.expect('press h now to abort reboot..')
Any ideas?
Answer: this thread is quite old, but I hope my answer can still be useful to you.
The expect methods are of pexpect, not of pyserial.
You should do something like:
temp = pexpect.fdpexpect.fdswpan(ser)
temp.expect("message")
basically, from temp onwards you should call methods on the temp object, not
on the serial object. This includes the sendline() call, later on.
|
Search and output with Python
Question: Help guys!!!
List of 150 text files,
One text file with query texts: (
SRR1005851
SRR1299210
SRR1021605
SRR1299782
SRR1299369
SRR1006158
...etc).
I want to search for each of this query texts from the list of 150 text files.
if for example `SRR1005851` is found in at least 120 of the files,
`SRR1005851` will be appended in an output file.
the search will iterate all search query text and through all 150 files.
Summary: I am looking for which query text is found in at least 90% of the 150
files.
Answer: I don't think I fully understand your question. Posting your code and an
example file would have been very helpful.
This code will count all entries in all files, then it will identify unique
entries per file. After that, it will count each entry's occurrence in each
file. Then, it will select only entries that appeared at least in 90% of all
files.
Also, this code could have been shorter, but for readability's sake, I created
many variables, with long, meaningful names.
Please read the comments ;)
import os
from collections import Counter
from sys import argv
# adjust your cut point
PERCENT_CUT = 0.9
# here we are going to save each file's entries, so we can sum them later
files_dict = {}
# total files seems to be the number you'll need to check against count
total_files = 0;
# raw total entries, even duplicates
total_entries = 0;
unique_entries = 0;
# first argument is script name, so have the second one be the folder to search
search_dir = argv[1]
# list everything under search dir - ideally only your input files
# CHECK HOW TO READ ONLY SPECIFIC FILE types if you have something inside the same folder
files_list = os.listdir(search_dir)
total_files = len(files_list)
print('Files READ:')
# iterate over each file found at given folder
for file_name in files_list:
print(" "+file_name)
file_object = open(search_dir+file_name, 'r')
# returns a list of entries with 'newline' stripped
file_entries = map(lambda it: it.strip("\r\n"), file_object.readlines())
# gotta count'em all
total_entries += len(file_entries)
# set doesn't allow duplicate entries
entries_set = set(file_entries)
#creates a dict from the set, set each key's value to 1.
file_entries_dict = dict.fromkeys(entries_set, 1)
# entries dict is now used differenty, each key will hold a COUNTER
files_dict[file_name] = Counter(file_entries_dict)
file_object.close();
print("\n\nALL ENTRIES COUNT: "+str(total_entries))
# now we create a dict that will hold each unique key's count so we can sum all dicts read from files
entries_dict = Counter({})
for file_dict_key, file_dict_value in files_dict.items():
print(str(file_dict_key)+" - "+str(file_dict_value))
entries_dict += file_dict_value
print("\nUNIQUE ENTRIES COUNT: "+str(len(entries_dict.keys())))
# print(entries_dict)
# 90% from your question
cut_line = total_files * PERCENT_CUT
print("\nNeeds at least "+str(int(cut_line))+" entries to be listed below")
#output dict is the final dict, where we put entries that were present in > 90% of the files.
output_dict = {}
# this is PYTHON 3 - CHECK YOUR VERSION as older versions might use iteritems() instead of items() in the line belows
for entry, count in entries_dict.items():
if count > cut_line:
output_dict[entry] = count;
print(output_dict)
|
How to query entities without no ancestors in appengine python
Question: Consider the following code snippet:
from google.appengine.ext import ndb
import pprint
class Entity(ndb.Model):
name = ndb.StringProperty()
age = ndb.IntegerProperty()
entity = Entity()
entity.name = "hello"
entity.age = 23
entity.key = ndb.Key(Entity, "p1")
entity.put()
e2 = Entity()
e2.key = ndb.Key(Entity, "p2", parent=ndb.Key(Entity, "p1"))
e2.name = "he11o2"
e2.age = 34
e2.put()
I want to query the Entity table records that doesn't have any parent
associated with it. For the above example it should yield me only p1 entity.
How can I achieve this ?
Answer: You can't. You can only query for things that exist in an index. Things with
no value unless explicity set to None (and you can't do that for parents)
can't be queried.
The only way I can suggest is have a computed property or some other property
that you set to None if no parent or the parent key or a flag. Then you can
query for all entities with parent=None. `parent` being a property of the
entity.
|
running terminal command from python 3.3
Question: i am trying to run wkhtmltopdf (a routine that convert an html to pdf:
<http://wkhtmltopdf.org>) command from python 3.3 (mac osx 10.7.5).
The routine works like a charm when directly run on terminal with the
following command:
wkhtmltopdf http:google.com /Users/ME/Desktop/google.pdf
where http:google.com is the html that will be converted to pdf in the
destination file: /Users/ME/Desktop/google.pdf
However when calling the shell from python:
import subprocess
subprocess.call(["wkhtmltopdf http:google.com /Users/ME/Desktop/google.pdf"])
**i get:**
> Traceback (most recent call last): File "<pyshell#5>", line 1, in
<module>
subprocess.call(["wkhtmltopdf http:google.com /Users/thenoze/Desktop/google.pdf"]) File
"/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/subprocess.py",
line 523, in call
with Popen(*popenargs, **kwargs) as p: File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/subprocess.py",
line 824, in __init__
restore_signals, start_new_session) File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/subprocess.py",
line 1448, in _execute_child
raise child_exception_type(errno_num, err_msg) FileNotFoundError: [Errno 2] No such file or directory: 'wkhtmltopdf http:google.com /Users/ME/Desktop/google.pdf'
\--> Any lead how to format my subprocess.call() ?
Answer: Separate the command line arguments as list items:
subprocess.call(["wkhtmltopdf", "http:google.com", "/Users/ME/Desktop/google.pdf"])
Otherwise, `wkhtmltopdf ... google.pdf` is treated as a program path, instead
of `wkhtmltopdf`.
|
AttributeError: 'list' object has no attribute 'extract'?
Question: I just want extract info from this url(<http://www.tuniu.com/g3300/whole-
nj-0/list-l1602-h0-i-j0_0/>) via xpath. As I run the following code ,it occur
AttributeError: 'list' object has no attribute 'extract'? Is my module import
wrong or dont match?
# -*- coding: utf-8 -*-
import urllib2
import sys
import lxml.html as HTML
reload(sys)
sys.setdefaultencoding("utf-8")
class spider(object):
def __init__(self):
print u'开始爬取内容'
def getSource(self, url):
html = urllib2.Request(url)
pageContent = urllib2.urlopen(html,timeout=60).read()
return pageContent
def getUrl(self, pageContent):
htmlSource = HTML.fromstring(pageContent)
urlInfo = htmlSource.xpath('//dd[@class="tqs"]/span/a/@href').extract()[0]
return urlInfo
if __name__ == "__main__":
url = "http://www.tuniu.com/g3300/whole-nj-0/list-l1602-h0-i-j0_0/"
tuniu = spider()
tuniu.getUrl(url)
following is error!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\anzhuang\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile
execfile(filename, namespace)
File "D:\anzhuang\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 71, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "D:/python/tuniu2/tuniu.py", line 34, in <module>
tuniu.getUrl(url)
File "D:/python/tuniu2/tuniu.py", line 27, in getUrl
urlInfo = htmlSource.xpath('//dd[@class="tqs"]/span/a/@href').extract()[0]
AttributeError: 'list' object has no attribute 'extract'
Answer: First, `getUrl` is called with a url. It does not fetch the content of the
url. Modify it to get page content.
And `extract` is not needed. To get the `href`, just get an item from the
returned list.
def getUrl(self, url):
pageContent = self.getSource(url) # <---
htmlSource = HTML.fromstring(pageContent)
urlInfo = htmlSource.xpath('//dd[@class="tqs"]/span/a/@href')[0]
return urlInfo
|
Getting an error while using Pandas.Series.quantile()
Question: As per the documentation on the Pandas page, we are allowed to pass a list of
values to the quantile function in Pandas series.
>>> s = Series([1, 2, 3, 4])
>>> s.quantile(.5)
2.5
>>> s.quantile([.25, .5, .75])
0.25 1.75
0.50 2.50
0.75 3.25
dtype: float64
While trying the same on my system, I get the following error.
>>> import pandas as pd
>>> s = pd.Series([1, 2, 3, 4])
>>> s
0 1
1 2
2 3
3 4
dtype: int64
>>> s.quantile(0.5)
2.5
>>> s.quantile([0.25, 0.5, 0.75])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/pandas/core/series.py", line 1324, in quantile
result = _quantile(valid_values, q * 100)
File "/usr/lib/python2.7/dist-packages/pandas/compat/scipy.py", line 66, in scoreatpercentile
idx = per / 100. * (values.shape[0] - 1)
TypeError: unsupported operand type(s) for /: 'list' and 'float'
Thanks in advance.
Answer: I think there's an issue with the version of SciPy that you are using. Just
check it out, which version of SciPy, your current version of pandas is
dependent on and accordingly update the SciPy library.
|
reading HTML(different folders) files
Question: I want to read HTML files in python. Normaly I do it like this (and it works):
import codecs
f = codecs.open("test.html",'r')
print f.read()
The Problem is that my html files are not all in the same Folder since have a
program which generates this html files and save them into folders which are
inside the folder where I have my script to read the files. Summarizing, I
have my script in a Folder and inside this Folder there are more Folders where
the generated html files are.
Does anybody know how can I proceed?
Answer:
import os
import codecs
for root, dirs, files in os.walk("./"):
for name in files:
abs_path = os.path.normpath(root + '/' + name)
file_name, file_ext = os.path.splitext(abs_path)
if file_ext == '.html':
f = codecs.open(abs_path,'r')
print f.read()
This will walk through `<script dir>/` (`./` will get translated to your
script-directory) and loop through all files in each sub-directory. It will
check if the extension is `.html` and do the work on each `.html` file.
You would perhaps define more file endings that are "accepted" (for instance
`.htm`).
|
execute a python script in C#
Question: I am trying to execute a python code in C#. Normally it should be done using
IronPython and after installing PTVS (I'm using VS 2010).
var pyEngine = Python.CreateEngine();
var pyScope = pyEngine.CreateScope();
try
{
pyEngine.ExecuteFile("plot.py", pyScope);
}
catch (Exception ex)
{
Console.WriteLine("There is a problem in your Python code: " + ex.Message);
}
The problem is that it seems that IronPython doesn't recognize some libraries
like numpy, pylab or matplotlib. I took a look a little bit and found some
people talking about Enthought Canopy or Anaconda, which i have both installed
without fixing the problem. What should I do to get the problem solved?
Answer: In order to execute a Python script which imports some libraries such as numpy
and pylab, it is possible to make this:
string arg = string.Format(@"C:\Users\ayed\Desktop\IronPythonExamples\RunExternalScript\plot.py"); // Path to the Python code
Process p = new Process();
p.StartInfo = new ProcessStartInfo(@"D:\WinPython\WinPython-64bit-2.7.5.3\python-2.7.5.amd64\python.exe", arg);
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true; // Hide the command line window
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.RedirectStandardError = false;
Process processChild = Process.Start(p.StartInfo);
|
Can't update my plot with matplotlib
Question: I am receiving data on my client and I have to plot them dynamically using
matplotlib. I want to update my plot continuously. Here is what I tried on a
simple example:
import time
import numpy as np
import matplotlib.pyplot as plt
h, = plt.plot([], [])
plt.ion()
plt.show()
for i in range(0, 100):
t = np.arange(i * 0.05, (i+1) * 0.05, 0.01)
y = np.sin(2*np.pi*t)
h.set_xdata(np.append(h.get_xdata(), t))
h.set_ydata(np.append(h.get_ydata(), t))
plt.draw()
time.sleep(0.05)
But nothing is plotting (neither in python2.7 nor 3), if I remove the
activation of interactive mode (ion()) then I get an empty plot (show() call)
but nothing is updated (the program seems to pause and don't go in the loop).
Can someone help?
Answer: Update based on the discussion below: the original code from MarAja is
working, the only problem is that the axis limits aren't being updated, so it
looks as if the plot isn't being updated.
* * *
From [this](http://stackoverflow.com/questions/4098131/how-to-update-a-plot-
in-matplotlib) example, it seems that you have to redraw the plot using
`fig.canvas.draw()`. Also note that you either have to set an appropriate
`xlim` and `ylim` to capture the entire data series, or update them every step
(like I did in this example):
import time
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
h, = plt.plot([], [])
plt.ion()
plt.show()
for i in range(0, 100):
t = np.arange(i * 0.05, (i+1) * 0.05, 0.01)
y = np.sin(2*np.pi*t)
h.set_xdata(np.append(h.get_xdata(), t))
h.set_ydata(np.append(h.get_ydata(), t))
fig.canvas.draw()
time.sleep(0.05)
plt.xlim(0,h.get_xdata().max())
plt.ylim(0,h.get_ydata().max())
|
Pandas pivot_table using a given list of indices and columns
Question: I would like some help to figure out how to pivot a pandas dataframe into a
table with a given list of indices and columns (instead of the default
behavior where the indices and columns are picked automatically by pandas).
Apologies if this is trivial. I am new to python/pandas.
Consider the following dataframe:
import pandas
import numpy as np
import datetime
data = {
'ticker' : np.array(['AAPL',
'AAPL',
'IBM',
'XOM']),
'trade_date' : np.array([datetime.datetime(2015,01,01),
datetime.datetime(2015,04,02),
datetime.datetime(2099,01,01),
datetime.datetime(2015,03,01)]),
'price' : np.array([10.0, 15.6, 20.9, 13.5])
}
x = pandas.DataFrame(data)
Upon pivot_table,
x.pivot_table(values = "price", index = "trade_date", columns = "ticker")
the result is:
ticker AAPL IBM XOM
trade_date
2015-01-01 10.0 NaN NaN
2015-03-01 NaN NaN 13.5
2015-04-02 15.6 NaN NaN
2099-01-01 NaN 20.9 NaN
However, what I want is:
ticker A AA AAPL IBM XOM
trade_date
2015-01-01 NaN NaN 10.0 NaN NaN
2015-01-02 NaN NaN NaN NaN NaN
2015-03-01 NaN NaN NaN NaN 13.5
2015-04-02 NaN NaN 15.6 NaN NaN
2099-01-01 NaN NaN NaN 20.9 NaN
There does not seem to be any provisions in pivot_table() to force a set of
indices and columns.
Is there a fast way of doing this? The data sets are fairly large, and it
would help to do this fast.
Answer: I'd reindex _after_ pivoting:
In [11]: df = x.pivot_table(values = "price", index = "trade_date", columns = "ticker")
In [12]: df
Out[12]:
ticker AAPL IBM XOM
trade_date
2015-01-01 10.0 NaN NaN
2015-03-01 NaN NaN 13.5
2015-04-02 15.6 NaN NaN
2099-01-01 NaN 20.9 NaN
In [13]: df.reindex_axis(["A", "AA", "AAPL", "IBM", "XOM"], axis=1)
Out[13]:
ticker A AA AAPL IBM XOM
trade_date
2015-01-01 NaN NaN 10.0 NaN NaN
2015-03-01 NaN NaN NaN NaN 13.5
2015-04-02 NaN NaN 15.6 NaN NaN
2099-01-01 NaN NaN NaN 20.9 NaN
|
ValueError: Wrong number of items passed 500, placement implies 1, Python and Pandas
Question: I'm importing just two columns from .xlsx file and I would like to calculate
some stuff (mean, deviation, percent change) and then I would like to plot all
this. First part doesn't give me any problems, but plotting does.
My code looks like this:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib.mlab as mlab
import math
df = pd.read_excel('KDPrviIzbor.xlsx', sheetname='List1', index_col = 0)
ch = df.pct_change(periods=252)
ma = np.mean(ch)*100
std = np.std(ch)*100
x = np.linspace(-100,100,500)
plt.plot(x,mlab.normpdf(x,ma,std))
plt.show()
But when I run my code, I get this error:
Traceback (most recent call last):
File "C:/Users/David/PythonStuff/normal_distribution.py", line 21, in <module> plt.plot(x,mlab.normpdf(x,ma,std))
File "C:\Python27\lib\site-packages\matplotlib\mlab.py", line 1579, in normpdf return 1./(np.sqrt(2*np.pi)*sigma)*np.exp(-0.5 * (1./sigma*(x - mu))**2)
File "C:\Python27\lib\site-packages\pandas\core\ops.py", line 534, in wrapper dtype=dtype)
File "C:\Python27\lib\site-packages\pandas\core\series.py", line 220, in __init__ data = SingleBlockManager(data, index, fastpath=True)
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 3383, in __init__ ndim=1, fastpath=True)
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 2101, in make_block placement=placement)
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 77, in __init__ len(self.values), len(self.mgr_locs)))
ValueError: Wrong number of items passed 500, placement implies 1`
I figured that the problem is in:
`plt.plot(x,mlab.normpdf(x,ma,std))`
but I cannot solve it. Any suggestions?
Answer: `ma` and `std` are `pandas.Series` objects in your example. The reason is,
that `np.mean` applied to a `pandas.DataFrame` returns a `pandas.Series`.
However, mlab.normpdf(x,ma,std) expects float values or numpy arrays as
inputs. You could simply convert `ma` and `std` to floats by `ma = float(ma)`.
I would not suggest to use `int(ma)` as you pointed out in your comment,
because that would cut away the decimals.
|
Representing object values __str__
Question: I have the following code:
import urllib
class Get:
def sendData(self):
self.data = urllib.urlencode({"contains":"silabeador"})
self.u = urllib.urlopen('http://tip.iatext.ulpgc.es/silabas/default.aspx', data)
request=Get()
print (request.sendData)
My output or returned value of the data sent to url is the following:
<bound method Get.sendData of <__main__.Get instance at 0x7f6089f5e050>>
How to can I get the value of the object Get and not their representation?
By the way, I am a newbie in python interested in send to some site a couple
of values and that this site receive this values in a texbox and search and
retrieve these search values. I say this, because request library
<http://docs.python-requests.org/en/latest/> it's a great alternative really?
Best Regards
**EDIT**
I have been organized my small code of this better way:
import urllib
class Get:
def __init__(self):
data = urllib.urlencode({"contains":"silabeador"})
u = urllib.urlopen('http://localhost:8000/login/', data)
print(u.read())
request=Get()
print request
And when I try get the value of my small page (on my localhost machine) I get
them, but at the end I see the object value too, the <**main**.Get instance at
0x7f052c4e00e0> value at the end ...
➜ ~ python2 pageGET.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="robots" content="NONE,NOARCHIVE">
<title>403 Forbidden</title>
<style type="text/css">
html * { padding:0; margin:0; }
body * { padding:10px 20px; }
body * * { padding:0; }
body { font:small sans-serif; background:#eee; }
body>div { border-bottom:1px solid #ddd; }
h1 { font-weight:normal; margin-bottom:.4em; }
h1 span { font-size:60%; color:#666; font-weight:normal; }
#info { background:#f6f6f6; }
#info ul { margin: 0.5em 4em; }
#info p, #summary p { padding-top:10px; }
#summary { background: #ffc; }
#explanation { background:#eee; border-bottom: 0px none; }
</style>
</head>
<body>
<div id="summary">
<h1>Prohibido <span>(403)</span></h1>
<p>CSRF verificacion fallida. Solicitud abortada</p>
<p>Estás viendo este mensaje porqué esta web requiere una cookie CSRF cuando se envían formularios. Esta cookie se necesita por razones de seguridad, para asegurar que tu navegador no ha sido comprometido por terceras partes.</p>
<p>Si has inhabilitado las cookies en tu navegador, por favor habilítalas nuevamente al menos para este sitio, o para solicitudes del mismo origen.</p>
</div>
<div id="info">
<h2>Help</h2>
<p>Reason given for failure:</p>
<pre>
CSRF cookie not set.
</pre>
<p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when
<a
href="https://docs.djangoproject.com/en/1.8/ref/csrf/">Django's
CSRF mechanism</a> has not been used correctly. For POST forms, you need to
ensure:</p>
<ul>
<li>Your browser is accepting cookies.</li>
<li>The view function passes a <code>request</code> to the template's <a
href="https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.render"><code>render</code></a>
method.</li>
<li>In the template, there is a <code>{% csrf_token
%}</code> template tag inside each POST form that
targets an internal URL.</li>
<li>If you are not using <code>CsrfViewMiddleware</code>, then you must use
<code>csrf_protect</code> on any views that use the <code>csrf_token</code>
template tag, as well as those that accept the POST data.</li>
</ul>
<p>You're seeing the help section of this page because you have <code>DEBUG =
True</code> in your Django settings file. Change that to <code>False</code>,
and only the initial error message will be displayed. </p>
<p>You can customize this page using the CSRF_FAILURE_VIEW setting.</p>
</div>
</body>
</html>
**<__main__.Get instance at 0x7f052c4e00e0>**
Answer: by using
print (request.sendData)
you are justing printing a **method definition** for `sendData()`.
In order to print the data, you just have to use `print (request.data)` since
you defined it in your class method.
**EDIT:**
Let's take a look at what you are doing in your second `__init__()` method.
def __init__(self):
1- data = urllib.urlencode({"contains":"silabeador"})
2- u = urllib.urlopen('http://localhost:8000/login/', data)
3- print(u.read())
1- You are encoding data
2- You are opening an url
3- You are reading from the url and printing it. The output is the html page.
Then next, on this line
request=Get()
You are creating an instance of Get and assigning it to `request`, Next, you
are printing `request`, which is an object reference.
So you want to print out just the pages contents? You can either:
1- Remove the `print request`
2- Change your method to:
def __init__(self):
data = urllib.urlencode({"contains":"silabeador"})
u = urllib.urlopen('http://localhost:8000/login/', data)
self.data = u.read() #assign the page content to an attribute
request = Get()
print request.data #print the data attribute.
|
How to extend Python Enum?
Question: What is best practice for extending `Enum` type in Python 3.4 and is there
even a possibility for do this?
For example:
from enum import Enum
class EventStatus(Enum):
success = 0
failure = 1
class BookingStatus(EventStatus):
duplicate = 2
unknown = 3
Traceback (most recent call last):
...
TypeError: Cannot extend enumerations
Currently there is no possible way to create a base enum class with members
and use it in other enum classes (like in the example above). Is there any
other way to implement inheritance for Python enums?
Answer: > Subclassing an enumeration is allowed only if the enumeration does not
> define any members.
>
> Allowing subclassing of enums that define members would lead to a violation
> of some important invariants of types and instances.
<https://docs.python.org/3/library/enum.html#restricted-subclassing-of-
enumerations>
So **no** , it's not directly possible.
|
Python Multiprocessing - Too Slow
Question: I have built a multiprocessing password cracker (using a wordlist) for a
specific function, it halved the time needed compared to using a single
process.
The original problem being that it would show you the cracked password and
terminate the worker, but the remaining workers would carry on until they ran
out of words to hash! not ideal.
My new step forward is to use `Manager.Event()` to terminate the remaining
workers, this works as I had hoped (after some trial and error), but the
application now takes far longer that it would take as a single process, I'm
sure this must be due to the `if` function inside `pwd_find()` but I thought I
would seek some advice.
#!/usr/bin/env python
import hashlib, os, time, math
from hashlib import md5
from multiprocessing import Pool, cpu_count, Manager
def screen_clear(): # Small function for clearing the screen on Unix or Windows
if os.name == 'nt':
return os.system('cls')
else:
return os.system('clear')
cores = cpu_count() # Var containing number of cores (Threads)
screen_clear()
print ""
print "Welcome to the Technicolor md5 cracker"
print ""
user = raw_input("Username: ")
print ""
nonce = raw_input("Nonce: ")
print ""
hash = raw_input("Hash: ")
print ""
file = raw_input("Wordlist: ")
screen_clear()
print "Cracking the password for \"" + user + "\" using "
time1 = time.time() # Begins the 'Clock' for timing
realm = "Technicolor Gateway" # These 3 variables dont appear to change
qop = "auth"
uri = "/login.lp"
HA2 = md5("GET" + ":" + uri).hexdigest() # This hash doesn't contain any changing variables so doesn't need to be recalculated
file = open(file, 'r') # Opens the wordlist file
wordlist = file.readlines() # This enables us to use len()
length = len(wordlist)
screen_clear()
print "Cracking the password for \"" + user + "\" using " + str(length) + " words"
break_points = [] # List that will have start and stopping points
for i in range(cores): # Creates start and stopping points based on length of word list
break_points.append({"start":int(math.ceil((length+0.0)/cores * i)), "stop":int(math.ceil((length+0.0)/cores * (i + 1)))})
def pwd_find(start, stop, event):
for number in range(start, stop):
if not event.is_set():
word = (wordlist[number])
pwd = word.replace("\n","") # Removes newline character
HA1 = md5(user + ":" + realm + ":" + pwd).hexdigest()
hidepw = md5(HA1 + ":" + nonce +":" + "00000001" + ":" + "xyz" + ":" + qop + ":" + HA2).hexdigest()
if hidepw == hash:
screen_clear()
time2 = time.time() # stops the 'Clock'
timetotal = math.ceil(time2 - time1) # Calculates the time taken
print "\"" + pwd + "\"" + " = " + hidepw + " (in " + str(timetotal) + " seconds)"
print ""
event.set()
p.terminate
p.join
else:
p.terminate
p.join
if __name__ == '__main__': # Added this because the multiprocessor module sometimes acts funny without it.
p = Pool(cores) # Number of processes to create.
m = Manager()
event = m.Event()
for i in break_points: # Cycles though the breakpoints list created above.
i['event'] = event
a = p.apply_async(pwd_find, kwds=i, args=tuple()) # This will start the separate processes.
p.close() # Prevents any more processes being started
p.join() # Waits for worker process to end
if event.is_set():
end = raw_input("hit enter to exit")
file.close() # Closes the wordlist file
screen_clear()
exit()
else:
screen_clear()
time2 = time.time() # Stops the 'Clock'
totaltime = math.ceil(time2 - time1) # Calculates the time taken
print "Sorry your password was not found (in " + str(totaltime) + " seconds) out of " + str(length) + " words"
print ""
end = raw_input("hit enter to exit")
file.close() # Closes the wordlist file
screen_clear()
exit()
**Edit (for @noxdafox):**
def finisher(answer):
if answer:
p.terminate()
p.join()
end = raw_input("hit enter to exit")
file.close() # Closes the wordlist file
screen_clear()
exit()
def pwd_find(start, stop):
for number in range(start, stop):
word = (wordlist[number])
pwd = word.replace("\n","") # Removes newline character
HA1 = md5(user + ":" + realm + ":" + pwd).hexdigest()
hidepw = md5(HA1 + ":" + nonce +":" + "00000001" + ":" + "xyz" + ":" + qop + ":" + HA2).hexdigest()
if hidepw == hash:
screen_clear()
time2 = time.time() # stops the 'Clock'
timetotal = math.ceil(time2 - time1) # Calculates the time taken
print "\"" + pwd + "\"" + " = " + hidepw + " (in " + str(timetotal) + " seconds)"
print ""
return True
elif hidepw != hash:
return False
if __name__ == '__main__': # Added this because the multiprocessor module sometimes acts funny without it.
p = Pool(cores) # Number of processes to create.
for i in break_points: # Cycles though the breakpoints list created above.
a = p.apply_async(pwd_find, kwds=i, args=tuple(), callback=finisher) # This will start the separate processes.
p.close() # Prevents any more processes being started
p.join() # Waits for worker process to end
Answer: I think your hunch is correct. You are checking a synchronization primitive
inside a fast loop. I would maybe only check if the event is set every so
often. You can experiment to find the sweet spot where you check it enough to
not do too much work but not so often that you slow the program down.
|
Having a function set a global variable
Question: Consider the following C++ module (explanation to follow):
#include <Python.h>
#include "nr3python.h"
Doub tau_0;
static PyObject* analysis_c_set_parameters(PyObject *self, PyObject *pyargs) {
NRpyArgs args(pyargs);
Doub tau_0 = NRpyDoub(args[0]);
return NRpyObject();
}
Doub solver(const Doub t) {
return tau_0;
}
static PyObject* analysis_c_solver(PyObject *self, PyObject *pyargs) {
NRpyArgs args(pyargs);
const Doub t = NRpyDoub(args[0]);
const Doub result = solver(t);
return NRpyObject(result);
}
static PyMethodDef AnalysisCMethods[] = {
{"set_parameters", analysis_c_set_parameters, METH_VARARGS,
"Set fixed parameters for the optimization procedure."},
{"solver", analysis_c_solver, METH_VARARGS,
"Call the optimization function for solving for the spike time."},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
initanalysis_c(void)
{
(void) Py_InitModule("analysis_c", AnalysisCMethods);
}
Note that this module is setup so that its functions can be imported into
Python scripts.
I have a global variable `tau_0`, which is declared without an initial value.
The value is set (or should be set) when the function
`analysis_c_set_parameters` is called (within Python). This value is then read
out when `analysis_c_solver` is called: `analysis_c_solver` calls `solver`,
which returns `tau_0`. `analysis_c_solver` then returns `tau_0`.
The problem I'm facing is that when I call these functions in Python script, I
get `0.0` as the value for `tau_0` even after I've attempted to set it to
something else (e.g., `0.5`).
In Python I have
import analysis_c
TAU_0 = 0.5
t = 0
analysis_c.set_parameters(TAU_0)
actual_result = analysis_c.solver(t)
In this case, `actual_result` is set to `0.0`.
What's going on here?
Answer: This line declares and initialises a new local variable:
Doub tau_0 = NRpyDoub(args[0]);
To assign to the global variable that you already declared you need to write
tau_0 = NRpyDoub(args[0]);
|
Bokeh DataTable won't update after trigger('change') without clicking on header
Question: Bokeh version: 0.10 Python: 3.4 Jupiter: 4.x
Goal: create a table that only shows data selected from a scatter plot
Problem: the DataTable only refreshes itself after being clicked on despite
the: s2.trigger('change'). In other examples on Bokeh site one plot will
update another using this technique: see
<http://bokeh.pydata.org/en/latest/docs/user_guide/interaction.html#customjs-
for-selections>
the code below should run in a Jupyter notebook if you're using the above
mentioned versions.
and, thanks for any help. Joe
from bokeh.io import output_notebook, show
from bokeh.plotting import figure
from bokeh.models import CustomJS, ColumnDataSource
from bokeh.models.widgets import DataTable, TableColumn
from bokeh.io import vform
output_notebook()
x = list(range(-20, 21))
y0 = [abs(xx) for xx in x]
# create a column data source for the plots to share
source = ColumnDataSource(data=dict(x=x, y0=y0))
s2 = ColumnDataSource(data=dict(x=[1],y0=[2]))
source.callback = CustomJS(args=dict(s2=s2), code="""
var inds = cb_obj.get('selected')['1d'].indices;
var d1 = cb_obj.get('data');
var d2 = s2.get('data');
d2['x'] = []
d2['y0'] = []
for (i = 0; i < inds.length; i++) {
d2['x'].push(d1['x'][inds[i]])
d2['y0'].push(d1['y0'][inds[i]])
}
s2.trigger('change');
""")
# create DataTable
columns = [
TableColumn(field="x", title="x"),
TableColumn(field="y0", title="y0"),
]
dt = DataTable(source=s2, columns=columns, width=300, height=300 )
# create a new plot and add a renderer
TOOLS = "box_select,lasso_select,help"
left = figure(tools=TOOLS, width=300, height=300)
left.circle('x', 'y0', source=source)
show(vform(left,dt))
Answer: only s2 change is triggered in the `CustomJS`, so it's normal that dt doesn't
change.
this will do the job, dt moved above the JS, dt is passed in the JS, and dt is
triggered :
dt = DataTable(source=s2, columns=columns, width=300, height=300 )
source.callback = CustomJS(args=dict(s2=s2, dt=dt), code="""
var inds = cb_obj.get('selected')['1d'].indices;
var d1 = cb_obj.get('data');
var d2 = s2.get('data');
d2['x'] = []
d2['y0'] = []
for (i = 0; i < inds.length; i++) {
d2['x'].push(d1['x'][inds[i]])
d2['y0'].push(d1['y0'][inds[i]])
}
console.log(dt);
s2.trigger('change');
dt.trigger('change');
""")
|
AWS Lambda Python with MySQL
Question: I'm trying to connect to mysql from my AWS Lambda script.
I did
`pip install --allow-external mysql-connector-python mysql-connector-python -t
<dir>`
to install mysql-connector-python in local directory.
I zipped the file and uploaded it to AWS Lambda where my python files are
being executed.
My scripts are executing correctly up to the point where I initialize a mysql
connection.
I have this
log('about to set connection for db')
connection = mysql.connector.connect(user=DB_USER, password=DB_PASSWORD, host=DB_HOST, database=DB_DATABASE)
query = "SELECT * FROM customers WHERE customer_email LIKE '%s' LIMIT 1"
log('set connection for DB')
'about to set connection for db' is being logged but 'set connection for DB'
is never logged and my program hits a timeout and stops executing.
What might I be doing wrong?
EDIT: This is my class that I'm calling from lambda_function.py
import mysql.connector
import logging
from mysql.connector import errorcode
class MySql( object ):
USER =None
PASSWORD=None
HOST =None
DATABASE=None
logger = logging.getLogger()
logger.setLevel( logging.INFO )
def __init__(self, user, password, host, database):
global USER, PASSWORD, HOST, DATABASE
USER = user
PASSWORD = password
HOST = host
DATABASE = database
def getId( self, customer_email ):
email_exists = False
connection = mysql.connector.connect(user=USER, password=PASSWORD, host=HOST, database=DATABASE)
query = "SELECT * FROM customers WHERE customer_email LIKE '%s' LIMIT 1"
cursor = connection.cursor()
cursor.execute( query % customer_email )
data = cursor.fetchall()
id = None
for row in data :
id = row[1]
break
cursor.close()
connection.close()
return id
def insertCustomer( self, customer_email, id ):
log('about to set connection for db')
connection = mysql.connector.connect(user=USER, password=PASSWORD, host=HOST, database=DATABASE)
log('set connection for DB')
cursor = connection.cursor()
try:
cursor.execute("INSERT INTO customers VALUES (%s,%s)",( customer_email, id ))
connection.commit()
except:
connection.rollback()
connection.close()
def log( logStr):
logger.info( logStr )
def main():
user = 'xxx'
password = 'xxx'
host = ' xxx'
database = 'xxx'
mysql = MySql( user, password, host, database )
id = mysql.getId('testing')
if id == None:
mysql.insertCustomer('blah','blahblah')
print id
if __name__ == "__main__":
main()
When I execute the MySql.py locally my code works fine.
My database gets updated but nothing happens when I run it from AWS.
Answer: Is it a MySQL instance on AWS (RDS) or on premise DB? If RDS, check the NACL
inbound rules of the vpc associated with your DB instance. Inbound rules can
allow/deny from specific IP sources
|
Python Sockets: Connection Timeout
Question: I'm trying to write two short python scripts that will connect two or more
machines to each other, one as the server and the others as clients. It worked
perfectly when testing the client and the server script on the same computer,
but when I tried it from another computer the client kept timing out; it
couldn't connect to the server. Here's my server code:
import socket
server = socket.socket()
host = "computername"
port = 12345
server.bind((host, port))
server.listen(5)
client, addr = server.accept()
Client code:
import socket
server = socket.socket()
host = "computername"
port = 12345
server.connect((host, port))
Any clue as to why the machines can't connect?
Answer: I think, you are changing host variable properly when running both client and
server scripts in different machines. Try by changing that properly/or using
IP address of server machine.
|
Generating random X,Y coordinates in a grid
Question: I'm fairly new to Python and this site. I'm hoping someone can help me with
this and clarify a few things. I'm stuck at this part in my battleship
program. I have a 10x10 grid and I want to randomize the locations for each of
the 3 ships within my grid . I also want to display the location when I want
them revealed. I've been trying to imitate this using other methods but to no
avail.
My current grid looks like this:
print(" 0 ","1 ","2 ","3 ","4 ","5 ","6 ","7 ","8 ","9","10")
symbol = " O "
row = 0
for i in range(0,11):
print(symbol*11 + " " + str(row))
row += 1
For example, I want the grid to look like this when I choose to reveal the
location of ships 1, 2 and 3:
O O O X O O O O O O
O O O X O O O O X O
O O O X O O O O X O
O O O X O O O O X O
O O O O O O O O X O
O O O O O O O O O O
O O X X X X O O O O
O O O O O O O O O O
O O O O O O O O O O
O O O O O O O O O O
Answer: You're doing too much manual work. You can store the entire grid as an array,
and modify the grid, and then print the grid. Also, you don't need to specify
0 in range. Anyway, check this out.
grid = [['O' for i in range(10)] for j in range(10)] # use generators to create list
def print_grid():
print(" " + " ".join(str(i) for i in range(10))) # " ".join() puts the " " between each string in the list
for y in range(10):
print(str(y) + " " + " ".join(grid[y]))
print_grid()
# OUTPUT:
# 0 1 2 3 4 5 6 7 8 9
# 0 O O O O O O O O O O
# 1 O O O O O O O O O O
# 2 O O O O O O O O O O
# 3 O O O O O O O O O O
# 4 O O O O O O O O O O
# 5 O O O O O O O O O O
# 6 O O O O O O O O O O
# 7 O O O O O O O O O O
# 8 O O O O O O O O O O
# 9 O O O O O O O O O O
grid[0][3] = 'X'
grid[1][3] = 'X'
grid[2][3] = 'X'
grid[3][3] = 'X'
print_grid()
# OUTPUT:
# 0 1 2 3 4 5 6 7 8 9
# 0 O O O X O O O O O O
# 1 O O O X O O O O O O
# 2 O O O X O O O O O O
# 3 O O O X O O O O O O
# 4 O O O O O O O O O O
# 5 O O O O O O O O O O
# 6 O O O O O O O O O O
# 7 O O O O O O O O O O
# 8 O O O O O O O O O O
# 9 O O O O O O O O O O
Hopefully that's most of what you need!
EDIT: Did not see the randomize aspect, my apologies!
Use random.randint, for example (but move the import to the top of your file):
import random
x = random.randint(1, 8)
y = random.randint(1, 8)
if random.randint(0, 1): # flip coin to determine orientation
grid[y-1][x] = 'X'
grid[y][x] = 'X'
grid[y+1][x] = 'X'
else:
grid[y][x-1] = 'X'
grid[y][x] = 'X'
grid[y][x+1] = 'X'
To check for collision, you might rather than setting those 3 as X off the
bat, verify that they are all O first, and if not, reroll the position and
orientation.
|
Translate pandas column with TextBlob
Question: I'm trying to read a csv and translate one column that is written in French to
English with the TextBlob package in Python (2.7.10 Mac OS X Yosemite).
However, Python throws the following error message at me:
AttributeError: 'Series' object has no attribute 'translate'
My Python code:
import pandas as pd
import numpy as np
from textblob import TextBlob
df = pd.read_csv('france_content.csv')
df2 = df[['HEADLINE', 'AUTHOR', 'CONTENT']]
TextBlob = df2['CONTENT'].str.strip()
TextBlob.translate(to="es")
On second thought, I actually think I don't need numpy here. But how can I
make pandas to read the content field and have textblob translate this to
English. Preferably placing this in a column named 'English'
EDIT: Changed to:
import pandas as pd
import numpy as np
from textblob import TextBlob
df = pd.read_csv('france_content.csv')
df['English'] = df['CONTENT'].str.encode('ascii', 'ignore').apply(lambda x: TextBlob(x.strip()).translate(to='en'))
Data is very basic with in column 1 Author name and in column 2 ('CONTENT')
the French text.
I still have the following error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 9: ordinal not in range(128)
Answer: import pandas as pd from textblob import TextBlob df =
pd.read_csv('d:\lan.csv') # path to csv file
# add english column in dataframe with converted words
df['english'] = df['structure'].str.encode('ascii', 'ignore').apply(lambda
x:TextBlob(x.strip()).translate(to='en')) df.to_csv("cool.csv")# your
documents folder
this works as required ,thanks
|
Calculate mean on values in python collections.Counter
Question: I'm profiling some numeric time measurements that cluster extremely closely. I
would like to obtain mean, standard deviation, etc. Some inputs are large, so
I thought I could avoid creating lists of millions of numbers and instead use
Python collections.Counter objects as a compact representation.
Example: one of my small inputs yields a `collection.Counter` like `[(48,
4082), (49, 1146)]` which means 4,082 occurrences of the value 48 and 1,146
occurrences of the value 49. For this data set I manually calculate the mean
to be something like 48.2192042846.
Of course if I had a simple list of 4,082 + 1,146 = 5,228 integers I would
just feed it to numpy.mean().
My question: how can I calculate descriptive statistics from the values in a
`collections.Counter` object just as if I had a list of numbers? Do I have to
create the full list or is there a shortcut?
Answer: `collections.Counter()` is a subclass of `dict`. Just use `Counter().values()`
to get a list of the counts:
counts = Counter(some_iterable_to_be_counted)
mean = numpy.mean(counts.values())
Note that I did _not_ call `Counter.most_common()` here, which would produce
the list of `(key, count)` tuples you posted in your question.
If you must use the output of `Counter.most_common()` you can filter out just
the counts with a list comprehension:
mean = numpy.mean([count for key, count in most_common_list])
If you are using Python 3 (where `dict.values()` returns a dictionary view),
you could either pass in `list(counts.values())`, or use the standard library
[`staticstics.mean()`
function](https://docs.python.org/3/library/statistics.html#statistics.mean),
which takes an iterable (including `dict.values()` dictionary view).
If you meant to calculate the mean _key value_ as weighted by their counts,
you'd do your own calculations directly from the counter values. In Python 2
that'd be:
from __future__ import division
mean = sum(key * count for key, count in counter.iteritems()) / sum(counter.itervalues())
The `from __future__` import should be at the top of your module and ensures
that you won't run into overflow issues with large floating point numbers. In
Python 3 that'd be simplified to:
mean = sum(key * count for key, count in counter.items()) / sum(counter.values())
The median could be calculated with bisection; sort the `(key, count)` pairs
by key, sum the counts, and bisect the half-way point into a accumulated sum
of the counts. The index for the insertion point points to the median key in
the sorted keys list.
|
Python application trying to insert into oracle
Question: I have a simple tkinter application I built to put in the amount of hours I
worked. for some reason I keep getting this error "DatabaseError: ORA-01036:
illegal variable name/number" any help will be greatly appreciated!
here is my SnowTime.py
import os
import sys
import Tkinter
import tkMessageBox
import cx_Oracle
from datetime import date, datetime, timedelta
import time
def insertBcl():
connection = cx_Oracle.connect('user', 'password', cx_Oracle.makedsn('xxx.xxx.xxx.xxx', 'port', 'sid'))
cursor = connection.cursor()
cursor.execute("SELECT MAX(TRANSACTION_ID) FROM LABOR")
for result in cursor:
r = reduce(lambda rst, d: rst * 10 + d, (result))
f = r + 1
#cursor.close()
#connection.close()
hours = e1.get()
today = datetime.now().date().strftime("%Y-%m-%d")
SNOWJ = "SNOWJ"
I = "I"
OH = "OH"
W = "W"
null = "null"
zero = 0
N = "N"
SNOW = "SNOW"
add_time =("INSERT INTO TEST "
"(EMPLOYEE_ID, TRANSACTION_DATE, TRANSACTION_ID, TYPE, INDIRECT_ID, HOURS_WORKED, GOOD_QTY, BAD_QTY, SHIFT_ID, SETUP_COMPLETED, PASS_FAIL, CREATE_DATE, REASON, USER_ID, OPEN_OP)"
"VALUES (%(EMPLOYEE_ID)s, %(TRANSACTION_DATE)s, %(TRANSACTION_ID)s, %(TYPE)s, %(INDIRECT_ID)s, %(HOURS_WORKED)s, %(GOOD_QTY)s, %(BAD_QTY)s, %(SHIFT_ID)s, %(SETUP_COMPLETED)s, %(PASS_FAIL)s, %(CREATE_DATE)s, %(REASON)s, %(USER_ID)s, %(OPEN_OP)s)")
data_time = { 'EMPLOYEE_ID': SNOWJ,
'TRANSACTION_DATE': today,
'TRANSACTION_ID': f,
'TYPE': I,
'INDIRECT_ID': OH,
'HOURS_WORKED': hours,
'GOOD_QTY': zero,
'BAD_QTY': zero,
'SHIFT_ID': null,
'SETUP_COMPLETED': N,
'PASS_FAIL': N,
'CREATE_DATE': today,
'REASON': null,
'USER_ID': SNOW,
'OPEN_OP': null,
}
print add_time
print data_time
cursor.execute(add_time, data_time)
connection.commit()
cursor.close()
connection.close()
here is what add_time looks like when printed
INSERT INTO TEST (EMPLOYEE_ID, TRANSACTION_DATE, TRANSACTION_ID, TYPE, INDIRECT_ID, HOURS_WORKED, GOOD_QTY, BAD_QTY, SHIFT_ID, SETUP_COMPLETED, PASS_FAIL, CREATE_DATE, REASON, USER_ID, OPEN_OP)VALUES (%(EMPLOYEE_ID)s, %(TRANSACTION_DATE)s, %(TRANSACTION_ID)s, %(TYPE)s, %(INDIRECT_ID)s, %(HOURS_WORKED)s, %(GOOD_QTY)s, %(BAD_QTY)s, %(SHIFT_ID)s, %(SETUP_COMPLETED)s, %(PASS_FAIL)s, %(CREATE_DATE)s, %(REASON)s, %(USER_ID)s, %(OPEN_OP)s)
here is what data_time looks like print
{'CREATE_DATE': '2015-11-13', 'OPEN_OP': 'null', 'HOURS_WORKED': '4', 'REASON': 'null', 'TRANSACTION_DATE': '2015-11-13', 'INDIRECT_ID': 'OH', 'TRANSACTION_ID': 12816058, 'PASS_FAIL': 'N', 'USER_ID': 'SNOW', 'EMPLOYEE_ID': 'SNOWJ', 'SHIFT_ID': 'null', 'SETUP_COMPLETED': 'N', 'GOOD_QTY': 0, 'BAD_QTY': 0, 'TYPE': 'I'}
here is my table structure
column_name data_type
EMPLOYEE_ID VARCHAR2(15 BYTE)
TRANSACTION_DATE DATE
TRANSACTION_ID NUMBER(10,0)
TYPE CHAR(1 BYTE)
INDIRECT_ID VARCHAR2(15 BYTE)
HOURS_WORKED NUMBER(7,2)
GOOD_QTY NUMBER(14,4)
BAD_QTY NUMBER(14,4)
SHIFT_ID VARCHAR2(15 BYTE)
SETUP_COMPLETED CHAR(1 BYTE)
PASS_FAIL CHAR(1 BYTE)
CREATE_DATE DATE
REASON VARCHAR2(50 BYTE)
USER_ID VARCHAR2(15 BYTE)
OPEN_OP CHAR(1 BYTE)
Answer: In Oracle odd things can happen when you use reserved key words.
I see you have a table column called TYPE which is a key word. You could try
the double quote trick like this
INSERT INTO TEST (EMPLOYEE_ID, TRANSACTION_DATE, TRANSACTION_ID, "TYPE", ...
%(TYPE)s, %(INDIRECT_ID)s, %(HOURS_WORKED)s, %(GOOD_QTY)s, %(BAD_QTY)s, %(SHIFT_ID)s, %(SETUP_COMPLETED)s, %(PASS_FAIL)s, %(CREATE_DATE)s, %(REASON)s, %(USER_ID)s, %(OPEN_OP)s)
If you still get odd errors I suggest renaming the column TYPE to something
that is not a key word.
|
Hadoop ERROR streaming
Question: I have a Mapper:
join1_mapper.py
#!/usr/bin/env python
import sys
for line in sys.stdin:
line = line.strip()
key_value = line.split(",")
key_in = key_value[0].split(" ")
value_in = key_value[1]
if len(key_in)>=2:
date = key_in[0]
word = key_in[1]
value_out = date+" "+value_in
print( '%s\t%s' % (word, value_out) )
else:
print( '%s\t%s' % (key_in[0], value_in) )
and I have this reducer:
import sys
prev_word = " "
months = ['Jan','Feb','Mar','Apr','Jun','Jul','Aug','Sep','Nov','Dec']
dates_to_output = []
day_cnts_to_output = []
line_cnt = 0
for line in sys.stdin:
line = line.strip()
key_value = line.split('\t')
line_cnt = line_cnt+1
curr_word = key_value[0]
value_in = key_value[1]
if curr_word != prev_word:
if line_cnt>1:
for i in range(len(dates_to_output)):
print('{0} {1} {2} {3}'.format(dates_to_output[i],prev_word,day_cnts_to_output[i],curr_word_total_cnt))
dates_to_output =[]
day_cnts_to_output=[]
prev_word =curr_word
if (value_in[0:3] in months):
date_day =value_in.split()
dates_to_output.append(date_day[0])
day_cnts_to_output.append(date_day[1])
else:
curr_word_total_cnt = value_in
for i in range(len(dates_to_output)):
print('{0} {1} {2} {3}'.format(dates_to_output[i],prev_word,day_cnts_to_output[i],curr_word_total_cnt))
when I run this JOB:
hadoop jar /usr/lib/hadoop-mapreduce/hadoop-streaming.jar -input /user/cloudera/input -output /user/cloudera/output_join -mapper /home/cloudera/join1_mapper.py -reducer /home/cloudera/join1_reducer.py
I get the error:
>
> ERROR streaming.StreamJob: Job not successful!
> Streaming Command Failed!
>
The first part the log say:
>
> packageJobJar: [] [/usr/jars/hadoop-streaming-2.6.0-cdh5.4.2.jar]
> /tmp/streamjob7178107162745054499.jar tmpDir=null15/11/13 02:03:42 INFO
> client.RMProxy: Connecting to ResourceManager at /0.0.0.0:803215/11/13
> 02:03:42 INFO client.RMProxy: Connecting to ResourceManager at
> /0.0.0.0:803215/11/13 02:03:43 INFO mapred.FileInputFormat: Total input
> paths to process : 415/11/13 02:03:43 INFO mapreduce.JobSubmitter: number of
> splits:515/11/13 02:03:43 INFO mapreduce.JobSubmitter: Submitting tokens for
> job: job_1445251653083_001315/11/13 02:03:44 INFO impl.YarnClientImpl:
> Submitted application application_1445251653083_001315/11/13 02:03:44 INFO
> mapreduce.Job: The url to track the job:
> http://quickstart.cloudera:8088/proxy/application_1445251653083_0013/15/11/13
> 02:03:44 INFO mapreduce.Job: Running job: job_1445251653083_001315/11/13
> 02:03:53 INFO mapreduce.Job: Job job_1445251653083_0013 running in uber mode
> : false15/11/13 02:03:53 INFO mapreduce.Job: map 0% reduce 0%15/11/13
> 02:04:19 INFO mapreduce.Job: map 40% reduce 0%15/11/13 02:04:19 INFO
> mapreduce.Job: Task Id : attempt_1445251653083_0013_m_000002_0, Status :
> FAILEDError: java.lang.RuntimeException: PipeMapRed.waitOutputThreads():
> subprocess failed with code 1 at
> org.apache.hadoop.streaming.PipeMapRed.waitOutputThreads(PipeMapRed.java:322)
> at
> org.apache.hadoop.streaming.PipeMapRed.mapRedFinished(PipeMapRed.java:535)
> at org.apache.hadoop.streaming.PipeMapper.close(PipeMapper.java:130) at
> org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:61) at
> org.apache.hadoop.streaming.PipeMapRunner.run(PipeMapRunner.java:34) at
> org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:453) at
> org.apache.hadoop.mapred.MapTask.run(MapTask.java:343) at
> org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:163) at
> java.security.AccessController.doPrivileged(Native Method) at
> javax.security.auth.Subject.doAs(Subject.java:415) at
> org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1671)
> at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)15/11/13
> 02:04:19 INFO mapreduce.Job: Task Id :
> attempt_1445251653083_0013_m_000003_0, Status : FAILEDError:
> java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess
> failed with code 1 at
>
I've searched in the url:
<http://quickstart.cloudera:8088/proxy/application_1445251653083_0013/> any
help but for me it is not clear what should I do. I don't understand where the
error is. Could someone please help me?
Answer: I have solved. In the INPUT Directory from HDFS must be only the TXT-Files
from the Calculation. In my case I had other files. I created another
directory. After I sent the TXT-Files back into the new directory. I ran the
program again in the new HDFS-INPUT directory. Now it worked.
|
python if statement always false
Question: I am having issues with an if statement always returning false. I am writing
my code in Canopy. I am almost positive it's my syntax, because I replaced "is
'graj mahal'" with "> 200", input a value of 300 and it returned "sounds
great!". Here is the excerpt of my code in question:
answer = str(raw_input("What do you want for dinner?"))
if answer is "graj mahal":
print ("Sounds great!")
else:
print ("Ewie")
print ("the end")
Any suggestions? Thanks for your help.
Answer: The reason OP's code was not working was that he was checking for the identity
of two equal strings, which, even if equal, are not considered the same
object.
In some conditions, the interpreter may cache string values (this is called
string "interning"), but not always, and only for short strings.
It's very important to properly differentiate the concepts of identity and
equality in Python. Identical objects sit at the same address in memory. Equal
objects are considered so by the return value of `__eq__`.
|
Use attribute and target matrices for TensorFlow Linear Regression Python
Question: I'm trying to follow [this
tutorial](http://www.tensorflow.org/tutorials/mnist/beginners/index.md).
TensorFlow just came out and I'm really trying to understand it. I'm familiar
with _penalized linear regression_ like Lasso, Ridge, and ElasticNet and its
usage in `scikit-learn`.
For `scikit-learn` Lasso regression, all I need to input into the regression
algorithm is `DF_X` [an M x N dimensional attribute matrix (pd.DataFrame)] and
`SR_y` [an M dimensional target vector (pd.Series)]. The `Variable` structure
in TensorFlow is a bit new to me and I'm not sure how to structure my input
data into what it wants.
It seems as if softmax regression is for classification. **How can I
restructure my`DF_X` (M x N attribute matrix) and `SR_y` (M dimensional target
vector) to input into `tensorflow` for linear regression?**
My current method for doing a Linear Regression uses pandas, numpy, and
sklearn and it's shown below. I think this question will be really helpful for
people getting familiar with TensorFlow:
#!/usr/bin/python
import pandas as pd
import numpy as np
import tensorflow as tf
from sklearn.linear_model import LassoCV
#Create DataFrames for attribute and target matrices
DF_X = pd.DataFrame(np.array([[0,0,1],[2,3,1],[4,5,1],[3,4,1]]),columns=["att1","att2","att3"],index=["s1","s2","s3","s4"])
SR_y = pd.Series(np.array([3,2,5,8]),index=["s1","s2","s3","s4"],name="target")
print DF_X
#att1 att2 att3
#s1 0 0 1
#s2 2 3 1
#s3 4 5 1
#s4 3 4 1
print SR_y
#s1 3
#s2 2
#s3 5
#s4 8
#Name: target, dtype: int64
#Create Linear Model (Lasso Regression)
model = LassoCV()
model.fit(DF_X,SR_y)
print model
#LassoCV(alphas=None, copy_X=True, cv=None, eps=0.001, fit_intercept=True,
#max_iter=1000, n_alphas=100, n_jobs=1, normalize=False, positive=False,
#precompute='auto', random_state=None, selection='cyclic', tol=0.0001,
#verbose=False)
print model.coef_
#[ 0. 0.3833346 0. ]
Answer: Softmax is an only addition function (in logistic regression for example), it
is not a model like
model = LassoCV()
model.fit(DF_X,SR_y)
Therefore you can't simply give it data with fit method. However, you can
simply create your model with the help of TensorFlow functions.
First of all, you have to create a computational graph, for example for linear
regression you will create tensors with the size of your data. They are only
tensors and you will give them your array in another part of the program.
import tensorflow as tf
x = tf.placeholder("float", [4, 3])
y_ = tf.placeholder("float",[4])
When you create two variables, that will contain initial weights of our model
W = tf.Variable(tf.zeros([3,1]))
b = tf.Variable(tf.zeros([1]))
And now you can create the model (you want to create regression, not
classification therefore you don't need to use tf.nn.softmax )
y=tf.matmul(x,W) + b
As you have regression and linear model you will use
loss=tf.reduce_sum(tf.square(y_ - y))
Then we will train our model with the same step as in the tutorial
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
Now that you created the computational graph you have to write one more part
of the program, where you will use this graph to work with your data.
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
sess.run(train_step, feed_dict={x:np.asarray(DF_X),y_:np.asarray(SR_y)})
Here you give your data to this computational graph with the help of
feed_dict. In TensorFlow you provide information in numpy arrays. If you want
to see your mistake you can write
sess.run(loss,feed_dict={x:np.asarray(DF_X),y_:np.asarray(SR_y)})
|
pairwise comparison within a column pandas python Biopython
Question: i have a large data set that i read in with pandas and i want to do pairwise
alignment by pairwise2.
import pandas as pd
from pandas import DataFrame
from Bio import pairwise2 #for pairwise alignments
from Bio.pairwise2 import format_alignment #for printing alignments out neatly
but here i will use a mock data set:
data = { 'sequence': ['ACAAGAGTGGGACTATACAGTGGGTACAGTTATGACTTC', 'GCACGGGCCCTTGGCTAC', 'GCAACAAGGGGGGATACAGCGGGAACAGTGGACAAGTGGTTCGATGTC']}
data = DataFrame(data)
look like this:
Out[34]:
sequence
0 ACAAGAGTGGGACTATACAGTGGGTACAGTTATGACTTC
1 GCACGGGCCCTTGGCTAC
2 GCAACAAGGGGGGATACAGCGGGAACAGTGGACAAGTGGTTCGATGTC
my goal is to do a pairwise alignment within the 'sequence' column, so the
first row compares with the second, then the second compares with the third,
the third compares with the first, and so on for a larger data set.
my code :
for seq in data['sequence']:
for a in pairwise2.align.globalxx(seq, seq):
print(format_alignment(*a)) #this is just to print the alignment out neatly.
this prints out:
ACAAGAGTGGGACTATACAGTGGGTACAGTTATGACTTC
|||||||||||||||||||||||||||||||||||||||
ACAAGAGTGGGACTATACAGTGGGTACAGTTATGACTTC
Score=39
GCACGGGCCCTTGGCTAC
||||||||||||||||||
GCACGGGCCCTTGGCTAC
Score=18
GCAACAAGGGGGGATACAGCGGGAACAGTGGACAAGTGGTTCGATGTC
||||||||||||||||||||||||||||||||||||||||||||||||
GCAACAAGGGGGGATACAGCGGGAACAGTGGACAAGTGGTTCGATGTC
Score=48
which is close to what i want but it only compares the first to the first,
second to second and third to third.
so i tried this:
for seq in data['sequence']: #for each 'sequence' column value
for index, row in data.iterrows(): #for each row
for a in pairwise2.align.globalxx(seq, row['sequence']): #compare 'sequence' column value to each row of the 'sequence' column
print(format_alignment(*a))
this gave out way too many lines of output i'm not even going to try to post
it here.
my idea was to compare the 'sequence' value to the rows of the 'sequence'
column, but the output gave way too many alignments than expected. i think the
double loop is not the way to go here. **i guess my question doesn't even have
anything to do with Biopython, just simply how can i do pairwise comparisons
within one column?**
Answer: Use the combinatoric generators from
[`itertools`](https://docs.python.org/2/library/itertools.html#itertools.combinations).
for seq0, seq1 in itertools.combinations(data['sequence'], 2):
for a in pairwise2.align.globalxx(seq0, seq1):
print(format_alignment(*a))
|
Dynamic Python Unit Test
Question: I am new to python unit testing. I have been playing with unittest and
py.test. I want to validate data in that is ini format. An example
[Section1]
key1 = value1
key2 = value2
key3 = value3
...
[Section2]
key1 = value1
...
The section names could be different in the ini file. I have data and I
compare it to the section/keynames.
I'm trying to create a test case for each section so I can generate a report
with failures by section name and which key/value is wrong. I research by I am
totally stuck.
Answer: Where gold.cfg is:
> [Section1]
> key1 = value1
> key2 = value2
> key3 = value3
>
> [Section2]
> key4 = value4
> key5 = value5
> key6 = value6
>
> [Section3]
> key7 = value7
> key8 = value8
> key9 = value9
>
And where example.cfg is:
> [Section1]
> key1 = value1
> key2 = value2
> key3 = value3
>
> [Section2]
> key1 = value1
>
# -*- coding: utf-8 -*-
import unittest
try:
import ConfigParser as configparser # Python 2
except ImportError:
import configparser # Python 3
class TestValidConfig(unittest.TestCase):
def setUp(self):
self.gold_config = configparser.RawConfigParser()
self.gold_config.read('gold.cfg')
self.allowed_section_names = self.gold_config.sections()
return None
def _test_allowed_section_names_pass(self):
example_config = configparser.RawConfigParser()
example_config.read('example.cfg')
for section_name in example_config.sections():
self.assertTrue(section_name in self.allowed_section_names)
return None
def test_values_by_section_pass(self):
"""Test example using setUp()"""
example_config = configparser.RawConfigParser()
example_config.read('example.cfg')
for section_name in example_config.sections():
example_pairs = example_config.items(section_name)
gold_pairs = self.gold_config.items(section_name)
self.assertTrue(set(example_pairs).issubset(set(gold_pairs)))
return None
if __name__ == '__main__':
unittest.main()
Iterate over the section named with the sections() method: `for section_name
in example_config.sections()`.
The items() method returns a list of key, value tuples, so use set to assert
that the list of key, value pairs from the example file is a
[subset](https://docs.python.org/2/library/stdtypes.html#set.issubset) of the
key, value pairs from your gold copy.
(If the gold copy has a single section listed all allowed key/value pairs,
modify the code so that section name is used explicitly during the
comparison.)
|
Using AWS ECS with Boto3
Question: I would like to lunch a Task on ECS cluster and wait for the task termination.
import boto3
client = boto3.client('ecs')
response = client.run_task(
cluster='default',
taskDefinition='RGB',
overrides={
'containerOverrides': [
{
'name': 'RGB',
'command': [
'python',
'-u',
'rgb.py'
]
}
]
}
)
arn = response["tasks"][0]['taskArn']
waiter = client.get_waiter('tasks_running')
waiter.wait(cluster='default', tasks=[arn])
Is it the correct way?
> I am getting: botocore.exceptions.WaiterError: Waiter TasksRunning failed:
> Waiter encountered a terminal failure state
Answer: Just change:
waiter = client.get_waiter('tasks_running')
for
waiter = client.get_waiter('tasks_stopped')
|
python, heapq: difference between heappushpop() and heapreplace()
Question: I couldn't figure out the difference (other than ordinality of push/pop
actions) between functions heapq.heappushpop() and heapq.heapreplace() when i
tested out the following code.
>>> from heapq import *
>>> a=[2,7,4,0,8,12,14,13,10,3,4]
>>> heapify(a)
>>> heappush(a,9)
>>> a
[0, 2, 4, 7, 3, 9, 14, 13, 10, 8, 4, 12]
>>> heappop(a)
0
>>> b=a.copy()
>>> heappushpop(a,6)
2
>>> heapreplace(b,6)
2
>>> a
[3, 4, 4, 7, 6, 9, 14, 13, 10, 8, 12]
>>> b
[3, 4, 4, 7, 6, 9, 14, 13, 10, 8, 12]
Answer: `heapreplace(a, x)` returns the smallest value originally in `a` regardless of
the value of `x`, while, as the name suggests, `heappushpop(a, x)` pushes `x`
onto `a` _before_ popping the smallest value. Using your data, here's a
sequence that shows the difference:
>>> from heapq import *
>>> a = [2,7,4,0,8,12,14,13,10,3,4]
>>> heapify(a)
>>> b = a[:]
>>> heappushpop(a, -1)
-1
>>> heapreplace(b, -1)
0
|
Python Impyla fails after Kerberos install
Question: I'm on a W7 machine, where I use Python (Anaconda distribution) to connect to
Impala in our Hadoop cluster using the Impyla package. My company has recently
added Kerberos and that ended up breaking what I had in place.
**before Kerberos:**
from impala.dbapi import connect
conn = connect( host='localhost', port=21050)
cur = conn.cursor()
cur.execute('SHOW TABLES')
cur.fetchall()
**after Kerberos**
from impala.dbapi import connect
conn = connect( host='localhost', port=21050, use_kerberos=True,
kerberos_service_name='impala/myservername')
Traceback (most recent call last):
File "<ipython-input-13-068c7348729f>", line 2, in <module>
kerberos_service_name='impala/myservername')
File "C:\Users\x\AppData\Local\Continuum\Anaconda\lib\site-packages\impala\dbapi\__init__.py", line 47, in connect
ldap_password, use_kerberos, kerberos_service_name)
File "C:\Users\x\AppData\Local\Continuum\Anaconda\lib\site-packages\impala\_rpc\hiveserver2.py", line 193, in connect_to_impala
use_kerberos, kerberos_service_name)
File "C:\Users\x\AppData\Local\Continuum\Anaconda\lib\site-packages\impala\_rpc\hiveserver2.py", line 166, in _get_transport
import sasl
ImportError: No module named sasl
I tried installing sasl from CMD:
>easy_install sasl
Searching for sasl
Reading https://pypi.python.org/simple/sasl/
Best match: sasl 0.1.3
Downloading https://pypi.python.org/packages/source/s/sasl/sasl-0.1.3.tar.gz#md5
=6db4ca3d4fb699cf126a6e6f2f516d8f
Processing sasl-0.1.3.tar.gz
Writing c:\users\x\appdata\local\temp\easy_install-zfqesn\sasl-0.1.3\setup
.cfg
Running sasl-0.1.3\setup.py -q bdist_egg --dist-dir c:\users\x\appdata\loc
al\temp\easy_install-zfqesn\sasl-0.1.3\egg-dist-tmp-cl0non
sasl/saslwrapper.cpp:21:23: fatal error: sasl/sasl.h: No such file or directory
compilation terminated.
error: Setup script exited with error: command 'C:\\Users\\x\\AppData\\Loc
al\\Continuum\\Anaconda\\Scripts\\gcc.bat' failed with exit status 1
Answer: I see you are running Windows. Are you running cygwin or some other python?
Have you tried:
1. If using Cygwin, have you tried installing libsasl2-devel ?
2. installing python-sasl from the GIT repository as Cloudera seems to do as part of their [jenkins environment](https://github.com/cloudera/impyla/blob/86e1a9f916785ccc77700de4327ecf77e4820fbd/jenkins/run-dbapi.sh#L90)?
pip install git+<https://github.com/laserson/python-sasl.git@cython>
Should do the magic.
By the way, the code you are using has been deprecated (as per the current
GitHub master).
Use
from impala.dbapi import connect
conn = connect( host='localhost', port=21050, auth_mechanism='GSSAPI',
kerberos_service_name='impala')
|
import gensim imports a file in an active module, not the root site-packages folder
Question: I'm running Anaconda Python 2.7 on Windows. I've installed gensim and pyLDAvis
to do some topic modeling. (Note installing pyLDAvis on python 2.7 in windows
is a little tricky as you have to make sure you are not using scikit-bio which
doesn't appear to compile on Windows 2.7... I think I have a workaround for
this, but I can't try it because of reasons to be outlined below!)
So I got pyLDAvis to install. However when running, it seems to have a problem
with an import statement.
pyLDAvis is installed in this folder....
C:\Anaconda2\Lib\site-packages\pyLDAvis-1.3.2-py2.7.egg\pyLDAvis
`sys.path` returns this:
['',
'C:\\Anaconda2\\lib\\site-packages\\pyldavis-1.3.2-py2.7.egg',
'C:\\Anaconda2\\lib\\site-packages\\joblib-0.9.3-py2.7.egg',
'C:\\Anaconda2\\python27.zip',
'C:\\Anaconda2\\DLLs',
'C:\\Anaconda2\\lib',
'C:\\Anaconda2\\lib\\plat-win',
'C:\\Anaconda2\\lib\\lib-tk',
'C:\\Anaconda2',
'C:\\Anaconda2\\Library\\bin',
'c:\\anaconda2\\lib\\site-packages\\sphinx-1.3.1-py2.7.egg',
'c:\\anaconda2\\lib\\site-packages\\setuptools-18.4-py2.7.egg',
'C:\\Anaconda2\\lib\\site-packages',
'C:\\Anaconda2\\lib\\site-packages\\cryptography-1.0.2-py2.7-win-amd64.egg',
'C:\\Anaconda2\\lib\\site-packages\\win32',
'C:\\Anaconda2\\lib\\site-packages\\win32\\lib',
'C:\\Anaconda2\\lib\\site-packages\\Pythonwin',
'C:\\Anaconda2\\lib\\site-packages\\IPython\\extensions']
What is happening is that when I try to run `pyLDAvis`, the library calls
`import gensim`. However, `gensim` is both a folder in the `site-packages` and
a file (`gensim.py`) inside `pyLDAvis`.
So when python tries to `import gensim` inside the `pyLDAvis` module, it
imports the `gensim.py` file within the `pyLDAvis` module, not the
``gensim`folder inside`site-packages`.
How do I go about fixing this?
Thanks.
Answer: File an issue report on [pyLDAvis's
GitHub](https://github.com/bmabey/pyLDAvis/issues). It looks like a [recent
change](https://github.com/bmabey/pyLDAvis/commit/848b247b77bb24b1e674aa0cf7c0d5f9b4f26a9d)
broke Python 2 compatibility by assuming Python 3 absolute import behavior for
`import gensim`.
In the meantime, I believe the bug isn't present in the 1.3.1 release, so you
could use that. Alternatively, you could edit `pyLDAvis/gensim.py` and add
`from __future__ import absolute_import` at the top. That'd _probably_ work as
a temporary fix, but I didn't try it.
|
jQuery ajax code loading scripts as text, but some of the code is being processed
Question: I am working on a block of code and it is doing something funny. I wrote this
for a site that I am working on to load a url from an XML file and insert the
code from a server side file into the pre tag as a way of showing the code I
developed for a class. This block works just fine for both Python and MEL
scripts, but when I tried to load the scripts for the site itself (javascript
and xml) which I developed as a side project for the class, it tries to
evaluate parts of it. Specifically, the HTML tags tags that are inside of the
code. I am unsure of how to stop this from happening. It isn't direly
important that I have this, I would just like to show off the work that I did
that was above and beyond the rest of the class for potential future
employers. I am really proud of the site as it sits.
id = $(this).attr("id");
$("#"+location+"_code").append("<a href='"+$(this).attr("src")+"' class='download' download/><dt>"+$(this).attr("title")+"</dt><dd><pre id='"+id+"'></pre></dd>");
$.ajax({
url:$(this).attr('src'),
dataType: "text",
async: false,
success: function(data) {
$("#"+id).append(data);
}
});
How do I prevent the browser from actually processing the text as anything but
text? I really was hoping that this would just display the code as a straight
string. I thought about using a textarea instead of a pre, but that just
caused a host of other issues that I didn't feel like dealing with. Any
suggestions?
Answer: You need to HTML encode your result so it displays as text. Try this:
var $result = $('<div/>').text(data);
$('#' + id).append($result);
|
Celery (Django) ImportError: No module named billiard.exceptions
Question: I'm using current versions (Celery 3.1.19, Billiard 3.3.0.21) and unable to
successfully deploy my Django site to AWS Elastic Beanstalk.
I'm trying to figure out if this is a WSGI issue, a system path issue, an app
issue, etc. I had the site working, but I upgraded Celery and other pip
packages as well as Amazon's AMI (at the same time... not smart for
debugging).
This is the stack trace:
Target WSGI script '/opt/python/current/app/mysite/wsgi.py' cannot be loaded as Python module.
Exception occurred processing WSGI script '/opt/python/current/app/mysite/wsgi.py'.
Traceback (most recent call last):
File "/opt/python/current/app/mysite/wsgi.py", line 23, in <module>
application = get_wsgi_application()
File "/opt/python/run/venv/lib/python2.7/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application
django.setup()
File "/opt/python/run/venv/lib/python2.7/site-packages/django/__init__.py", line 17, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "/opt/python/run/venv/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in __getattr__
self._setup(name)
File "/opt/python/run/venv/lib/python2.7/site-packages/django/conf/__init__.py", line 44, in _setup
self._wrapped = Settings(settings_module)
File "/opt/python/run/venv/lib/python2.7/site-packages/django/conf/__init__.py", line 92, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/opt/python/current/app/mysite/__init__.py", line 5, in <module>
from .celery import app as celery_app
File "/opt/python/current/app/mysite/celery.py", line 3, in <module>
from celery import Celery
File "/opt/python/run/venv/lib/python2.7/site-packages/celery/five.py", line 306, in __getattr__
module = __import__(self._object_origins[name], None, None, [name])
File "/opt/python/run/venv/lib/python2.7/site-packages/celery/app/__init__.py", line 14, in <module>
from celery import _state
File "/opt/python/run/venv/lib/python2.7/site-packages/celery/_state.py", line 20, in <module>
from celery.utils.threads import LocalStack
File "/opt/python/run/venv/lib/python2.7/site-packages/celery/utils/__init__.py", line 27, in <module>
from celery.exceptions import CPendingDeprecationWarning, CDeprecationWarning
File "/opt/python/run/venv/lib/python2.7/site-packages/celery/exceptions.py", line 15, in <module>
from billiard.exceptions import ( # noqa
ImportError: No module named billiard.exceptions
AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.
Just a line before `application = get_wsgi_application()` I print `sys.path`:
['/opt/python/run/venv/lib/python2.7/site-packages',
'/opt/python/current/app',
'',
'/opt/python/run/baselinenv/local/lib64/python2.7/site-packages',
'/opt/python/run/baselinenv/local/lib/python2.7/site-packages',
'/opt/python/run/baselinenv/lib64/python2.7',
'/opt/python/run/baselinenv/lib/python2.7',
'/opt/python/run/baselinenv/lib64/python2.7/site-packages',
'/opt/python/run/baselinenv/lib/python2.7/site-packages',
'/opt/python/run/baselinenv/lib64/python2.7/lib-dynload',
'/usr/lib64/python2.7',
'/usr/lib/python2.7']
In my wsgi.conf:
WSGIPythonHome /opt/python/run/baselinenv
Any guidance on even where to start debugging this will be helpful.
Answer: The problem was my `WSGIDaemonProcess` `python-path` in my wsgi.conf. I had to
add a reference to `lib64` in addition to the normal `lib` directory.
python-path=/opt/python/current/app:/opt/python/run/venv/lib/python2.7/site-packages:/opt/python/run/venv/lib64/python2.7/site-packages
|
Adding progress feedback in Grequests task
Question: I've followed the grequests [usage
example](https://github.com/kennethreitz/grequests), but I'm trying to add
some progress feedback. A percentage of the completed requests. How could I
achieve that?
import grequests
urls = [
'http://www.heroku.com',
'http://python-tablib.org',
'http://httpbin.org',
'http://python-requests.org',
'http://kennethreitz.com'
]
def feedback(r, **kwargs):
print "%s fetched." % r.url
return r
rs = (grequests.get(u, callback=feedback) for u in urls)
res = grequests.map(rs)
Answer: Try this:
from gevent import monkey
monkey.patch_all()
import gevent
import sys
import requests
rs = [gevent.spawn(requests.get, u) for u in urls]
[i.start() for i in rs]
while 1:
gevent.sleep()
percent = 0.0
for i in rs:
if i.successful():
percent += 100 / len(rs)
sys.stdout.write(('='*int(percent))+(''*(100-int(percent)))+("\r [ %d"%percent+"% ] "))
sys.stdout.flush()
if percent == 100:
sys.stdout.write('\n')
sys.stdout.flush()
break
|
Remove special characters from indvisual python list
Question: I have a list that contain many elements. I was able to find a way to remove
duplicates, blank values, and white space.
The only thing left is to:
1. remove any thing that contain (ae) string.
2. remove from the list any thing that contain the period (.)
Order of the resulting list is not important. The final list should only
contain:
FinalList = ['eth-1/1/0', 'jh-3/0/1', 'eth-5/0/0','jh-5/9/9']
Code:
XYList = ['eth-1/1/0', 'ae1', 'eth-1/1/0', 'eth-1/1/0', 'ae1', 'jh-3/0/1','jh-5/9/9', 'jh-3/0/1.3321', 'jh-3/0/1.53', 'ae0', '', 'eth-5/0/0', 'ae0', '', 'eth-5/0/0', 'ae0', 'eth-5/0/0', '', 'jh-2.1.2']
XYUnique = set(XYList)
XYNoBlanks = (filter(None,XY))
RemovedWhitespace = [item.strip() for item in XYNoBlanks]
# the order of the list is not important
# the final result should be
FinalList = ['eth-1/1/0', 'jh-3/0/1', 'eth-5/0/0','jh-5/9/9']
Answer: The entire conversion sequence (excluding uniqueness) can be accomplished with
a list comprehension:
FinalList = [elem.strip() for elem in set(XYList) if elem and "." not in elem and "ae" not in elem]
|
Python prints unwanted extra newline
Question: Why is that Python always prints an extra newline when I run the code below? I
tried to re-write the code to eliminate any unintended blank space but it
still prints out an extra new line. Anyone knows why? Thanks.
def main():
names_in() #This function import the file and read all the content and put the content into a list.
print_names(names_in) # Before the names are sorted.
def names_in():
infile = open('names.txt','r')
names_list = [] #empty list.
names = infile.readline() # read contents.
#loop for continue to read.
while names != '':
names = infile.readline() #continue to the next name.
names = names.rstrip('\n') #return a copy of the string which all \n has been stripped from the end of the string.
names_list.append(names) #write names in the file into a list.
infile.close()
return names_list #return the list back to the function.
def print_names(names_in): #This function will print out the names in the list one per line, single-spaced.
for item in names_in():
print(item)
main()
This in my input file:
Riggs, Jerry
Stone, Ruby
Wood, Holly
Dover, Ilene
Funt, Ella
Storm, Wayne
Lowe, Lyle
Free, Bjorn
Caine, Candy
Carr, Rex
Downs, Mark
Twain, Lionel
Thorn, Rose
Shore, Rocky
Bush, Rose
Waters, Muddy
Graves, Doug
Stone, Roxanne
Rivers, Wade
Answer: The reason that your code prints an extra newline is because in the last
iteration of the `names_in` function, the variable `names` is ``, which gets
appended to the end of `names_list`, causing the `print_names` function to run
`print ''` at the end, which prints an extra newline.
|
Font not printing out in pygame program
Question: I'm writing a program in Python that will act as a scratch ticket type of
game. I have everything done except printing out the numbers when the user
'scratches off' the square on the ticket. This is my code:
import pygame
pygame.init()
pygame.font.init()
screen = pygame.display.set_mode((300,450))
pygame.display.set_caption("test grid")
background = pygame.Surface(screen.get_size())
background.fill((209, 95, 238))
clock = pygame.time.Clock()
keepGoing = True
pos = [0, 0]
x = 40
for line in range(5):
y = 200
for row in range(4):
pygame.draw.rect(background, (238, 201, 0), (x, y, 40, 40), 0)
y += 45
x += 45
board = [[1, 1, 3, 15, 11],
[1, 14, 13, 15, 9],
[2, 6, 7, 15, 5],
[8, 10, 4, 12, 7]]
myfont = pygame.font.SysFont("arial", 50)
while keepGoing:
clock.tick(30)
y = 200
x = 40
x1 = 40
x2 = 80
y1 = 200
y2 = 240
num = 0
label = myfont.render(str(num),1,(255,255,255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
keepGoing = False
elif event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
print pygame.mouse.get_pos()
for row in range(4):
for line in range(5):
if pos[0] >= x1 and pos[0] <= x2 and pos[1] >= y1 and pos[1] <= y2:
pygame.draw.rect(background, (0,0,0), (x,y,40,40), 0)
num = board[row][line]
label = myfont.render(str(num), 1, (255,255,255))
x1 += 45
else:
x1 += 45
x2 += 45
x += 45
x = 40
y += 45
y1 += 45
y2 += 45
x1 = 40
x2 = 80
screen.blit(label,(200,200))
screen.blit(background, (0,0))
pygame.display.flip()
pygame.quit()
For some reason that I can't figure out, not matter what I do, none of my font
stuff will print out. I tried declaring it outside the loop only, I tried
declaring it inside the loop only, I tried both together, and for some reason
nothing will work, and I can't figure out why my text refuses to print on the
screen. Help, please?
My teacher said it was something to do with my x1 and x2 variables, but I
checked and they're doing exactly what they should be doing.
(For anyone wondering, the reason I added 45 to x1 even if the statement in
the if is true is because that way it won't continue to repeat and print out
the number again and again until the for loop is over. Not the greatest
solution but the only one I could think of.)
Answer: Just before updating the screen with `pygame.display.flip`, your code runs
`screen.blit(background,(0,0))`, which completely overrides everything you
have drawn to the screen. Moving the blitting of the background to the
beginning of your `while keepGoing` loop would solve this.
|
How to automatically parse csv in python 2.7 into int, string and list objects and their values
Question: I want to be able to parse csv files that will be maintained outside of our
software group. A sample csv may contain:
temperature,50,55,56
color,blue
count,10
dummy,line
The code will search the file for a list of ints called temperature, a string
called color and an int called count. Then it will assign the values [50, 55,
56], 'blue' and 10 respectively.
* The row ordering in the csv files is arbitrary (e.g. sometimes 'color' could come before 'temperature').
* The object names are predefined but the values will vary between csv files.
* The csv files will always contain the object names that the python code searches for.
* The csv files may contain extra data rows that are not useful to the python code.
* The object names will always be in the first column of the csv.
I have seen other code examples that search for specific object types, or
objects in predefined row positions. However, I need a solution that is more
robust.
Any help will be appreciated. Please let me know if you need clarification and
I will edit.
Answer: All you need is something like the following:
import csv
with open('file.csv', 'r') as f:
reader = csv.reader(f)
dummy = []
temperature = []
color = ''
count = 0
for row in reader:
try:
if row[0] == 'temperature':
temperature = map(int, row[1:])
elif row[0] == 'color':
color = row[1]
elif row[0] == 'count':
count = int(row[1])
else:
dummy.append(row)
# for robustness, let's catch the case where a row
# may be malformed or does not contain more than 1 column
except IndexError:
dummy.append(row)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.