text
stringlengths 226
34.5k
|
---|
Python Beautiful Soup Scraping Exact Content From Charts
Question: In python using beautiful soup I want to be able to grab specific text
`<a>/numbers<td>` from a sortable table online.
[http://www.nfl.com/stats/categorystats?archive=false&conference=null&role=OPP&offensiveStatisticCategory=null&defensiveStatisticCategory=INTERCEPTIONS&season=2014&seasonType=REG&tabSeq=2&qualified=false&Submit=Go](http://www.nfl.com/stats/categorystats?archive=false&conference=null&role=OPP&offensiveStatisticCategory=null&defensiveStatisticCategory=INTERCEPTIONS&season=2014&seasonType=REG&tabSeq=2&qualified=false&Submit=Go)
I have attempted this about a million times and can't figure it out.
This is the best i could do:
from bs4 import BeautifulSoup
import urllib2
import requests
import pymongo
import re
soup = BeautifulSoup(urllib2.urlopen('http://www.nfl.com/stats/categorystats?archive=false&conference=null&role=OPP&offensiveStatisticCategory=null&defensiveStatisticCategory=INTERCEPTIONS&season=2014&seasonType=REG&tabSeq=2&qualified=false&Submit=Go').read())
find = soup('a', text="Miami Dolphins")
print find
I don't know how to find/call the 10th (9th in python) < td > tag after Miami
Dolphins.
The table code looks something like this.
<table id="result" style="width:100%" cellpadding="0" class"data-table1"
cellspacing="0">
<caption class="thd1">...</caption>
<tbody>...</tbody>
<tbody>
<tr class="odd">...</tr>
<tr class="even">...</tr>
<tr class="odd">...</tr>
<tr class="even">...</tr>
<tr class="odd">...</tr>
<tr class="even">...</tr>
<tr class="odd">...</tr>
<tr class="even">...</tr>
<tr class="odd">...</tr>
<tr class="even">...</tr>
<tr class="odd">...</tr>
<tr class="even">...</tr>
<tr class="odd">...</tr>
<tr class="even">...</tr>
<tr class="odd">...</tr>
<tr class="even">
<td>14</td>
<td>
<a href="/teams/miamidolphins/profile?team=MIA onclick=
"s_objectID="http://www.nfl.com/teams.miamidolphins/profile?
team=MIA_1";return this.s_oc?this.s_oc(e):true">Miami Dolphins</a> *********I want to grab team name**********
</td>
<td>
16
</td>
<td>24.2</td>
<td>
388
</td>
<td class="right">...</td>
<td class="right">...</td>
<td class="right">...</td>
<td class="right">...</td>
<td class="right">...</td>
<td class="right">...</td>
<td class="sorted right">...</td>
"
14 ****I want to grab 10th number/<td> tag after team name****
"
</td>
<td class="right">...</td>
<td class="right">...</td>
<td class="right">...</td>
<td class="right">...</td
</tr>
Answer: Try this
import urllib2
from lxml import etree
url = 'http://www.nfl.com/stats/categorystats?archive=false&conference=null&role=OPP&offensiveStatisticCategory=null&defensiveStatisticCategory=INTERCEPTIONS&season=2014&seasonType=REG&tabSeq=2&qualified=false&Submit=Go'
response = urllib2.urlopen(url)
htmlparser = etree.HTMLParser()
tree = etree.parse(response,htmlparser)
text = tree.xpath('//a[contains(text(),"Miami Dolphins")]/parent::td/following-sibling::td[10]/text()')
if text:
print text[0].strip()
|
python sending a hex string to serial port
Question: I am trying to send a hexadecimal string to a serial port and it has to be in
the following format '\x02\x81....' this is my code
from binascii import unhexlify
string='0281E1B1'
print unhexlify(string)
gives me some randon symbols ?a+ instead of \x02\x81\xE1\xB1 I have python 2.7
so decode('hex') isnt working either
Answer: you are doing it right .... you just need to send it over the port
print repr(unhexlify(my_string))
my_serial.write(unhexlify(my_string))
#or
my_serial.write(my_string.decode("hex"))
the problem is you cant just print random bytes( `"\x##"`) to the terminal and
expect to see something that makes sense ...the terminal displays characters
it cannot decode a ? or like a diamond with a question mark
>>> '0281E1B1'.decode("hex")
'\x02\x81\xe1\xb1'
>>> print '0281E1B1'.decode("hex")
☻üß▒
>>> '0281E1B1'.decode("hex") == unhexlify('0281E1B1')
True
although for whatever weird reason my terminal didnt add any ? to that
particular string
|
python open a serialized C# file
Question: I'm having an issue getting data out of a c# array serialized class with
python. I have two files containing the classes. The first I am able to loop
though the array and grab the public variables. However in the second file I
see the class but am Unable to access any of the variables. It's been 10+
years since I used C# and have been beating my head against the computer. The
only difference I can see is file1.bin uses String where file2.bin uses
string. Any pointers would be mot helpful.
ironpython used to read .bin files.
from System.Runtime.Serialization.Formatters.Binary import BinaryFormatter
from System.IO import FileStream, FileMode, FileAccess, FileShare
from System.Collections.Generic import *
def read(name):
bformatter = BinaryFormatter()
file_stream = FileStream(name, FileMode.Open, FileAccess.Read, FileShare.Read)
res = bformatter.Deserialize(file_stream)
file_stream.Close()
return res
def write(name,data):
bformatter = BinaryFormatter()
stream = FileStream(name, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)
bformatter.Serialize(stream, data)
stream.Close()
res = read('fiel2.bin')
for space in res:
print dir(space)
File1.bin - (simplified) array of Resident - Can Access data
namespace RanchoCSharp
{
[Serializable]
public class Resident
{
public Resident()
{
}
public Resident(String fName, String lName)
{
firstN = fName;
lastN = lName;
}
//Invoice info
public String firstN;
public String lastN;
}
}
file2.bin (simplified) Array of Resident Info Can't access data
namespace Rancho_Resident
{
[Serializable]
class ResidentInfo
{
public ResidentInfo()
{
}
public string unit;
public string space;
}
}
**update**
After looking closer it appears that one class is public and the other is
internal. However, I'm not sure how to access the internal class.
Answer: By default, internal members are invisible to external assemblies including
IronPython, but you can change that.
If you are running `ipy.exe`, start it by:
ipy.exe -X:PrivateBinding
If you are hosting the `IronPython` scripting engine, then add an option:
IDictionary<string, object> options = new Dictionary<string, object>();
options.Add("PrivateBinding", true);
ScriptEngine engine = IronPython.Hosting.Python.CreateEngine(options);
|
servlet filter in jython
Question: Based on [this java example](http://stackoverflow.com/questions/12652957/how-
to-change-the-requesturl-using-filter-or-servlet), I made the following
servlet filter in jython (exact code):
from javax.servlet import Filter
from javax.servlet.http import HttpServletRequest
class HttpServletRequestWrapper(HttpServletRequest):
def init(self, request):
self.originalURL = self.getRequestURL()
pathi = self.originalURL.find('/', 10) # find start of path
qsi = self.originalURL.find('?', pathi) # find start of qs if any
qs = self.originalURL[qsi:] if qsi > -1 else ''
self.newURL = self.originalURL[:pathi] + '/ccc/jope.py' + qs
def getRequestURL(self):
return self.newURL
class Route2Jope(Filter):
def init(self, config):
pass
def doFilter(self, request, response, chain):
wrapped = HttpServletRequestWrapper(request)
chain.doFilter(wrapped, response)
However, I am getting the error message:
Traceback (most recent call last):
File "c:\CCC\webapps\ccc\WEB-INF\pyfilter\Route2Jope.py", line 24, in doFilter
wrapped = HttpServletRequestWrapper(request)
TypeError: org.python.proxies.__main__$HttpServletRequestWrapper$2(): expected 0 args; got 1
org.python.core.Py.TypeError(Py.java:259)
org.python.core.PyReflectedFunction.throwError(PyReflectedFunction.java:209)
org.python.core.PyReflectedFunction.throwArgCountError(PyReflectedFunction.java:262)
org.python.core.PyReflectedFunction.throwError(PyReflectedFunction.java:319)
org.python.core.PyReflectedConstructor.__call__(PyReflectedConstructor.java:177)
org.python.core.PyObject.__call__(PyObject.java:419)
org.python.core.PyMethod.instancemethod___call__(PyMethod.java:237)
org.python.core.PyMethod.__call__(PyMethod.java:228)
org.python.core.PyMethod.__call__(PyMethod.java:223)
org.python.core.Deriveds.dispatch__init__(Deriveds.java:19)
org.python.core.PyObjectDerived.dispatch__init__(PyObjectDerived.java:1112)
org.python.core.PyType.type___call__(PyType.java:1713)
org.python.core.PyType.__call__(PyType.java:1696)
org.python.core.PyObject.__call__(PyObject.java:461)
org.python.core.PyObject.__call__(PyObject.java:465)
org.python.pycode._pyx1.doFilter$6(c:\CCC\webapps\ccc\WEB-INF\pyfilter\Route2Jope.py:25)
org.python.pycode._pyx1.call_function(c:\CCC\webapps\ccc\WEB-INF\pyfilter\Route2Jope.py)
org.python.core.PyTableCode.call(PyTableCode.java:167)
org.python.core.PyBaseCode.call(PyBaseCode.java:307)
org.python.core.PyBaseCode.call(PyBaseCode.java:198)
org.python.core.PyFunction.__call__(PyFunction.java:482)
org.python.core.PyMethod.instancemethod___call__(PyMethod.java:237)
org.python.core.PyMethod.__call__(PyMethod.java:228)
org.python.core.PyMethod.__call__(PyMethod.java:218)
org.python.core.PyMethod.__call__(PyMethod.java:213)
org.python.core.PyObject._jcallexc(PyObject.java:3626)
org.python.proxies.__main__$Route2Jope$3.doFilter(Unknown Source)
org.python.util.PyFilter.doFilter(PyFilter.java:80)
I think it's telling me I should not pass the parameter 'request', but it does
not make sense to me. Maybe I am overlooking some mapping issue between python
ad java classes? Suggestions?
Answer: The name of your constructor must be `__init__`, not `init`. :)
|
Print text from a terminal command into shell
Question: I am creating a MS-DOS replica to test out my python skills since I am
particularly new and I'm writing the "dir" command. Right now, the command
opens a terminal that seems to be doing what I want it to be doing, except for
printing it out into a terminal instead of the program output. I want to
transfer the text it creates in the command line to the output of the program,
basically. Here's what I'm using right now:
if COMMAND == ("dir"):
os.system('dir')
Anyway, thanks for the help if anyone sees this, since I am pretty nooby at
python and new to this website.
Answer: You could use `subprocess.check_output`.
>>> import subprocess
>>> print subprocess.check_output("dir", shell=True)
Volume in drive C is System
Volume Serial Number is E4C1-A0AA
Directory of C:\Users\Kevin
04/30/2015 08:12 AM <DIR> .
04/30/2015 08:12 AM <DIR> ..
03/30/2015 02:51 PM <DIR> Contacts
...
|
Why does running my Python script start taking a screenshot?
Question: I'm writing a script in Python, but when I attempt to run it a cross cursor
appears and lets me take screenshots. But that's not part of my program, and
the rest of the script never executes at all!
The minimal code that produces this behavior is:
import fiona
import scipy
Answer: It's a known issue which regularly happens to some.
Without a `python` shebang line the script is treated as a shell script. And
line `import module` is treated as a command to run `import` application,
which is present on your system (part of ImageMagick, I guess) and makes a
screenshot saving it to the specified file.
|
Python tkinter passing input value within the same class
Question: Most of the code below is just so the problem is accurately replicated, the
issue most likely is in the hand-off of `filename` from`askopenfilenameI()` to
`printing(stringToPrint)`or the `if` statement at the end.
## Goal
The goal of this program is to simply print the file path to the console when
`Print File Path` button is clicked.
## Current state
When the program is executed the window appears correctly and the it lets you
select a file in the file system. Once the file is opened, the script seems to
call `printing` method before it executes its own `print` statement. When I
open another file it prints the only the print statement from
`askopenfilename()` (which is correct).
However, clicking the `Print File Path` Button does not seem to get work at
any stage.
An example output would be:
Value on click: `no-file`
askopenfilename value: `C:/Temp/AFTER_FIRST_OPEN.txt`
askopenfilename value: `C:/Temp/AFTER_SECOND_OPEN.txt`
## Code
import Tkinter, Tkconstants, tkFileDialog
filename = 'no-file'
class TkApp(Tkinter.Frame):
def __init__(self, root):
Tkinter.Frame.__init__(self, root)
# options for buttons
button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5}
# define buttons
Tkinter.Button(self, text='Open File', command=self.askopenfilename).pack(**button_opt)
Tkinter.Button(self, text='Print File Path', command=self.printing(filename)).pack(**button_opt)
Tkinter.Button(self, text='Quit', command=self.quit).pack(**button_opt)
# define options for opening or saving a file
self.file_opt = options = {}
options['defaultextension'] = '.twb'
options['filetypes'] = [('All', '*')]
options['initialdir'] = 'C:\\'
options['parent'] = root
options['title'] = 'Select a File'
def askopenfilename(self):
"""Returns an opened file in read mode.
This time the dialog just returns a filename and the file is opened by your own code.
"""
global filename
# get filename
filename = tkFileDialog.askopenfilename(**self.file_opt)
# open file on your own
if filename:
print "askopenfilename value: " + filename
return filename
def printing(self, stringToPrint):
print "Value on click: " + stringToPrint
def quit(self):
root.destroy()
if __name__=='__main__':
root = Tkinter.Tk()
root.title("Path Printer")
TkApp(root).pack()
root.mainloop()
Answer: The root of your problem is that you're calling `self.printing` at the time
you create the button. The solution is simple: change
`self.printing(filename)` to be just `self.printing`, and then have
`self.printing` print an attribute that is set by `self.askopenfilename`.
For example:
class TkApp(Tkinter.Frame):
def __init__(self, root):
...
self.currentFile = None
...
Tkinter.Button(self, text='Open File', command=self.askopenfilename)
Tkinter.Button(self, text='Print File Path', command=self.printing)
...
def askopenfilename(self):
...
self.currentFile = tkFileDialog.askopenfilename(**self.file_opt)
...
def printing(self):
print "Value on click: " + self.currentFile
Note: a `return` statement in a function that is called from a button serves
absolutely no purpose. The actual caller of the button ignores all return
values.
|
How can I output blank value in python yaml file
Question: I am writing yaml file like this
with open(fname, "w") as f:
yaml.safe_dump({'allow':'', 'deny': ''}, f,
default_flow_style=False, width=50, indent=4)
This outputs:
allow: ''
I want to output as
allow:
How can I do that?
Answer: If you load a YAML src
allow:
into Python you get `None` assigned to the key `allow`, that is the correct
behaviour.
If you use [ruamel.yaml](https://pypi.python.org/pypi/ruamel.yaml) (of which I
am the author), and its `RoundTripDumper`, `None` is written as you want it
(which is IMO the most readable, although not explicit):
import ruamel.yaml
print ruamel.yaml.dump(dict(allow=None), Dumper=ruamel.yaml.RoundTripDumper)
will give you:
allow:
You can also properly round-trip this:
import ruamel.yaml
yaml_src = """
allow:
key2: Hello # some test
"""
data = ruamel.yaml.load(yaml_src, ruamel.yaml.RoundTripLoader)
print '#### 1'
print data['allow']
print '#### 2'
print ruamel.yaml.dump(data, Dumper=ruamel.yaml.RoundTripDumper)
print '#### 3'
print type(data)
to get as output:
#### 1
None
#### 2
allow:
key2: Hello # some test
#### 3
In the above, `data` is a subclass of ordereddict, which is necessary to keep
track of the flowstyle of the input, handling comments attached to lines,
order of the keys, etc..
Such a subclass can be created on the fly, but it is normally easier to start
with some readable and well formatted YAML code (possible already saved on
disc) and then update/extend the values.
|
How to Quickly Assign Letter Counts from Lists to Variables in Python
Question: Basically I have a list of (for all intents and purposes) random letters. The
letters are not really random, they do have significance; however, it really
isn't important for the question. The lists would look something like this:
list = ['v', 'f', 't', 'w', 'w', 'i', 'b']
the real lists are significantly longer (up to 100 characters). I want to
count how many times each letter appears and assign that to a variable that is
that letter. For example:
a = list.count('a')
b = list.count('b')
c = list.count('c')
...
...
z = list.count('z')
I just want to know if there is a simpler way to do this instead of typing the
same line 26 times. I am running Python 3.4. I want to be able to do it in as
few lines and as few characters as possible. Any suggestions would be helpful,
thank you.
Answer:
import collections
counts = collections.Counter(l)
`counts['a']` is then the number of occurrences of `a`. With a list of length
`L` and `N` possible different items, this runs in `O(L)` time instead of the
`O(NL)` a `list.count`-based solution would take, and it's less code.
|
import files inside packages - Project Structure
Question: I have some doubts in relation to packages structure in a python project when
I make the imports
These are some conventions
**`python-irodsclient_API = Project Name`**
I've defined python packages for each file, in this case are the following:
**`python-irodsclient_API/config/`**
**`python-irodsclient_API/connection/`**
_These packages are well define as a packages and not as a directories
really?_

I have the file **`python-irodsclient_API/config/config.py`** in which I've
defined some constants about of configuration for connect with my server:

And I have the **`python-irodsclient_API/connection/connection.py`** file:

In the last or previous image (highlighted in red) .. is this the right way of
import the files?
I feel the sensation of this way is not better. I know that the "imports"
should be relatives and not absolutes (for the path) and that is necessary use
"." instead "*" In my case I don't know if this can be applied in relation to
the I'm doing in the graphics.
I appreciate your help and orientation Best Regards
Answer: There is a good tutorial about this in the [Python module
docs](https://docs.python.org/2/tutorial/modules.html#packages), which
explains how to refer to packages under structured folders.
Basically, `from x import y`, where `y` is a submodule name, allows you to use
`y.z` instead of `x.y.z`.
|
Picking up field value using Python regex
Question: This is an example of two lines in a file that I am trying to pick up
information from.
...
{ "SubtitleSettings_REPOSITORY", FieldType_STRING, (int32_t)REPOSITORY},
{ "PREFERRED_SUBTITLE_LANGUAGE", FieldType_STRING,SUBTITLE_LANGUAGE},
...
What I want to do is to find out the 3rd field of this weird data structure
for the given string to match to 1st field, i.e.
SubtitleSettings_REPOSITORY => REPOSITORY
PREFERRED_SUBTITLE_LANGUAGE => SUBTITLE_LANGUAGE
The regx in my Python code can only handles the second line, but not cope with
the first line. How I can improve it?
import re
...
#field is given a value in previous code, can be "SubtitleSettings_REPOSITORY", or "PREFERRED_SUBTITLE_LANGUAGE"
match = re.search(field+'"[, \t]+(\w+)[, \t]+(\w+)', src_file.read(), re.M|re.I)
return_value = match.group(2)
Answer:
import re
with open("input.txt") as f:
pattern = "\{ \"(.+)\",.+,(.+)\}"
for line in f:
first, third = re.findall(pattern, line.strip())[0]
print first.strip(), "=>", third.strip()
prints
SubtitleSettings_REPOSITORY => (int32_t)REPOSITORY
PREFERRED_SUBTITLE_LANGUAGE => SUBTITLE_LANGUAGE
where `input.txt` contains
{ "SubtitleSettings_REPOSITORY", FieldType_STRING, (int32_t)REPOSITORY},
{ "PREFERRED_SUBTITLE_LANGUAGE", FieldType_STRING,SUBTITLE_LANGUAGE}
**Breakdown:**
* `\{ \"(.+)\"` matches strings with the structure **{ + space + " + text + "** and extracts **text**
* `,.+,(.+)\}` matches strings with the structure **, + text1 + , + text2 + }** and extracts **text2**
|
Python convert date string to datetime
Question: Im trying to convert a date string into Python but get errors -
String: `'1986-09-22T00:00:00'`
dob_python = datetime.strptime('1986-09-22T00:00:00' , '%Y-%m-%d%Z%H-%M-%S').date()
Error:-
ValueError: time data '1986-09-22T00:00:00' does not match format '%Y-%m-%d%Z%H-%M-%S'
Answer: `T` is not a timezone. It is _just_ a separator. Don't use `%Z` to try and
parse it, use a literal `T`. Your time separators must match as well; you need
to look for `:` colons, not dashes:
dob_python = datetime.strptime('1986-09-22T00:00:00', '%Y-%m-%dT%H:%M:%S').date()
# ^ ^ ^
Demo:
>>> from datetime import datetime
>>> datetime.strptime('1986-09-22T00:00:00', '%Y-%m-%dT%H:%M:%S').date()
datetime.date(1986, 9, 22)
|
Find the max sum for each line and find max list and line number of maximum list count in python
Question:
"[1.0, 0.5]","[0.5, 0.5, 0.5]","[0.5, 0.5]"
"[1.0, 0.0]","[0.5, 0.5, 0.5]","[0.0, 0.0]"
"[0.0, 0.0]","[0.0, 0.0, 0.0]","[0.0, 0.0]"
"[0.0, 0.0]","[1.0, 1.0, 1.0]","[0.0, 0.0]"
"[0.0, 0.0]","[0.5, 0.5, 0.5]","[1.0, 1.0]"
"[0.0, 0.0]","[0.0, 0.0, 1.0]","[0.5, 0.5]"
"[1.0, 0.5]","[0.5, 0.5, 0.5]","[0.5, 0.5]"
"[1.0, 0.0]","[0.5, 0.5, 0.5]","[0.0, 0.0]"
"[0.0, 0.0]","[0.0, 0.0, 0.0]","[0.0, 0.0]"
"[0.0, 0.0]","[1.0, 1.0, 1.0]","[0.0, 0.0]"
"[0.0, 0.0]","[0.5, 0.5, 0.5]","[1.0, 1.0]"
"[0.0, 0.0]","[0.0, 0.0, 1.0]","[0.5, 0.5]"
I have list of diagonals now i want to find the sum for each list in each
line. Output should be like this
1.5
1.5
0
3
1.5
1
How can i do this?
Answer:
from ast import literal_eval
with open("in.csv") as f:
for ind, line in enumerate(f, 1):
if line.strip(): # catch empty lines
print(ind,max(sum(literal_eval(sub.strip('"'))) for sub in line.rstrip().split('",')))
Output:
(1, 1.5)
(2, 1.5)
(3, 0.0)
(4, 3.0)
(5, 2.0)
(6, 1.0)
Using the csv module makes life easier as it does the splitting correctly for
us:
import csv
from ast import literal_eval
with open("in.csv") as f:
reader = csv.reader(f)
for ind, row in enumerate(reader,1):
if row: # only needed if you have empty rows
print(ind, max(sum(literal_eval(sub)) for sub in row))
Output:
(1, 1.5)
(2, 1.5)
(3, 0.0)
(4, 3.0)
(5, 2.0)
(6, 1.0)
[ast.literal_eval](https://docs.python.org/2/library/ast.html#ast.literal_eval)
> Safely evaluate an expression node or a Unicode or Latin-1 encoded string
> containing a Python literal or container display. The string or node
> provided may only consist of the following Python literal structures:
> strings, numbers, tuples, lists, dicts, booleans, and None.
>
> This can be used for safely evaluating strings containing Python values from
> untrusted sources without the need to parse the values oneself. It is not
> capable of evaluating arbitrarily complex expressions, for example involving
> operators or indexing.
Considering you have a csv file then it is a no brainer which option to use.
If you want the max of all the lines, we can use a generator expression to get
the max from each line then use operator.itemgetter to get the max based on
the second element of our tuple which is the max:
import csv
from ast import literal_eval
from operator import itemgetter
with open("in.csv") as f:
reader = csv.reader(f)
totals = ((ind, max(sum(literal_eval(sub))for sub in row))
for ind, row in enumerate(reader, 1) if row)
print(max(totals,key=itemgetter(1)))
Output:
(4, 3.0) # line 4
|
reserved keyword is used in protobuf in Python
Question: In general, I have a protobuf definition which used a Python keyword "from".
It works in Java/C#/C++, but when comes to Python, I could not assign value to
it.
Here is the detail of my problem.
I have a protobuf definition like below:
message Foo
{
required int64 from = 10
...
}
Since the field "from" is a keyword in Python, after I generated the python
code, I could not compile the code as below:
foo = Foo()
foo.from = 1234
Then, I tried to use setattr() to set the attribute:
setattr(foo, 'from', 1234)
That gives me a Protobuf exception:
AttributeError: Assignment not allowed to composite field "from" in protocol message object.
I could not change the definition at this moment because it has been used
widely in the system. Any help would be appreciated if I can workaround to use
the "from" attribute in Python.
Below is the ProtoBuf generated code:
import sys
_FOO = _descriptor.Descriptor(
name='Foo',
full_name='com.kerneljoy.Foo',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='from', full_name='com.kerneljoy.Foo.from', index=0,
number=10, type=3, cpp_type=2, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
oneofs=[
],
serialized_start=28,
serialized_end=47,
)
DESCRIPTOR.message_types_by_name['Foo'] = _FOO
Foo = _reflection.GeneratedProtocolMessageType('Foo', (_message.Message,), dict(
DESCRIPTOR = _FOO,
__module__ = 'Foo_pb2'
# @@protoc_insertion_point(class_scope:com.kerneljoy.Foo)
))
_sym_db.RegisterMessage(Foo)
Answer: After couple attempts, I found the setattr() and getattr() can workaround
this. Because in my production code, the 'from' refers to another protobuff
definition. So the solution here is as below:
foo = Foo()
object = getattr(foo, 'from')
object.bar = 'value'
object.bar2 = 'value2'
|
subproccess.call through python cgi script raspberry pi
Question: So I have a Raspberry Pi that I have set up to be an Access Point with hostapd
and isc-dhcp-server. It broadcasts an SSID, I connect to it with my phone or
laptop, go to 192.168.42.1 and it serves up a page where I have a form for
SSID, PSK, and Device ID. The idea is that it should then connect to the
network with the information that I have given it by invoking a bunch of
subproccess calls, as it is, it doesn't.
This is the index.html:
<html>
<body>
<form enctype="multipart/form-data" action="/cgi-bin/set_wifi.py" method="POST">
ssid: <input type="text" size="70" name="ssid" value=""><br>
pass: <input type="text" size="70" name="pass" value=""><br>
devid: <input type="text" size="70" name="devid" value=""><br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>
The content of start_wifi.py is as follows:
#!/usr/bin/python
import cgi
import cgitb
import subprocess
cgitb.enable()
print "Content-type: text/html\n\n"
form=cgi.FieldStorage()
ssid_val=form['ssid'].value
pass_val=form['pass'].value
devid=form['devid'].value
#Write Device ID to devid.text
myfile= open("/home/pi/project/devid.txt","w")
myfile.write(form['devid'].value)
myfile.close()
#Write SSID and PSK to wpa_supplicant.conf
file = open('/etc/wpa_supplicant/wpa_supplicant.conf','a')
file.write('\n\nnetwork={\n ssid="')
file.write(ssid_val)
file.write('"\n psk="')
file.write(pass_val)
file.write('"\n}')
file.close()
subprocess.call("sudo service hostapd stop", shell=True)
subprocess.call("sudo service isc-dhcp-server stop",shell=True)
subprocess.call("sudo ifdown wlan0",shell=True)
subprocess.call("sudo /etc/init.d/networking stop",shell=True)
subprocess.call("cp /etc/network/interfaces-manual /etc/network/interfaces",shell=True)
subprocess.call("sudo /etc/init.d/networking start",shell=True)
subprocess.call("sudo ifup wlan0",shell=True)
I have another python script called stopapd.py which is essentially everything
after file.close() in the set_wifi.py script above. When I run it through the
terminal it works fine. Stops networking, rewrites interfaces, restarts
networking and re-establishes wlan0 if the network is already saved in
wpa_supplicant.conf
The problem is that when set_wifi.py executes via cgi, the first half of the
script works, it writes to devid.txt and wpa_supplicant.conf, but the only
subproccess.call that I think is working correctly is the
cp /etc/network/interfaces-manual /etc/network/interfaces
which changes the interfaces file from static to dhcp...
None of the other commands seem to run...but when I run the same code as
stopapd.py from the terminal it works...I don't know why...any help would be
greatly appreciated.
Answer: This was driving me nuts but I kept working on it and here's what I came up
with...
In set_wifi.py, I commented out everything after file.close() and added
file=open('/home/pi/project/set_wifi_ran.txt','w')
file.write('set_wifi_ran')
file.close()
Then I have another script running all the time called stopapd.py...it
monitors set_wifi_ran.txt, and if it ever changes it executes the
subprocess.calls...which solves all my problems
while True:
file=open('/home/pi/project/set_wifi_ran.txt')
length=(file.readline())
file.close()
if length>0
file=open('/home/pi/project/set_wifi_ran.txt','w')
file.close()
subprocess.call("sudo service hostapd stop", shell=True)
subprocess.call("sudo service isc-dhcp-server stop",shell=True)
subprocess.call("sudo ifdown wlan0",shell=True)
subprocess.call("sudo /etc/init.d/networking stop",shell=True)
subprocess.call("cp /etc/network/interfaces-manual /etc/network/interfaces",shell=True)
subprocess.call("sudo /etc/init.d/networking start",shell=True)
subprocess.call("sudo ifup wlan0",shell=True)
I'm sure this is not a very elegant way to do this...I'd appreciate any
feedback and I'd still love to know why this doesn't work through the cgi
script
|
ImportError: No module named tweepy - In python
Question: i am trying to do a Sentiment analysis using AWS as explained in the following
section <http://docs.aws.amazon.com/gettingstarted/latest/emr/getting-started-
emr-sentiment-tutorial.html>
Everything went fine until I encountered the following error
[ec2-user@ip-10-65-140-113 sentiment]$ ls enter code herecollector.py
twaiter.py twaiter.pyc twitterparams.py
[ec2-user@ip-10-65-140-113 sentiment]$ **collector.py kindle**
-bash: collector.py: command not found
[ec2-user@ip-10-65-140-113 sentiment]$ python collector.py kindle
Traceback (most recent call last):
File "collector.py", line 6, in <module>
from twaiter import TWaiter
File "/home/ec2-user/sentiment/twaiter.py", line 5, in <module>
from tweepy import StreamListener
**ImportError: No module named tweepy**
Any help as to why this could be. twaiter.py has the following content. I
opened the twaiter.py to see line no 5 and is here
[ec2-user@ip-10-65-140-113 sentiment]$ vi twaiter.py
1 # based on http://badhessian.org/2012/10/collecting-real-time-twitter-data-w ith-the-streaming-api/
2 # with modifications by http://github.com/marciw
3 # requires Tweepy https://github.com/tweepy/tweepy
4
5 from tweepy import StreamListener
6 import json, time, sys
7
8 class TWaiter(StreamListener):
9
10 # see Tweepy for more info
11
12 def __init__(self, api = None, label = 'default_collection'):
13 self.api = api or API()
14 self.counter = 0
15 self.label = label
16 self.output = open(label + '.' + time.strftime('%b%d-%H%M') + '.txt ', 'w')
17 self.deleted = open('deleted_tweets.txt', 'a')
18
19 def on_data(self, data):
20 # The presence of 'in_reply_to_status' indicates a "normal" tweet.
@
Answer: The message "ImportError: No module named tweepy" clearly shows that the ec2
machine does not have tweepy library installed. So while running the current
python script, it is not able to locate it and therefore giving import error.
There are several ways to install tweepy. One simple way in Linux machine is
**sudo pip install tweepy**
Other ways are:
<http://code.google.com/p/tweepy/>
You can get to a tutorial wiki page for it at the same Google Code link.
To install it with easy_install, just run easy_install tweepy
To install it with git:
git clone git://github.com/joshthecoder/tweepy.git
cd tweepy
python setup.py install
To install it from source, download the source from
<http://pypi.python.org/pypi/tweepy> then run something like:
tar xzvf tweepy-1.7.1.tar.gz
cd tweepy-1.7.1
python setup.py install
Please refer [Where and how can I install twitter's Python
API?](http://stackoverflow.com/questions/5957495/where-and-how-can-i-install-
twitters-python-api) for further details.
Also, if further error comes refer [ImportError: No module named
tweepy](http://stackoverflow.com/questions/27451316/importerror-no-module-
named-tweepy)
|
Generating random sample with random.random in python
Question: I'd like to generate a sample size of 100 random numbers between 0 and 1 using
the random.random function.
import random
sample = [random.random for x in range(100)]
For instance, `while print(len(sample))` gives me 100, `print(sample[1])`
returns just a reference to the random object() instead of the actual random
number, which is what I want.
Why is this not working for me?
Probably basic, but I couldn't find an answer.
Answer: You are not calling the method:
[random.random() for x in range(100)]
^^
|
Python Increment Int variable in a String
Question: I can't seem to make a variable that prints out a line of text and next to it
a variable containing an integer that increments each time the for loop is
executed. This is my code:
id = 1
for x in range(0, 4):
studentID = 'Bart: ' + `id`
print(studentID)
id += 1
The loop executes four times but it just prints out
Bart: 1
Bart: 1
Bart: 1
Bart: 1
for four times it doesn't increment the `id` integer
Answer: Try this:
id = 1
for x in range(1, 4):
studentID = "Bart: {}".format(id)
print(studentID)
id += 1
But, why are you incrementing id inside a for loop? Why not just use the for
loop?
Edit: Also, you can use `print("Bart: ", id)`. And, if you want them all on
the same line as you show, you can use either of these:
print("Bart: ", id, end="")
or
sys.stdout.write("Bart: ")
sys.stdout.write(str(id))
sys.stdout.write(" ")
You will need `import sys` at the top of your file.
These are Python 3+ solutions.
|
Python string patterns
Question: I have some input: `'123Joe's amazing login'`
What I'm looking to do with that input is remind the user that is registering
to the site that he needs to make his username url friendly
So server side I would like to have some string match or comparison to see if
it is indeed url friendly, and if it is okay we are golden, if not I would
like to urlfy it and send it back to the user saying something like: "Hey this
name: 123joes-amazing-login is better"
I'm not too sure where to start looking, any suggestions?
edit:
other io could be: "this is awesome" to "this_is_awesome" etc... just need to
make sure it's url friendly!
edit 2: I wound up using this:
username = str(request.form['username'])
username = urllib.quote(username, '')
if '%' in username:
This covers the scope of the handling i.e. users can still underscore and
dash.
Thanks for all the help.
Answer: First `pip install python-slugify`, then
>>> import slugify
>>> username = "123Joe's amazing login"
>>> slugify.slugify(username)
'123joes-amazing-login'
You can check if the given username is equal to the slugified version, and
then do your warning logic if they are unequal.
Now, I want to suggest to you that this is a questionable design choice. There
is no good reason why usernames shouldn't be allowed to contain spaces and
quotes. If you need them to translate into unique urls it's usually better to
tackle that problem by generating a user ID aswell as the username. This can
be done in such a way that it looks like a slugified version of the username,
by the way (although you have to be careful about uniqueness).
|
Using Tor and Meteor DDP
Question: I am trying to use the a [meteor ddp
client](https://github.com/hharnisc/python-meteor) to use the data from a
meteor app in my python script. IT is a script that uses the Tor proxy API
called stem. This is how my tor communicator looks like which works if ran
separately:
Tor communicator (taken from the tor tutorial page with minor alterations):
import socket
import socks
import stem.process
import requests
from stem.util import term
from requestData import requestData
SOCKS_PORT = 7000
# Set socks proxy and wrap the urllib module
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', SOCKS_PORT)
socket.socket = socks.socksocket
# Perform DNS resolution through the socket
def getaddrinfo(*args):
return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
socket.getaddrinfo = getaddrinfo
def query(itemId):
"""
Uses requests to fetch a site using SocksiPy for Tor over the SOCKS_PORT.
"""
try:
return requestData(itemId)
except:
return "Unable to get data"
# Start an instance of Tor configured to only exit through Russia. This prints
# Tor's bootstrap information as it starts. Note that this likely will not
# work if you have another Tor instance running.
def print_bootstrap_lines(line):
if "Bootstrapped " in line:
print(line)
print(term.format("Starting Tor:\n", term.Attr.BOLD))
tor_process = stem.process.launch_tor_with_config(
config = {
'SocksPort': str(SOCKS_PORT),
'ExitNodes': '{ru}',
},
init_msg_handler = print_bootstrap_lines,
)
tor_process.kill() # stops tor
The above script is being ran from this script:
import Communicator
from MeteorClient import MeteorClient
client = MeteorClient('ws://127.0.0.1:3000/websocket')
client.connect()
def subscription_callback(error):
if error:
print(error)
client.subscribe('accounts', callback=subscription_callback)
all_posts = client.find('accounts')
print(all_posts)
Communicator.query("190aqe41vbewh7367f2hf27521")
But it is then giving me this result:
[1mStarting Tor:
[0m
May 10 13:21:45.000 [notice] Bootstrapped 0%: Starting
May 10 13:21:45.000 [notice] Bootstrapped 80%: Connecting to the Tor network
May 10 13:21:46.000 [notice] Bootstrapped 85%: Finishing handshake with first hop
May 10 13:21:46.000 [notice] Bootstrapped 90%: Establishing a Tor circuit
May 10 13:21:47.000 [notice] Bootstrapped 100%: Done
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\socks.py", line 663, in connect
_BaseSocket.connect(self, proxy_addr)
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\gatsu\My Documents\LiClipse Workspace\TorCommunicator\MeteorDDP.py", line 5, in <module>
client.connect()
File "C:\Python34\lib\site-packages\python_meteor-0.1.6-py3.4.egg\MeteorClient.py", line 55, in connect
File "C:\Python34\lib\site-packages\python_ddp-0.1.5-py3.4.egg\DDPClient.py", line 119, in connect
File "C:\Python34\lib\site-packages\ws4py-0.3.4-py3.4.egg\ws4py\client\__init__.py", line 209, in connect
File "C:\Python34\lib\site-packages\socks.py", line 674, in connect
raise ProxyConnectionError(msg, error)
socks.ProxyConnectionError: Error connecting to SOCKS5 proxy 127.0.0.1:7000: [WinError 10061] No connection could be made because the target machine actively refused it
Answer: I solved this by importing the Communicator after I had done my Meteor stuff,
right before I call a method in the Communicator.
from MeteorClient import MeteorClient
client = MeteorClient('ws://127.0.0.1:3000/websocket')
client.connect()
def subscription_callback(error):
if error:
print(error)
client.subscribe('accounts', callback=subscription_callback)
all_posts = client.find('accounts')
print(all_posts)
import Communicator
Communicator.query("190aqe41vbewh7367f2hf27521")
|
Create DDE server in python and send data continuously
Question: I am trying to write a DDE server in python which needs to send a continuously
changing string to a program which is connected as a DDE client.
The program which connects to a DDE server uses the following DDE settings to
connect [Service: Orbitron, Topic: Tracking, Item: Tracking]. The program has
to receive information that is sent by the DDE server in the following string
format: "UP0 DN145000001 UMusb DMfm AZ040 EL005 SNNO SATELLITE".
The content of this string changes approximately every second and I want the
DDE server to send the new string to the connected DDE client, for example
every second.
I am currently using the code below, which is a slightly modified version of
the original _ddeserver.py_ file, [see
here](https://code.google.com/p/pythonxy/source/browse/src/python/pywin32/PLATLIB/win32/Demos/dde/ddeserver.py?repo=xy-27).
import win32ui
from pywin.mfc import object
import dde
class MySystemTopic(object.Object):
def __init__(self):
object.Object.__init__(self, dde.CreateServerSystemTopic())
def Exec(self, cmd):
print "System Topic asked to exec", cmd
class MyOtherTopic(object.Object):
def __init__(self, topicName):
object.Object.__init__(self, dde.CreateTopic(topicName))
def Exec(self, cmd):
print "Other Topic asked to exec", cmd
class MyRequestTopic(object.Object):
def __init__(self, topicName):
topic = dde.CreateTopic(topicName)
topic.AddItem(dde.CreateStringItem(""))
object.Object.__init__(self, topic)
def Request(self, aString):
print "Request Topic sent: ", aString
a="UP0 DN145800001 UMusb DMfm AZ040 EL005 SNNO SATELLITE"
print a
return(a)
server = dde.CreateServer()
server.AddTopic(MyRequestTopic("Tracking"))
server.Create('Orbitron')
while 1:
win32ui.PumpWaitingMessages(0, -1)
When I run the code I can successfully connect with the program and the string
(as provided in the code) is received one time. I tried a few different things
but I can not think of a way yet how to change to python code in order to have
the DDE server continuously resend the string in a loop or similar.
Any suggestions would be very welcome.
P.S. I am relatively new to python, DDE and this forum, my apologies if
something is unclear. Just let me know.
Answer:
# coded by JayleoPlayGround
# use Portable Python 2.7.5.1 + pywin32-214
import time
import win32ui, dde
from pywin.mfc import object
class DDETopic(object.Object):
def __init__(self, topicName):
self.topic = dde.CreateTopic(topicName)
object.Object.__init__(self, self.topic)
self.items = {}
def setData(self, itemName, value):
try:
self.items[itemName].SetData( str(value) )
except KeyError:
if itemName not in self.items:
self.items[itemName] = dde.CreateStringItem(itemName)
self.topic.AddItem( self.items[itemName] )
self.items[itemName].SetData( str(value) )
ddeServer = dde.CreateServer()
ddeServer.Create('Orbitron')
ddeTopic = DDETopic('Tracking')
ddeServer.AddTopic(ddeTopic)
while True:
yourData = time.ctime() + ' UP0 DN145000001 UMusb DMfm AZ040 EL005 SNNO SATELLITE'
ddeTopic.setData('Tracking', yourData)
win32ui.PumpWaitingMessages(0, -1)
time.sleep(0.1)
|
Get all scope names on Sublime Text 3
Question: I am creating a plugin for [ST3](http://www.sublimetext.com/) and need the
list of all defined scopes. I know that hitting `ctrl+alt+shift+p` shows the
current scope in the status bar but I can't do it for every file extension.
## Edit:
In addition to simple `.tmLanguage` files I am extracting the `.sublime-
package` files and reading `.tmLanguage` files from inside. This added some
entries like `source.php` to the list. But `source.python` is still missing !
Actually, the python code is: ( this is for Python 3.3 )
import sublime, sublime_plugin, os, subprocess, glob, tempfile, plistlib
from zipfile import ZipFile
def scopes_inside(d):
result = []
for k in d.keys():
if k == 'scopeName':
result = result + [ s.strip() for s in d[k].split(',') ]
elif isinstance(d[k], dict):
result = result + scopes_inside(d[k])
return result
scopes = set()
for x in os.walk(sublime.packages_path() + '/..'):
for f in glob.glob(os.path.join(x[0], '*.tmLanguage')):
for s in scopes_inside(plistlib.readPlist(f)):
scopes.add(s.strip())
for x in os.walk(sublime.packages_path() + '/..'):
for f in glob.glob(os.path.join(x[0], '*.sublime-package')):
input_zip = ZipFile(f)
for name in input_zip.namelist():
if name.endswith('.tmLanguage'):
for s in self.get_scopes_from(plistlib.readPlistFromBytes(input_zip.read(name))):
scopes.add(s.strip())
scopes = list(scopes)
And it gives this list now:
"font",
"license",
"source.c++",
"source.cmake",
"source.coffee",
"source.css",
"source.d",
"source.disasm",
"source.dockerfile",
"source.gdb.session",
"source.gdbregs",
"source.git",
"source.gradle",
"source.groovy",
"source.gruntfile.coffee",
"source.gruntfile.js",
"source.gulpfile.coffee",
"source.gulpfile.js",
"source.ini",
"source.ini.editorconfig",
"source.jade",
"source.jl",
"source.js",
"source.json",
"source.json.bower",
"source.json.npm",
"source.jsx",
"source.less",
"source.php",
"source.procfile",
"source.puppet",
"source.pyjade",
"source.qml",
"source.rust",
"source.sass",
"source.scss",
"source.shell",
"source.stylus",
"source.swift",
"source.yaml",
"source.zen.5a454e6772616d6d6172",
"text.html.basic",
"text.html.mustache",
"text.html.ruby",
"text.html.twig",
"text.slim",
"text.todo"
But I can't find some languages like `python` in this list. I guess other are
stored within some binary files somewhere within the installation folder. If
that's true so how the parse thoses files ?
Answer: I just found the remaining packages wich are stored within the installation
directory. So the final code which gives all scope names is:
import sublime, sublime_plugin, os, subprocess, glob, tempfile, plistlib
from zipfile import ZipFile
# This function gives array of scope names from the plist dictionary passed as argument
def scopes_inside(d):
result = []
for k in d.keys():
if k == 'scopeName':
result = result + [ s.strip() for s in d[k].split(',') ]
elif isinstance(d[k], dict):
result = result + scopes_inside(d[k])
return result
# Using set to have unique values
scopes = set()
# Parsing all .tmLanguage files from the Packages directory
for x in os.walk(sublime.packages_path()):
for f in glob.glob(os.path.join(x[0], '*.tmLanguage')):
for s in scopes_inside(plistlib.readPlist(f)):
scopes.add(s.strip())
# Parsing all .tmLanguage files inside .sublime-package files from the Installed Packages directory
for x in os.walk(sublime.installed_packages_path()):
for f in glob.glob(os.path.join(x[0], '*.sublime-package')):
input_zip = ZipFile(f)
for name in input_zip.namelist():
if name.endswith('.tmLanguage'):
for s in self.get_scopes_from(plistlib.readPlistFromBytes(input_zip.read(name))):
scopes.add(s.strip())
# Parsing all .tmLanguage files inside .sublime-package files from the Installation directory
for x in os.walk(os.path.dirname(sublime.executable_path())):
for f in glob.glob(os.path.join(x[0], '*.sublime-package')):
input_zip = ZipFile(f)
for name in input_zip.namelist():
if name.endswith('.tmLanguage'):
for s in self.get_scopes_from(plistlib.readPlistFromBytes(input_zip.read(name))):
scopes.add(s.strip())
scopes = list(scopes)
This code may give different results depending on Packages installed (some
packages add new syntax/scope names). In my case, the result was :
font
license
source.actionscript.2
source.applescript
source.asp
source.c
source.c++
source.camlp4.ocaml
source.clojure
source.cmake
source.coffee
source.cs
source.css
source.d
source.diff
source.disasm
source.dockerfile
source.dosbatch
source.dot
source.erlang
source.gdb.session
source.gdbregs
source.git
source.go
source.gradle
source.groovy
source.gruntfile.coffee
source.gruntfile.js
source.gulpfile.coffee
source.gulpfile.js
source.haskell
source.ini
source.ini.editorconfig
source.jade
source.java
source.java-props
source.jl
source.js
source.js.rails
source.json
source.json.bower
source.json.npm
source.jsx
source.less
source.lisp
source.lua
source.makefile
source.matlab
source.nant-build
source.objc
source.objc++
source.ocaml
source.ocamllex
source.ocamlyacc
source.pascal
source.perl
source.php
source.procfile
source.puppet
source.pyjade
source.python
source.qml
source.r
source.r-console
source.regexp
source.regexp.python
source.ruby
source.ruby.rails
source.rust
source.sass
source.scala
source.scss
source.shell
source.sql
source.sql.ruby
source.stylus
source.swift
source.tcl
source.yaml
source.zen.5a454e6772616d6d6172
text.bibtex
text.haml
text.html.asp
text.html.basic
text.html.erlang.yaws
text.html.javadoc
text.html.jsp
text.html.markdown
text.html.markdown.multimarkdown
text.html.mustache
text.html.ruby
text.html.tcl
text.html.textile
text.html.twig
text.log.latex
text.plain
text.restructuredtext
text.slim
text.tex
text.tex.latex
text.tex.latex.beamer
text.tex.latex.haskell
text.tex.latex.memoir
text.tex.latex.rd
text.tex.math
text.todo
text.xml
text.xml.xsl
|
Python Regular expression potential match
Question: I'm using the re module to validate IP address, this is my pattern:
`"^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$"`
Is there a way to know if a string **_can become_** a potential match without
chaniging the pattern? for example: `"127.0.0."` is good or `"10.0"` however
`"10.."` is not good. I don't mean the `re.match` function, I want to know if
a string is not a match but it could be.
I need a function that will do something like this:
import re
p = re.potential("10.0","^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
print p # True
**Edit:** the thing is I want to know if I can recognize a potential match and
use it to limit the wx.TextCtrl with the wx.EVT_CHAR Event, I didn't ask about
my pattern. right now I have implemented it like this:
def OnChar(self,event):
"""event validation of ip"""
key = event.GetKeyCode()
text_value = event.GetEventObject().GetValue()
length = len(text_value)
numbers = True
point = True
if length:
if length>2 and '.' not in text_value[-1:-4:-1]:
numbers = False
elif text_value[-1] =='.':
point=False
if Keys.is_numeric(key) and numbers:
event.Skip()
if Keys.equal(key,'.') and point:
event.Skip()
if Keys.is_moves(key):
event.Skip()
This way the text the user enters can't be something not good, but is there a
way to do it with the re module?
Answer: If I understand you correctly, you want an expression that matches when
something can _become_ an IP address, in a way. Just make parts optional:
^(?:\d{1,3}(?:\.\d{1,3}){0,2}(?:\.\d{0,3})?)?$
[Demo](https://regex101.com/r/yM2kJ0/1): This matches `12`, `234.54`,
`23.53.12.5` and the empty string, but not `34.34..4` or `3546.34`.
**edit:** Less nested, thanks to Casimir et Hippolyte.
|
How to write a recursion function for all the possible parameter combinations in python
Question: I am trying to write a piece of code to traverse all the possible parameter
combinations for a algorithm with python.
import numpy as np
parameter={'alpha1':np.linspace(0.3,0.4,10),'alpha2':np.linspace(0.9,2,100),...'alpha5':np.linspace(5,10,100)}
the problem is that I just couldn't write 5-nested for loop.Can anyone give a
demo on how to write a recursion function to give a list of all possible
combinations of the parameters? Thanks
Answer: You could use the `itertools.product` function, which takes a list of
iterators and creates the iterator of their cartesian product (see
[documentation](https://docs.python.org/2/library/itertools.html#itertools.product)).
In my solution I use the values from the `parameter` dictionary as the
iterators. I go over the product of the options for each key (`for
values_option in product(*parameter.values())`) and create a new dictionary
with the original keys)
from itertools import product
import numpy as np
parameter={'alpha1':np.linspace(0.3,0.4,10),'alpha2':np.linspace(0.9,2,100)}
def parameter_options(parameter):
for values_option in product(*parameter.values()):
yield dict(zip(parameter.keys(), values_option))
for opt in parameter_options(parameter):
print opt
* * *
Let's go over this piece by piece:
**`parameter.values()`**
This gives a list of the values for each key-value in the dictionary.
For example, if we have `dictionary = {a: (1, 2, 3), b: (4, 5, 6)}`, using
`dictionary.values()` will return `[(1, 2, 3), (4, 5, 6)]`. Doing
`dictionary.keys()` will give `['a', 'b']`.
_Note_ : There's a difference here between Python 2 and Python 3 - in Python 2
these methods (`keys()` and `values()`) will return normal lists, whereas in
Python 3 they return a special iterator. This shouldn't change the solution.
**`product(*parameter.values())`**
We use the asterisk to "unpack" lists. Simply put, `itertools.product`
receives any number of arguments. We want to use all the `values` as input:
vals = parameter.values()
product(vals[0], vals[1], vals[2], ..., vals[len(vals)])
Python has an easy way to pass lists as input to functions that receive an
arbitrary number of arguments. This last line is the same as `product(*vals)`.
**`for values_option in product(*parameter.values()):`**
We go over all the options for the values of the `parameter` dictionary.
The first iteration will give the first option for all arguments. The second
iteration will give the first option for all but one argument, which will have
its second option. This goes on all the way until we have the last option
where each argument has its last option.
**`zip(parameter.keys(), values_option)`**
This takes the two lists (of keys and possible values) and basically
transposes them. it gives a list of the same length which includes pairs: the
first element from the first list and the second from the second list. Like
so:
keys = ['a', 'b', 'c', 'd']
vals = [1, 2, 3, 4]
zip(keys, vals) = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
**`dict(...)`**
Now we can use this zipped list to create a dictionary. This is a different
way to initiate a dict
{'a': 1, 'b': 2, 'c': 3} == dict([('a', 1), ('b', 2), ('c', 3)])
**`yield ...`**
This is what we use in python to create iterators. It's a complicated subject
but instead of this you could write before the `for` loop this line
options = []
and instead of `yield dict(...)` write `options.append(dict(...))`. and in the
end of the function `return options`.
Voila.
|
Incorrect Pandas DataFrame creation using lists
Question: I want to create a data frame using Python's Panda by reading a text file. The
values are tab-separated but when I use this code:
import sys
import pandas as pd
query = sys.argv[1]
df = pd.DataFrame()
with open(query) as file_open:
for line in iter(file_open.readline, ''):
if line.startswith("#CHROM"):
columns = line.split("\t")
if line.startswith("chr7"):
df = df.append(line.split("\t"))
print df
print len(df)
My output is:
...
0 chr7
1 158937585
2 rs3763427
3 T
4 C
5 931.21
6 .
7 AC=2;AF=1.00;AN=2;DP=24;Dels=0.00;FS=0.000;HRu...
8 GT:DP:GQ:PL:A:C:G:T:IR
9 1/1:24:72.24:964,72,0:0,0:11,12:0,0:0,0:0\n
0 chr7
1 158937597
2 .
3 C
4 CG
5 702.73
6 .
7 AC=2;AF=1.00;AN=2;BaseQRankSum=-1.735;DP=19;FS...
8 GT:DP:GQ:PL:A:C:G:T:IR
9 1/1:19:41.93:745,42,0:0,0:10,8:0,0:0,0:17\n
[510350 rows x 1 columns]
510350
The text file contains this format:
#CHROM \t POS \t ID \t REF \t ALT \t QUAL \t FILTER \t INFO \n
chr7 \t 149601 \t tMERGED_DEL_2_39754 \t T \t .\t 141.35 \t . \t AC=0;AF=0.00;AN=2;DP=37;MQ=37.00;MQ0=0;1000gALT=<DEL>;AF1000g=0.09.. \n
chr7 \t 149616 \t rs190051229 \t C \t . \t 108.65 \t . \t AC=0;AF=0.00;AN=2;DP=35;MQ=37.00;MQ0=0;1000gALT=T;AF1000g=0.00.. \n
...
I want the data frame to look like:
#CHROM POS ID REF ALT QUAL FILTER INFO
chr7 149601 MERGED.. T . 141.35 . AC=0;AF=0.00;A..
chr7 149616 rs1900.. C . 108.65 . AC=0;AF=0.00;A..
...
Reading each line with the code above creates a list of the values in that
line:
['chr7','149601','MERGED..','T','.','141.35','.','AC=0;AF=0;A..'\n]
What is wrong about my code?
Thank you.
Rodrigo
Answer: Don’t read the file by hand. Use pandas’ powerful `read_csv`:
df = pd.read_csv(query, sep='\t')
Full program:
import sys
import pandas as pd
query = sys.argv[1]
df = pd.read_csv(query, sep='\t')
print df
|
Creating APK from Kivy on Mac OS X fails after compile
Question: My background is in HTML/JS, so compiling is new for me. While attempting to
build my python project in Kivy to an Android .apk, I am getting an error I do
not understand:
Command failed: ./distribute.sh -m "kivy"
Here is a portion of the tail end of the debug output...
Compiling /Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python-install/lib/python2.7/xmllib.py ...
Compiling /Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python-install/lib/python2.7/xmlrpclib.py ...
Compiling /Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python-install/lib/python2.7/zipfile.py ...
make: [libinstall] Error 1 (ignored)
PYTHONPATH=/Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python-install/lib/python2.7 LD_LIBRARY_PATH=/Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python/Python-2.7.2: \
/Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python/Python-2.7.2/hostpython -Wi -t /Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python-install/lib/python2.7/compileall.py \
-d /Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python-install/lib/python2.7/site-packages -f \
-x badsyntax /Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python-install/lib/python2.7/site-packages
Listing /Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python-install/lib/python2.7/site-packages ...
PYTHONPATH=/Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python-install/lib/python2.7 LD_LIBRARY_PATH=/Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python/Python-2.7.2: \
/Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python/Python-2.7.2/hostpython -Wi -t -O /Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python-install/lib/python2.7/compileall.py \
-d /Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python-install/lib/python2.7/site-packages -f \
-x badsyntax /Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python-install/lib/python2.7/site-packages
Listing /Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python-install/lib/python2.7/site-packages ...
PYTHONPATH=/Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python-install/lib/python2.7 LD_LIBRARY_PATH=/Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python/Python-2.7.2: \
/Users/Travis/buildozer/.buildozer/android/platform/python-for-android/build/python/Python-2.7.2/hostpython -Wi -t -c "import lib2to3.pygram, lib2to3.patcomp;lib2to3.patcomp.PatternCompiler()"
Leaving ARM environment
cp: build/lib.linux-x86_64-2.7/_ctypes*.so: No such file or directory
# Command failed: ./distribute.sh -m "kivy" -d "myapp"
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2
Here is the full debug, for those who want it...
<https://www.dropbox.com/s/45lgdhk5y4uj8eg/KivyDebug.txt?dl=1>
Also, my buildozer.spec file...
<https://www.dropbox.com/s/g5p43jjts49rzza/buildozer.spec?dl=1>
EDIT: Downgrading Cython per the advice
[HERE](http://stackoverflow.com/a/29140927/4096787) did not help. EDIT2: Tried
changing requirements to kivy==master. No luck. EDIT3: Tried chmod -R 777 on
both source and buildozer folders. No luck.
Answer: OK, I came across the answer to my own problem a while ago and I'm posting it
here in case someone else makes the same boneheaded mistake. Basically, I did
not read the instructions carefully enough in [the
documentation](http://kivy.org/docs/guide/packaging-android.html). The
instructions clearly state "**navigate to your project directory** and run:
buildozer init". I did not navigate to the project folder. I was building in
my user directory, hence "/Users/Travis/". Hence the "No such file or
directory" error.
You may be asking "How do you expect buildozer to know where your project is?"
Well, the next step says to configure "buildozer.spec", and in there, there is
a place to put your path to the main.py, which by default is ".", so I changed
that. It actually worked up to the point that it has to write any files.
So, if you're having the same issue as me, you might just need to read more
carefully.
|
how to find number of processes running particular command in python
Question: The output of
ps uaxw | egrep 'kms' | grep -v 'grep'
yields:
user1 8148 0.0 0.0 128988 3916 pts/8 S+ 18:34 0:00 kms
user2 11782 0.7 0.3 653568 56564 pts/14 Sl+ 20:29 0:01 kms
Clearly two processes running the program. I want to store this number (2
here) as a variable. Any suggestions on how to do this in python?
I tried the following:
procs = subprocess.check_output("ps uaxw | egrep 'kmns' |grep -v 'grep'",shell=True)
But i get the following (I think when the jobs are not currently running, so
number of processes running the jobs is zero):
> Traceback (most recent call last): File "", line 1, in File "/usr/lib64/python2.7/subprocess.py", line 573, in check_output raise CalledProcessError(retcode, cmd, output=output) subprocess.CalledProcessError: Command 'ps uaxw | egrep 'kmns' |grep -v 'grep'' returned non-zero exit status 1
How do I get around this?
Btw, here is the function I wrote to detect if my system was busy (which means
if the number of cpus > total installed, and if load avg > 0.9 per cpu):
def busy():
import subprocess
output = subprocess.check_output("uptime", shell=False)
words = output.split()
sys.stderr.write("%s\n"%(output))
procs = subprocess.check_output("ps uaxw | egrep '(kmns)' | grep -v 'grep'", shell=True)
kmns_wrds = procs.split("\n")
wrds=words[9]
ldavg=float(wrds.strip(','))+0.8
sys.stderr.write("%s %s\n"%(ldavg,len(kmns_wrds)))
return max(ldavg, len(kmns_wrds)) > ncpus
The above is called by:
def wait_til_free(myseconds):
while busy():
import time
import sys
time.sleep(myseconds)
""" sys.stderr.write("Waiting %s seconds\n"%(myseconds)) """
which basically tells the system to wait while all cpus are taken.
Any suggestions?
Many thanks!
Answer: If you're going to do this all with a big shell command, just add the `-c`
argument to
[`grep`](http://pubs.opengroup.org/onlinepubs/009604499/utilities/grep.html),
so it gives you a count of lines instead of the actual lines:
$ ps uaxw |grep python |grep -v grep
abarnert 1028 0.0 0.3 2529488 55252 s000 S+ 9:46PM 0:02.80 /Library/Frameworks/Python.framework/Versions/3.4/Resources/Python.app/Contents/MacOS/Python /Library/Frameworks/Python.framework/Versions/3.4/bin/ipython3
abarnert 9639 0.0 0.1 2512928 19228 s002 T 3:06PM 0:00.40 /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python /usr/local/bin/ipython2
$
$ ps uaxw |grep python |grep -c -v grep
2
Of course you could make this more complicated by adding a `| wc -l` to the
end, or by counting the lines in Python, but why?
* * *
Alternatively, why even involve the shell? You can search within Python just
as easily as you can run `grep`—and then you don't have the problem that
you've accidentally created a `grep` process that `ps` will repeat as matching
your search and then need to `grep -v` it back out:
procs = subprocess.check_output(['ps', 'uaxw']).splitlines()
kms_procs = [proc for proc in procs if 'kms' in proc]
count = len(kms_procs)
* * *
Or, even more simply, don't ask `ps` to give you a whole bunch of information
that you don't want and then figure out how to ignore it, just ask for the
information you want:
procs = subprocess.check_output(['ps', '-a', '-c', '-ocomm=']).splitlines()
count = procs.count('kms')
* * *
Or, even more more simplierly, install
[`psutil`](https://pypi.python.org/pypi/psutil) and don't even try to run
subprocesses and parse their output:
count = sum(1 for proc in psutil.process_iter() if proc.name() == 'kms')
|
error on bar chart (Python, Matplotlib)
Question: code for ploting bar chart:
import pylab as pl
data = """35389 6
35316 7
33921 8
1914 5
21 4
3 3
3 2
"""
values = []
dates = []
for line in data.split("\n"):
x, y = line.split()
values.append(int(x))
dates.append(int(y))
fig = pl.figure()
ax = pl.subplot(111)
ax.bar(dates, values, width=100)
ax.xaxis_date()
Give this error :
File "try2.py", line 17, in x, y = line.split() ValueError: need more than 0
values to unpack
How to fix it?
Answer: I have slightly re-written some of your original code namely the string as the
putting `"""` at the bottom like you have it will cause a redundant new
element to be added to the list since you are splitting upon a new line
You have created the plot, but you still have not shown the plot I have fixed
this by adding two additional lines to the bottom of your code. However, even
with this you are going to have one or two more errors and I will leave these
to you to figure out the resolution.
import pylab as pl
data = """35389 6
35316 7
33921 8
1914 5
21 4
3 3
3 2"""
values = []
dates = []
for element in data.split("\n"):
x, y= element.split()
values.append(int(x))
dates.append(int(y))
fig = pl.figure()
ax = pl.subplot(111)
ax.bar(dates, values, width=100)
ax.xaxis_date()
fig.show()
pl.show()
|
Why does re.sub('.*?', '-', 'abc') return '-a-b-c-' instead of '-------'?
Question: This is the results from python2.7.
>>> re.sub('.*?', '-', 'abc')
'-a-b-c-'
The results I thought **should** be as follows.
>>> re.sub('.*?', '-', 'abc')
'-------'
But it's not. Why?
Answer: Are you sure you interpreted
[re.sub](https://docs.python.org/2/library/re.html)'s documentation correctly?
> `*?`, `+?`, `??` The '_', '+', and '?' qualifiers are all greedy; they match
> as much text as possible. Sometimes this behaviour isn’t desired; if the RE
> <._> is matched against `'<H1>title</H1>'`, it will match the entire string,
> and not just `'<H1>'`. Adding '?' after the qualifier makes it perform the
> match in non-greedy or minimal fashion; as few characters as possible will
> be matched. Using .*? in the previous expression will match only ''.
Adding a `?` will turn the expression into a non-greedy one.
**Greedy:**
re.sub(".*", "-", "abc")
**non-Greedy:**
re.sub(".*?", "-", "abc")
**Update:** FWIW `re.sub` does exactly what it should:
>>> from re import sub
>>> sub(".*?", "-", "abc")
'-a-b-c-'
>>> sub(".*", "-", "abc")
'-'
See @BrenBarn's awesome answer on why you get `-a-b-c-` :)
Here's a visual representation of what's going on:
.*?

[Debuggex Demo](https://www.debuggex.com/r/mOJU8zu1w1xkDvdT)
|
Parsing XML Python
Question: I am using `xml.etree.ElementTree` to parse an XML file. I have a problem. I
do not know how to obtain a plain text line between tags.
<Sync time="4.496"/>
<Background time="4.496" type="music" level="high"/>
<Event desc="pause" type="noise" extent="instantaneous"/>
Plain text
<Sync time="7.186"/>
<Event desc="b" type="noise" extent="instantaneous"/>
Plain text
<Sync time="10.949"/>
Plain text
I have this code already:
import xml.etree.ElementTree as etree
import os
data_file = "./file.xml"
xmlD = etree.parse(data_file)
root = xmlD.getroot()
sections = root.getchildren()[2].getchildren()
for section in sections:
turns = section.getchildren()
for turn in turns:
speaker = turn.get('speaker')
mode = turn.get('mode')
childs = turn.getchildren()
for child in childs:
time = child.get('time')
opt = child.get('desc')
if opt == 'es':
opt = "ESP:"
elif opt == "la":
opt = "LATIN:"
elif opt == "*":
opt = "-ININT-"
elif opt == "fs":
opt = "-FS-"
elif opt == "throat":
opt = "-THROAT-"
elif opt == "laugh":
opt = "-LAUGH-"
else:
opt = ""
print speaker, mode, time, opt+child.tail.encode('latin-1')
I can access through the XML until the Sync|Background|Event tag, and can't
extract the text after these tags. I put a piece of the XML file, no the
entire file. I only have problems with the final piece of code
Thank you so much @alecxe . Now I can get the info that I needed. But now I
have a new little problem. I obtain the line typing the `tail` command but a
newline character `\n` is generated before or something similar, so, I need
something like: `spk1 planned LAN: Plain text from tail`>
But I get this:
`spk1 planned LAN: Plain text from tail`
I have tried many things, `re.match()` module, `sed` commands after processing
the XML, but it seems there is no `\n` new line character, but I can't "put
up" the plain text! Thank you in advance
Anyone? Thank you!
Answer: This is called a [`tail` of an
element](https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.tail):
> The tail attribute can be used to hold additional data associated with the
> element. This attribute is usually a string but may be any application-
> specific object. If the element is created from an XML file the attribute
> will contain any **text found after the element’s end tag and before the
> next tag**.
Locate the `Event` tag and get the tail, example:
section.find("Event").tail
|
Calling the mixpanel API never returns a response
Question: When I use the following Python code to call the Mixpanel API, I never get a
response.
import requests
requests.get("https://data.mixpanel.com/")
But when I try in the browser it works fine. (I get the following response:
`{error: "Not Found"}` which is expected.)
Why is this? Or what can I do to locate the problem?
**Edit:**
* After a while I get the following error:
ConnectionError: HTTPSConnectionPool(host='data.mixpanel.com', port=443): Max
retries exceeded with url: / (Caused by : [Errno 54] Connection reset by peer)
* urllib2 also does not return any response.
Answer: OP: Are you harnessing the response struct from requests.get ? What do you get
when you run:
import requests
result = requests.get("https://data.mixpanel.com/")
print result.text
(requests.get returns an object that you can then query ...)
Be sure to see: <http://docs.python-requests.org/en/latest/> for more examples
of how to use the requests library.
|
django stopped working with mod_wsgi/apache
Question: I can't seem to understand why django/apache refuses to load
DJANGO_SETTINGS_MODULE inspite of it being declared! I checked that the
environmental variable is loaded through python, and manage.py can create a
run server without any errors about the settings.
echo $DJANGO_SETTINGS_MODULE >>> harshp.settings.production
Apache error log
AH02282: No slotmem from mod_heartmonitor
AH00489: Apache/2.4.12 (Unix) OpenSSL/1.0.1k mod_wsgi/3.5 Python/2.7.6 configured -- resuming normal operations
AH00094: Command line: '/opt/bitnami/apache2/bin/httpd -f /opt/bitnami/apache2/conf/httpd.conf'
mod_wsgi (pid=7056): Exception occurred processing WSGI script '/opt/bitnami/apps/django/django_projects/harshp.com/harshp/wsgi.py'.
Traceback (most recent call last):
File "/opt/bitnami/python/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 170, in __call__
self.load_middleware()
File "/opt/bitnami/python/lib/python2.7/site-packages/django/core/handlers/base.py", line 49, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:
File "/opt/bitnami/python/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in __getattr__
self._setup(name)
File "/opt/bitnami/python/lib/python2.7/site-packages/django/conf/__init__.py", line 42, in _setup
% (desc, ENVIRONMENT_VARIABLE))
ImproperlyConfigured: Requested setting MIDDLEWARE_CLASSES, but settings are not configured.
You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.~
Apache config
WSGIScriptAlias / /opt/bitnami/apps/django/django_projects/harshp.com/harshp.wsgi
WSGIPythonPath /opt/bitnami/apps/django/django_projects/harshp.com
<Directory /opt/bitnami/apps/django/django_projects/harshp.com/>
Require all granted
</Directory>
wsgi.py
sys.path.append('/opt/bitnami/apps')
sys.path.append('/opt/bitnami/apps/django/django_projects/harshp.com')
*** edit *** SETTINGS was typed as SETTNGS only on SO
os.environ['DJANGO_SETTINGS_MODULE']='harshp.settings.production'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
httpd-app.conf
<IfDefine !IS_DJANGOSTACK_LOADED>
Define IS_DJANGOSTACK_LOADED
WSGIDaemonProcess wsgi-djangostack processes=2 threads=15 display-name=%{GROUP}
</IfDefine>
WSGIScriptAlias / '/opt/bitnami/apps/django/django_projects/harshp.com/harshp/wsgi.py'
<Directory "/opt/bitnami/apps/django/django_projects/harshp.com/harshp/">
WSGIProcessGroup wsgi-djangostack
WSGIApplicationGroup %{GLOBAL}
<IfVersion < 2.3 >
Order allow,deny
Allow from all
</IfVersion>
<IfVersion >= 2.3>
Require all granted
</IfVersion>
</Directory>
Answer: bitnami developer here. I think you have a typo, at least in the code you are
pasting:
os.environ['DJANGO_SETTNGS_MODULE']='harshp.settings.production'
Can you try to change it from SETTNGS to SETTINGS?
|
python 3 IndexError: list index out of range
Question: My problem is that the average value on this won't show up as it returns as an
error
Traceback (most recent call last):
(file location), line 29, in <module>
average_score = [[x[8],x[0]] for x in a_list]
(file location), line 29, in <listcomp>
average_score = [[x[8],x[0]] for x in a_list]
IndexError: list index out of range
the code
import csv
class_a = open('class_a.txt')
csv_a = csv.reader(class_a)
a_list = []
for row in csv_a:
row[3] = int(row[3])
row[4] = int(row[4])
row[5] = int(row[5])
minimum = min(row[3:5])
row.append(minimum)
maximum = max(row[3:5])
row.append(maximum)
average = sum(row[3:5])//3
row.append(average)
a_list.append(row[0:8])
print(row[8])
this clearly works when I test out the values 0 to 7 ,even if I change the
location of the avarage sum I still get the error
Answer: When you call `a_list.append(row[0:8])` you're appending an array using only
indexes 0, 1, 2, 3, 4, 5, 6, and 7 from `row`. This means that when you later
iterate `a_list`, the `x` variable only has indexes up to 7, and you're trying
to access 8.
Quick example:
>>> row = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x = row[:8]
>>> x[8]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> x[7]
7
>>>
|
Access static method from static variable
Question: There are plenty answers for how to access static variables from static
methods (like [this one](http://stackoverflow.com/questions/11233729/access-
static-variable-from-static-method), and [that
one](http://stackoverflow.com/questions/707380/in-python-how-can-i-access-
static-class-variables-within-class-methods), and the great info on the
subject [here](http://stackoverflow.com/questions/68645/static-class-
variables-in-python)), however I'm having trouble with the other direction:
How can you use static methods to initialize static variables. E.g.:
import os, platform
class A(object):
@staticmethod
def getRoot():
return 'C:\\' if platform.system() == 'Windows' else '/'
pth = os.path.join(A.getRoot(), 'some', 'path')
The last line gives an exception: `NameError: name 'A' is not defined`. The
same error happens if I use `@classmethod` instead of `@staticmethod`.
Is it possible to access a static method from a class variable?
Answer: The problem is that the class "A" doesn't exist yet at the moment your
vatiable pth is declared, so the evaluation fails. How about declaring it
right after?
import os, platform
class A(object):
@staticmethod
def getRoot():
return 'C:\\' if platform.system() == 'Windows' else '/'
A.pth = os.path.join(A.getRoot(), 'some', 'path')
An uglier alternative would be:
import os, platform
class A(object):
@staticmethod
def getRoot():
return 'C:\\' if platform.system() == 'Windows' else '/'
pth = os.path.join(getRoot.__func__(), 'some', 'path')
... but it's pretty unreadable (and depends on implementation details of
@staticmethod, which is bad).
For this specific case I'd do something like this (which doesn't really answer
your question, instead it sidesteps the need for it):
import os, platform
class A(object):
_root = 'C:\\' if platform.system() == 'Windows' else '/'
@staticmethod
def getRoot():
return A._root
pth = os.path.join(_root, 'some', 'path')
... because your platform is pretty unlikely to change while your program is
still running, right? :) If you have a better reason to do something like
that, maybe use one of the methods above.
|
Converting time string to TimeField
Question: I have the following field on my `Django` model:
ValidationError: [u"'36.332' value has an invalid format. It must be in
HH:MM[:ss[.uuuuuu]] format."]
from django.db import models
class TestSuite(models.Model):
time = models.TimeField()
when I parse my `.xml` test report files, I have the following field:
'time': u'36.332'
When I try to create the model via a `**kwargs` I'm seeing the following
error:
kwargs = {'time': u'36.332'}
testsuite = TestSuite(**kwargs)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 710, in save
force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 738, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 822, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 861, in _do_insert
using=using, raw=raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 920, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 970, in execute_sql
for sql, params in self.as_sql():
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 928, in as_sql
for obj in self.query.objs
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 710, in get_db_prep_save
prepared=False)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 2293, in get_db_prep_value
value = self.get_prep_value(value)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 2288, in get_prep_value
return self.to_python(value)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 2275, in to_python
params={'value': value},
ValidationError: [u"'36.332' value has an invalid format. It must be in HH:MM[:ss[.uuuuuu]] format."]
How can I convert my string `'time'` to a `TimeField()` object ? *** Note: ***
`'36.332'` means `36.332 seconds`
Answer: The `TimeField` field is not used to save and/or express an amount of time,
like "x seconds", but a time in the day, like saying "X event occurred at
03:00:00"; here, "03:00:00" is the value for `TimeField`. Namely you _might_
see it as the time part of a `datetime.datetime` object.
If what you need to store is an _amount_ of time, you can use any other built-
in field (IntegerField, CharField, etc) that fits your needs and manipulate it
yourself.
Depending on what you need the value for, [django-
timedeltafield](https://pypi.python.org/pypi/django-timedeltafield) or
[DurationField](https://docs.djangoproject.com/en/1.8/ref/models/fields/#durationfield)
may be useful as well. Although `DurationField` is only available in django
1.8 at the moment.
I hope this helps! :)
|
How do I bypass the "Flash Camera and Microphone Access" pop-up when using Pepper/PPAPI Flash in Chrome (via Selenium)?
Question: Chrome supports two flavors of Flash: NPAPI and PPAPI (Pepper). These two
implementations seem to handle camera and microphone permissions differently.
Specifically, PPAPI (Pepper) does not appear to honor any previous grants of
permission.
With NPAPI, which is the default, the first time I navigate to a Flash site
that requests permission to use the computer's camera and microphone, an Adobe
Flash pop-up asks the user to allow or deny access. I allow access, and this
grant is remembered. The next time I navigate to that site, permission is
granted automatically, without the pop-up.
When I want to test with PPAPI (Pepper) Flash, I specify the "--enable-
bundled-ppapi-flash" and "--disable-npapi" command-line arguments to Chrome.
In this mode, the previous grants are ignored, and the pop-up is displayed
every time. I have not figured out how to detect this in Selenium and click on
"Allow".
Does anyone know how to bypass this pop-up, either by clicking on "Allow", or
by disabling it altogether?
Thanks.
**Update:** I have discovered that non-Pepper Flash stores camera/microphone
permissions in a file called 'settings.sol', stored in a directory specific to
the site requesting access. For example, on Windows, when the host at 1.2.3.4
requests access, the following file is created:
C:\Users[user]\AppData\Roaming\Macromedia\Flash
Player\macromedia.com\support\flashplayer\sys#1.2.3.4\settings.sol
Note the space in "Flash Player". This file is a local shared object, encoded
as AMF. I use the Python pyamf package to create a file that grants permanent
access to a site:
from pyamf import sol
permissions = sol.SOL ('1.2.3.4/settings')
permissions[u'always'] = True
permissions[u'allow'] = True
permissions[u'klimit'] = 100
sol.save (permissions, 'my-settings.sol')
When I copy this to the appropriate directory, access is granted
automatically. But again, this does not work for Pepper Flash.
Pepper Flash ignores this directory, and instead gets a new temporary
directory for each instance of Chrome:
C:\Users[user]\AppData\Local\Temp\scoped_dir5976_6686\Default\Pepper
Data\Shockwave Flash\WritableRoot#SharedObje
cts\6DMDJWLP\macromedia.com\support\flashplayer\sys#1.2.3.4\settings.sol
Unfortunately, the directory changes on each invocation. If I could somehow
discover the name of this directory, then I could upload the file before
requesting access.
But I don't know how to discover the name of this directory.
Answer: It turns out that my problem was specific to Selenium, and how I was using
Selenium.
First, back to NPAPI Flash, which stores its permissions on Windows in a
subdirectory under the user directory; for example:
C:\Users[user]\AppData\Roaming\Macromedia\Flash Player\macromedia.com\support\flashplayer\sys
Pepper Flash does not use this directory for its permissions, and thus does
not honor the settings stored there. Instead, it stores its permissions files
in a subdirectory that is underneath the Chrome user's data directory.
When I was creating a Chrome browser instance via Selenium, a temporary user
data directory was created for the session For example:
C:\Users[user]\AppData\Local\Temp\scoped_dir5976_6686
Pepper Flash was storing its permissions files underneath this directory, but
when the browser session ended, this temporary directory was deleted, and the
settings were forgotten.
The solution is simple: when starting Chrome via Selenium, specify the Chrome
user's data directory via a command-line argument:
"user-data-dir=C:\\Users\\[user]\AppData\Local\Google\Chrome\User Data"
Pepper Flash will then store its permissions in this directory, and because it
is a permanent directory that does not get deleted when the browser session
ends, it will be there for the next instance, and thus the permissions granted
will be remembered.
|
Getting "Message: h is null"
Question: I've recently encountered something I've never seen before while using
`selenium`.
The code (quite simple and straightforward):
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.drugs.com/drug-class/laxatives.html?condition_id=&generic=0&sort=rating&order=desc")
print driver.find_element_by_tag_name("title").text
Here is a stack trace of the error I'm getting:
Traceback (most recent call last):
File "/Users/a/p/SO/selenium_scripts/test.py", line 6, in <module>
print driver.find_element_by_tag_name("title").text
File "/Users/a/.virtualenvs/so/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 328, in find_element_by_tag_name
return self.find_element(by=By.TAG_NAME, value=name)
File "/Users/a/.virtualenvs/so/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 664, in find_element
{'using': by, 'value': value})['value']
File "/Users/a/.virtualenvs/so/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 175, in execute
self.error_handler.check_response(response)
File "/Users/a/.virtualenvs/so/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 166, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: h is null
Using Firefox 37.0 and selenium 2.45.0.
* * *
Observations:
* if I switch to `webdriver.Chrome()` \- I don't see any errors
* if I use a different URL, e.g. `https://google.com` \- I don't see any errors
* I've tried to explicitly wait for search results to be visible before making any further actions, but I still get the same error, code I've used:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox()
driver.get("http://www.drugs.com/drug-class/laxatives.html?condition_id=&generic=0&sort=rating&order=desc")
# wait for the table list to load
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "table.data-list")))
* it is not easily googleable which probably means it is web-site specific, but, as noted before, no errors in Chrome
* * *
Where is the error coming from and what can I do to prevent/fix it? Does this
mean I cannot browser/locate elements on this particular web page using
selenium+firefox?
Answer: Looks like `selenium 2.45.0 does not support ff 37`.
The [change
log](http://code.google.com/p/selenium/source/browse/java/CHANGELOG) shows
selenium 2.44 supported FF33. Selenium 2.45 was released around Feb 26th 2015,
while FF37 was released on March 31st 2015.
|
not able to run the first run.py of eve
Question: I'm trying to learn eve to use it to expose a database and I'm starting from
the beginning [eve first step](http://python-eve.org/quickstart.html).
**run.py**
from eve import Eve
app = Eve()
if __name__ == '__main__':
app.run()
**settings.py**
DOMAIN = {'people': {}}
**requirements.txt**
scrapy==0.24.4
eve==0.5
pymongo==3.0.1
**`python run.py`**
eve.io.base.ConnectionException: Error initializing the driver. Make sure the database serveris running. Driver exception: ConfigurationError('Unknown option auto_start_request',)
what's wrong? Why is there a problem with the database although I followed
exactly what is in the `eve` quickstart?
* `virtualenv --version`: 12.0.7
* `pip -V`: 6.1.1
* `python --version : 2.7.6`
* `MongoDB shell version: 2.4.9`
Answer: The error you are getting is because you are running PyMongo 3.0.1 which
breaks backward compatibility in a big way. If you look into [Eve
requirements](https://github.com/nicolaiarocci/eve/blob/develop/setup.py#L17)
you will find that it requires PyMongo 2.8 (actually it's 2.7.x in production;
2.8+ on the development branch).
If you got PyMongo 3.0.1, then I suspect that you installed the requirements
by hand. The ideal way to install Eve (or any other Python library really) is
to pip install from PYPI, even better if in a virtualenv; see
[installation](http://python-eve.org/install.html) page.
For the record, a PyMongo 3.0.1 compatibile branch is ready on GitHub, but it
is currently relying on a Flask-PyMongo fork since the current Flask-PyMongo
release is not compatible with PyMongo 3+. Also, if you want to run MongoDB
3.0 with Eve you can do that. PyMongo 2.8 is fully compatibile with MongoDB
3.0.
|
Can't import ggplot module in iPython
Question: I'm trying to use ggplot in an Anaconda iPython notebook. I ran `%matplotlib
inline` and `from ggplot import *`, but I just get the following error:
ImportError Traceback (most recent call last)
<ipython-input-3-02aeb6e281ab> in <module>()
----> 1 from ggplot import *
ImportError: No module named ggplot
Where in the Anaconda launcher can modules be imported?
Answer: You probably need to install ggplot via the terminal first. Assuming you
already have pip installed, run this in the terminal:`$ pip install ggplot`
You should see the package download. Then go back to your notebook and run
your same commands again.
|
receiving packets from a socket in scapy
Question: I am trying to code a basic packet sniffer by listening to a socket in python
and found that we could use the socket library in python and do the following,
s = socket.socket( socket.AF_PACKET , socket.SOCK_RAW , socket.ntohs(0x0005))
Wanted to know whether if we would do the same in scapy?
Answer: From the [Scapy
Documentnat](http://www.secdev.org/projects/scapy/doc/usage.html#sniffing):
from scapy.all import sniff
data = sniff(filter="icmp and host 127.0.0.1", count=2)
print data.summary()
|
django.core.exceptions.ImproperlyConfigured about setting TEMPLATES
Question: a question about django.template
here is code:
from django import template
t = template.Template('My name is {{ name }}.')
but when i ran:
Traceback (most recent call last):
File "F:/daima/QPython/123.py", line 2, in <module>
t = template.Template('my name is {{ name }}.')
File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\template\base.py", line 187, in __init__
engine = Engine.get_default()
File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\utils\lru_cache.py", line 125, in wrapper
result = user_function(*args, **kwds)
File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\template\engine.py", line 73, in get_default
django_engines = [engine for engine in engines.all()
File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\template\utils.py", line 108, in all
return [self[alias] for alias in self]
File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\template\utils.py", line 105, in __iter__
return iter(self.templates)
File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\utils\functional.py", line 60, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\template\utils.py", line 31, in templates
self._templates = settings.TEMPLATES
File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\conf\__init__.py", line 48, in __getattr__
self._setup(name)
File "C:\Python27\lib\site-packages\django-1.8-py2.7.egg\django\conf\__init__.py", line 42, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting TEMPLATES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
settings?what's wrong?thanks for your help
Answer: Import settings first.
from django.conf import settings
settings.configure()
from django import template
t = template.Template('My name is {{ name }}.')
|
how make python script for renewable downloads?
Question: I've been searching (without results) a reanudable (i don't know if this is
the correct word, sorry) way to download big files from internet with python,
i know how do it directly with urllib2, but if something interrupt the
connection, i need some way to reconnect and continue the download where it
was if it's possible (like a download manager).
Answer: For other people who can help the answer, there's a HTTP protocol called
Chunked Transfer Encoding that allow to do this specifying the 'Range' header
of the request with the beginning and end bytes (separated by a dash), thus is
possible just count how many bytes was downloaded previously and send it like
the new beginning byte for continue the download. Example with requests
module:
import requests
from os.path import getsize
#get size of previous downloaded chunk file
beg = getsize(PATH_TO_FILE)
#if we want we can get the size before download the file (without actually download it)
end = request.head(URL).headers['content-length']
#continue the download in the next byte from where it stopped
headers = {'Range': "bytes=%d-%s"%(beg+1,end)}
download = requests.get(URL, headers=headers)
|
Adding Google Analytics API Library to Google App Engine
Question: I am trying to run a simple python script on Google App Engine. How do I
install the Google Analytics API library?
Library: <https://developers.google.com/api-client-
library/python/apis/analytics/v3>
Instructions:
<https://cloud.google.com/appengine/docs/python/tools/libraries27#vendoring>
I've tried everything and can't get this to run, even though it works on my
pc. What I have right now is: The python scripts in the root folder, In the
/lib folder I copied the folders that were installed from my PC
(/googleapiclient and /google_api_python_client-1.4.0-py2.7.egg-info) And I
have appengine_config.py in /lib folder which contains:
from google.appengine.ext import vendor
# Add any libraries installed in the "lib" folder.
vendor.add('lib')
vendor.add('google-api-client')
app.yaml file:
application: psyched-cab-861
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: hello_analytics_api_v3.app
Traceback:
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
ImportError: No module named helloworld
New Log:
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/lib_config.py", line 354, in __getattr__
self._update_configs()
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/lib_config.py", line 290, in _update_configs
self._registry.initialize()
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/lib_config.py", line 165, in initialize
import_func(self._modname)
File "/base/data/home/apps/s~just-terminus-94303/1.384249106864280829/appengine_config.py", line 5, in <module>
vendor.add('google-api-python-client')
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/vendor/__init__.py", line 44, in add
'No such virtualenv or site directory' % path)
ValueError: virtualenv: cannot access google-api-python-client: No such virtualenv or site directory
I tried editing the appengine_config.py file to
vendor.add('googleapiclient') #The name of the file
I edit it in GAE, and click commit, it saves, but I get the same error as
above with the vendor.add('google-api-python-client') error. Why is the file
not updating?
Answer: As the
[docs](https://cloud.google.com/appengine/docs/python/tools/libraries27#vendoring)
say: put the `appengine_config.py` in your **root** folder of the application
(and not in the **/lib** folder). By the way, the name of the library is
`google-api-python-client` and not `google-api-client`.
Then you have to install `google-python-api-client` in your **/lib** folder:
$ pip install -t lib google-api-python-client
|
Python datetime.strptime - Converting month in String format to Digit
Question: I have a string that contains the date in this format: `full_date =
"May.02.1982"`
I want to use datetime.strptime() to display the date in all digits like:
"1982-05-02"
Here's what I tried:
full_date1 = datetime.strptime(full_date, "%Y-%m-%d")
When I try to print this, I get garbage values like `built-in-67732` Where am
I going wrong? Does the strptime() method not accept string values?
Answer: Your format string is wrong, it should be this:
In [65]:
full_date = "May.02.1982"
import datetime as dt
dt.datetime.strptime(full_date, '%b.%d.%Y')
Out[65]:
datetime.datetime(1982, 5, 2, 0, 0)
You then need to call `strftime` on a datetime object to get the string format
you desire:
In [67]:
dt.datetime.strptime(full_date, '%b.%d.%Y').strftime('%Y-%m-%d')
Out[67]:
'1982-05-02'
`strptime` is for creating a datetime format from a string, not to reformat a
string to another datetime string.
So you need to create a datetime object using `strptime`, then call `strftime`
to create a string from the datetime object.
The datetime format strings can be found in the
[docs](https://docs.python.org/2/library/datetime.html#strftime-strptime-
behavior) as well as an explanation of `strptime` and `strftime`
|
Get large files from FTP with python lib
Question: I need to download some large files (>30GB per file) from a FTP server. I'm
using ftplib from the python standardlib but there are some pitfalls: If i
download a large file, i can not use the connection anymore if the file
finishes. I get an EOF Error afterwards, so the connection is closed (due to
timeout?) and for each succeeding file i will get an error 421.
From what i read, there are two connections. The data and control channel,
where the data channel seems to work correctly (i can download the file
completly) but the control channels times out in the meantime. I also read
that the ftplib (and other python ftp libraries) are not suited for large
files and may only support files up to around 1GB. There is a similar question
to this topic here: [How to download big file in python via ftp (with
monitoring & reconnect)?](http://stackoverflow.com/questions/19245769/how-to-
download-big-file-in-python-via-ftp-with-monitoring-reconnect) which is not
quite the same because my files are huge in comparison.
My current code looks like this:
import ftplib
import tempfile
ftp = ftplib.FTP_TLS()
ftp.connect(host=server, port=port)
ftp.login(user=user, passwd=password)
ftp.prot_p()
ftp.cwd(folder)
for file in ftp.nlst():
fd, local_filename = tempfile.mkstemp()
f = open(fd, "wb")
ftp.retrbinary('RETR %s' % file, callback=f.write, blocksize=8192)
f.close()
Is there any tweak to it or another library that i can use, which does support
huge files?
Answer: If you experience issues with standard FTP, you can try using a different
protocol that is specifically designed to handle such large files.
A number of suitable
[solutions](http://moo.nac.uci.edu/~hjm/HOWTO_move_data.html) exist. Rsync
would probably be a good way to start.
|
How can I exit a Python3 script after 5 minutes
Question: I have a script that was copying data from SD card. Due to the huge amount of
files/filesize, this might take a longer period of time than expected. I would
like to exit this script after 5 minutes. How can I do so?
Answer: It's hard to verify that this will work without any example code, but you
could try something like this, using the [signal
module](https://docs.python.org/2/library/signal.html):
At the beginning of your code, define a handler for the alarm signal.
import signal
def handler(signum, frame):
print 'Times up! Exiting..."
exit(0)
Before you start the long process, add a line like this to your code:
#Install signal handler
signal.signal(signal.SIGALRM, handler)
#Set alarm for 5 minutes
signal.alarm(300)
In 5 minutes, your program will receive the alarm signal, which will call the
handler, which will exit. You can also do other things in the handler if you
want.
|
How to represent networkx graphs with edge weight using nxpd like outptut
Question: Recently I asked the question [How to represent graphs with
ipython](http://stackoverflow.com/questions/29774105/representating-graphs-
with-ipython). The answer was exactly what i was looking for, but today i'm
looking for a way to show the edge valuation on the final picture.
The edge valuation is added like this :
import networkx as nx
from nxpd import draw # If another library do the same or nearly the same
# output of nxpd and answer to the question, that's
# not an issue
import random
G = nx.Graph()
G.add_nodes_from([1,2])
G.add_edge(1, 2, weight=random.randint(1, 10))
draw(G, show='ipynb')
And the result is here.

I read the `help` of `nxpd.draw` (didn't see any web documentation), but i
didn't find anything. Is there a way to print the edge value ?
**EDIT** : also, if there's a way to give a formating function, this could be
good. For example :
def edge_formater(graph, edge):
return "My edge %s" % graph.get_edge_value(edge[0], edge[1], "weight")
**EDIT2** : If there's another library than nxpd doing nearly the same output,
it's not an issue
**EDIT3** : has to work with `nx.{Graph|DiGraph|MultiGraph|MultiDiGraph}`
Answer: If you look at the
[source](https://github.com/chebee7i/nxpd/blob/master/nxpd/nx_pydot.py)
`nxpd.draw` (function `draw_pydot`) calls `to_pydot` which filters the graph
attributes like:
if attr_type == 'edge':
accepted = pydot.EDGE_ATTRIBUTES
elif attr_type == 'graph':
accepted = pydot.GRAPH_ATTRIBUTES
elif attr_type == 'node':
accepted = pydot.NODE_ATTRIBUTES
else:
raise Exception("Invalid attr_type.")
d = dict( [(k,v) for (k,v) in attrs.items() if k in accepted] )
If you look up
[`pydot`](https://github.com/erocarrera/pydot/blob/master/pydot.py) you find
the `pydot.EDGE_ATTRIBUTES` which contains valid Graphviz-attributes. The
`weight` strictly refers to edge-weight by Graphviz if I recall, and `label`
is probably the attribute you need. Try:
G = nx.Graph()
G.add_nodes_from([1,2])
weight=random.randint(1, 10)
G.add_edge(1, 2, weight=weight, label=str(weight))
* * *
Note that I haven't been able to test if this works, just downvote if it
doesn't.
|
How can I properly copy nested dictionary objects?
Question: I'm working on a project with **Python 2.7** where I have a "complex"
dictionary structure, and I was trying to do something like this:
generic_dict = {
'user': {'created': {}, 'modified': {}, 'errors': {}},
'usermon': {'created': {}, 'modified': {}, 'ignored': {}, 'errors': {}}
log_data = {
'esp': generic_dict,
'por': generic_dict,
'sui': generic_dict,
'ben': generic_dict,
'mex': generic_dict,
'arg': generic_dict,
}
I was trying to use the generic dict to avoid repeating code but I have a
problem if I do like this, when I modify any of the country dicts (esp, ben,
por) all are modifying at the same time.
Let's assume the dictionary is empty and I do this
log_data['esp']['user']['created']['today'] = 'asdasdasda'
all the other dicts now have the same value like generic_dict is the same all
of them.
print log_data['ben']['user']['created']
Output: {'today': 'asdasdasda'}
print log_data['ben']['user']['created']
Output: {'today': 'asdasdasda'}
I understand what's happening but I don't know how to avoid that
* Which is the best way copy nested dictionary objects ?
Answer: You can use
[`copy.deepcopy`](https://docs.python.org/2/library/copy.html#copy.deepcopy)
to create a new copy of the `generic_dict` object, like this
from copy import deepcopy
log_data = {
'esp': deepcopy(generic_dict),
'por': deepcopy(generic_dict),
'sui': deepcopy(generic_dict),
'ben': deepcopy(generic_dict),
'mex': deepcopy(generic_dict),
'arg': deepcopy(generic_dict),
}
* * *
Otherwise, you can have a constructor function, like this
def generic_dict():
return {'user': {'created': {}, 'modified': {}, 'errors': {}},
'usermon': {'created': {}, 'modified':{}, 'ignored': {}, 'errors': {}}}
And then call it to create a new dictionary object every time, like this
log_data = {
'esp': generic_dict(),
'por': generic_dict(),
'sui': generic_dict(),
'ben': generic_dict(),
'mex': generic_dict(),
'arg': generic_dict(),
}
|
Indent Error with my battleship.py script
Question: I'm trying to create a simple two player game like the classic Battleship.
Hence I'm beginning to learn Python and I'm keeping it simple. I have created
a 5x5 grid and I want the players (2) to be able to place one ship 1x1
anywhere on the board. Then they take turns guessing where the other person
placed their ship.
When I compiled my code I got an indent error on line 61 `"else: "`. I'm aware
that the "H" and "M" for hit and miss will overlap since I'm outputting it to
the same playing board.
I guess what I need help with is the while loops in my code.
import sys
#////////////////////////////Setting up board////////////////////////////////////
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
#///////////////////////////Getting input//////////////////////////////////////////
def user_row():
get_row = raw_input("Enter ship row between 1 and 5")
#Not shure if this is the best way of checking that the input is an int
if int(get_row) == False:
print "You must enter an integer between 1 and 5"
get_row = raw_input("Enter ship row...")
if int(get_row) == False:
sys.exit()
def user_col():
get_col = raw_input("Enter ship col between 1 and 5")
if int(get_col) == False:
print "You must enter an integer between 1 and 5"
get_col = raw_input("Enter ship col...")
if int(get_col) == False:
sys.exit()
#/////////////////////////Intro//////////////////////////////////////////////////////
print "Let's play Battleship!"
print "This is your ocean"
print_board(board)
#////////////////////////Placing ships//////////////////////////////////////////////
print "Player 1 your up!"
print "Player 2 look away!"
print "Place your ship..."
#Not shure if this will call the two functions chronologic and store them as index 0 and 1 in my array. That is what I want it to do
user1_ship = [user_row(), user_col()]
print_board(board)
print "Player 2 your up!"
print "Player 1 look away!"
print "Place your ship..."
user_2 = [user_row(), user_col()]
#///////////////////////guesswork?//////////////////////////////////////////////////
#Maybe while loops inside while loops is not the best way of running the code over and over until someone sinks the other persons ship
#What Im expecting is the first inside while loop to break the outer loop if the player hits the other players ship otherwise break itself. Likewise with the second inner loop.
while True:
while True:
print "Player 1 your turn"
user1_guess = [user_row(), user_col()]
if user1_guess == user2_ship:
board[user1_guess[0]][user1_guess[1]] == "H"
print "PLAYER 1 WINS!"
break
else:
board[user1_guess[0]][user1_guess[1]] == "M"
print "You missed"
break
while True:
print "Player 2 your turn"
user2_guess = [user_row(), user_col()]
if user2_guess == user1_ship:
board[user2_guess[0]][user2_guess[1]] == "H"
print "PLAYER 2 WINS!"
break
else:
board[user2_guess[0]][user2_guess[1]] == "M"
print "You missed"
break
Answer: Your indentation is incorrect... Look at this:
while True:
while True:
print "Player 1 your turn"
user1_guess = [user_row(), user_col()]
if user1_guess == user2_ship:
board[user1_guess[0]][user1_guess[1]] == "H"
print "PLAYER 1 WINS!"
break
The `break` statement must have the same indentation as the `print` statement
like this:
while True:
while True:
print "Player 1 your turn"
user1_guess = [user_row(), user_col()]
if user1_guess == user2_ship:
board[user1_guess[0]][user1_guess[1]] == "H"
print "PLAYER 1 WINS!"
break
If you have some time, please read a [Python
Styleguide](https://www.python.org/dev/peps/pep-0008/) to improve the quality
of your code.
|
Theano: how to efficiently undo/reverse max-pooling
Question: I'm using Theano 0.7 to create a [convolutional neural
net](http://deeplearning.net/tutorial/lenet.html) which uses **[max-
pooling](http://deeplearning.net/tutorial/lenet.html#maxpooling)** (i.e.
shrinking a matrix down by keeping only the local maxima).
In order to "undo" or "reverse" the max-pooling step, one method is to store
the locations of the maxima as auxiliary data, then simply recreate the un-
pooled data by making a big array of zeros and using those auxiliary locations
to place the maxima in their appropriate locations.
Here's how I'm currently doing it:
import numpy as np
import theano
import theano.tensor as T
minibatchsize = 2
numfilters = 3
numsamples = 4
upsampfactor = 5
# HERE is the function that I hope could be improved
def upsamplecode(encoded, auxpos):
shp = encoded.shape
upsampled = T.zeros((shp[0], shp[1], shp[2] * upsampfactor))
for whichitem in range(minibatchsize):
for whichfilt in range(numfilters):
upsampled = T.set_subtensor(upsampled[whichitem, whichfilt, auxpos[whichitem, whichfilt, :]], encoded[whichitem, whichfilt, :])
return upsampled
totalitems = minibatchsize * numfilters * numsamples
code = theano.shared(np.arange(totalitems).reshape((minibatchsize, numfilters, numsamples)))
auxpos = np.arange(totalitems).reshape((minibatchsize, numfilters, numsamples)) % upsampfactor # arbitrary positions within a bin
auxpos += (np.arange(4) * 5).reshape((1,1,-1)) # shifted to the actual temporal bin location
auxpos = theano.shared(auxpos.astype(np.int))
print "code:"
print code.get_value()
print "locations:"
print auxpos.get_value()
get_upsampled = theano.function([], upsamplecode(code, auxpos))
print "the un-pooled data:"
print get_upsampled()
> _(By the way, in this case I have a 3D tensor, and it's only the third axis
> that gets max-pooled. People who work with image data might expect to see
> two dimensions getting max-pooled.)_
The output is:
code:
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
locations:
[[[ 0 6 12 18]
[ 4 5 11 17]
[ 3 9 10 16]]
[[ 2 8 14 15]
[ 1 7 13 19]
[ 0 6 12 18]]]
the un-pooled data:
[[[ 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 2. 0.
0. 0. 0. 0. 3. 0.]
[ 0. 0. 0. 0. 4. 5. 0. 0. 0. 0. 0. 6. 0. 0.
0. 0. 0. 7. 0. 0.]
[ 0. 0. 0. 8. 0. 0. 0. 0. 0. 9. 10. 0. 0. 0.
0. 0. 11. 0. 0. 0.]]
[[ 0. 0. 12. 0. 0. 0. 0. 0. 13. 0. 0. 0. 0. 0.
14. 15. 0. 0. 0. 0.]
[ 0. 16. 0. 0. 0. 0. 0. 17. 0. 0. 0. 0. 0. 18.
0. 0. 0. 0. 0. 19.]
[ 20. 0. 0. 0. 0. 0. 21. 0. 0. 0. 0. 0. 22. 0.
0. 0. 0. 0. 23. 0.]]]
This method **works** but it's a **bottleneck** , taking most of my computer's
time (I think the set_subtensor calls might imply cpu<->gpu data copying). So:
can this be implemented more efficiently?
I suspect there's a way to express this as a single `set_subtensor()` call
which may be faster, but I don't see how to get the tensor indexing to
broadcast properly.
* * *
**UPDATE:** I thought of a way of doing it in one call, by working on the
flattened tensors:
def upsamplecode2(encoded, auxpos):
shp = encoded.shape
upsampled = T.zeros((shp[0], shp[1], shp[2] * upsampfactor))
add_to_flattened_indices = theano.shared(np.array([ [[(y + z * numfilters) * numsamples * upsampfactor for x in range(numsamples)] for y in range(numfilters)] for z in range(minibatchsize)], dtype=theano.config.floatX).flatten(), name="add_to_flattened_indices")
upsampled = T.set_subtensor(upsampled.flatten()[T.cast(auxpos.flatten() + add_to_flattened_indices, 'int32')], encoded.flatten()).reshape(upsampled.shape)
return upsampled
get_upsampled2 = theano.function([], upsamplecode2(code, auxpos))
print "the un-pooled data v2:"
ups2 = get_upsampled2()
print ups2
However, this is still not good efficiency-wise because when I run this (added
on to the end of the above script) I find out that the Cuda libraries can't
currently do the integer index manipulation efficiently:
ERROR (theano.gof.opt): Optimization failure due to: local_gpu_advanced_incsubtensor1
ERROR (theano.gof.opt): TRACEBACK:
ERROR (theano.gof.opt): Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/theano/gof/opt.py", line 1493, in process_node
replacements = lopt.transform(node)
File "/usr/local/lib/python2.7/dist-packages/theano/sandbox/cuda/opt.py", line 952, in local_gpu_advanced_incsubtensor1
gpu_y = gpu_from_host(y)
File "/usr/local/lib/python2.7/dist-packages/theano/gof/op.py", line 507, in __call__
node = self.make_node(*inputs, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/theano/sandbox/cuda/basic_ops.py", line 133, in make_node
dtype=x.dtype)()])
File "/usr/local/lib/python2.7/dist-packages/theano/sandbox/cuda/type.py", line 69, in __init__
(self.__class__.__name__, dtype, name))
TypeError: CudaNdarrayType only supports dtype float32 for now. Tried using dtype int64 for variable None
Answer: I don't know whether this is faster, but it may be a little more concise. See
if it is useful for your case.
import numpy as np
import theano
import theano.tensor as T
minibatchsize = 2
numfilters = 3
numsamples = 4
upsampfactor = 5
totalitems = minibatchsize * numfilters * numsamples
code = np.arange(totalitems).reshape((minibatchsize, numfilters, numsamples))
auxpos = np.arange(totalitems).reshape((minibatchsize, numfilters, numsamples)) % upsampfactor
auxpos += (np.arange(4) * 5).reshape((1,1,-1))
# first in numpy
shp = code.shape
upsampled_np = np.zeros((shp[0], shp[1], shp[2] * upsampfactor))
upsampled_np[np.arange(shp[0]).reshape(-1, 1, 1), np.arange(shp[1]).reshape(1, -1, 1), auxpos] = code
print "numpy output:"
print upsampled_np
# now the same idea in theano
encoded = T.tensor3()
positions = T.tensor3(dtype='int64')
shp = encoded.shape
upsampled = T.zeros((shp[0], shp[1], shp[2] * upsampfactor))
upsampled = T.set_subtensor(upsampled[T.arange(shp[0]).reshape((-1, 1, 1)), T.arange(shp[1]).reshape((1, -1, 1)), positions], encoded)
print "theano output:"
print upsampled.eval({encoded: code, positions: auxpos})
|
How to create a 4 or 8 connected adjacency matrix
Question: I have been looking for a python implementation that returns a 4- or
8-connected adjacency matrix, given an array. I find it surprising that cv2 or
networkx don't include this functionality. I came across this great Matlab
[implementation](http://stackoverflow.com/a/3283732/4663466) and decided to
make something similar in python.
**Problem** : I'm looking for an implementation that improves on the linked
Matlab solution in runtime / space OR other interesting approaches.
**Disclaimer** :
I submit my own implementation here as I figure I can't be the only person who
will ever need to create an (4 / 8 connected) adjacency matrix for image
processing or other applications. It is my hope that improvements or better
implementations will be offered.
Answer: Using the diagonal structure, as detailed in [this
answer](http://stackoverflow.com/a/3283732/4663466) regarding "Construct
adjacency matrix in MATLAB", I create only the upper diagonals and add them in
the appropriate positions to a sparse diagonal matrix using
[scipy.sparse.diags](http://docs.scipy.org/doc/scipy-0.13.0/reference/generated/scipy.sparse.diags.html).
This sparse matrix is added to its transpose to give us the adjacency matrix.
When working with images it is often desirable to break up the image into non-
overlapping rectangular sub-images or patches. The patch_size parameter is a
tuple (rows, cols) that describes the rectangular patch of size 'rows x cols'.
import numpy as np
import scipy.sparse as s
def connected_adjacency(image, connect, patch_size=(1, 1)):
"""
Creates an adjacency matrix from an image where nodes are considered adjacent
based on 4-connected or 8-connected pixel neighborhoods.
:param image: 2 or 3 dim array
:param connect: string, either '4' or '8'
:param patch_size: tuple (n,m) used if the image will be decomposed into
contiguous, non-overlapping patches of size n x m. The
adjacency matrix will be formed from the smaller sized array
e.g. original image size = 256 x 256, patch_size=(8, 8),
then the image under consideration is of size 32 x 32 and
the adjacency matrix will be of size
32**2 x 32**2 = 1024 x 1024
:return: adjacency matrix as a sparse matrix (type=scipy.sparse.csr.csr_matrix)
"""
r, c = image.shape[:2]
r = r / patch_size[0]
c = c / patch_size[1]
if connect == '4':
# constructed from 2 diagonals above the main diagonal
d1 = np.tile(np.append(np.ones(c-1), [0]), r)[:-1]
d2 = np.ones(c*(r-1))
upper_diags = s.diags([d1, d2], [1, c])
return upper_diags + upper_diags.T
elif connect == '8':
# constructed from 4 diagonals above the main diagonal
d1 = np.tile(np.append(np.ones(c-1), [0]), r)[:-1]
d2 = np.append([0], d1[:c*(r-1)])
d3 = np.ones(c*(r-1))
d4 = d2[1:-1]
upper_diags = s.diags([d1, d2, d3, d4], [1, c-1, c, c+1])
return upper_diags + upper_diags.T
else:
raise ValueError('Invalid parameter \'connect\'={connect}, must be "4" or "8".'
.format(connect=repr(connect)))
A simple example:
a = np.arange(9).reshape((3, 3))
adj = connected_adjacency(a, '4').toarray()
print a
[[0 1 2]
[3 4 5]
[6 7 8]]
print adj
[[ 0. 1. 0. 1. 0. 0. 0. 0. 0.]
[ 1. 0. 1. 0. 1. 0. 0. 0. 0.]
[ 0. 1. 0. 0. 0. 1. 0. 0. 0.]
[ 1. 0. 0. 0. 1. 0. 1. 0. 0.]
[ 0. 1. 0. 1. 0. 1. 0. 1. 0.]
[ 0. 0. 1. 0. 1. 0. 0. 0. 1.]
[ 0. 0. 0. 1. 0. 0. 0. 1. 0.]
[ 0. 0. 0. 0. 1. 0. 1. 0. 1.]
[ 0. 0. 0. 0. 0. 1. 0. 1. 0.]]
Using networkx + matplotlib to plot the adjacency matrix as a graph: 
|
Overwriting/changing a field on a CSV in Python
Question: Not got too much Python (3.4) experience however I'm working on a program
which will let you add number plates and edit the 'status'. It's a car parking
program so the status will be In/Out.
Only problem I have is that I don't know how to edit a specific field on a CSV
file following an input. Eg: From In to Out.
For example CSV:
NH08OTR, 2008, Vauxhall, Corsa, Blue, In
I want to be able to change the last field from 'In' to 'Out' however the CSV
will have a variable amount of rows so I only want it to do it on a specific
registration plate. Example below:
Please choose a number plate to change the status of: NH08OTR
Status change: Out
Status successfully changed to 'Out'
I then want it to change the 'In' on the CSV to out.
Hope you understand and thanks for reading.
Answer: Given a csv:
NH08OTR, 2008, Vauxhall, Corsa, Blue, In
NH08OTY, 2008, Vauxhall, Corsa, Blue, Out
NH08OTZ, 2008, Vauxhall, Corsa, Blue, In
We want to open it, edit it in memory, then save the edit, hence:
import csv
# Open csv
r = csv.reader(open('car_parking.csv'))
line_in = [k for k in r]
#look for plate
number_plate = 'NH08OTZ'
#get current parking status
find_plate=([i for i,k in enumerate(line_in) if k[0] == number_plate]) #find plate in array
current_park_status = line_in[find_plate[0]][5]
print current_park_status
#edit array position, with new status
new_parking_status = 'IN'
line_in[find_plate[0]][5] = new_parking_status
#overwrite cv with new result
out = csv.writer(open('car_parking.csv', 'w'))
out.writerows(line_in)
|
How to use generic in Class.class
Question: I want to avoid the warning:
"type safety the expression of type needs unchecked conversion to conform to
Class"
From this sentence:
Class<MyInterface> cc = interpreter.get("Myclass", Class.class );
I have tried:
Class<MyInterface> cc = interpreter.get("Myclass", Class<MyInterface>.class );
But is invalid.
How can I do that without @SuppressWarnings("unchecked")
The signature of interpreter.get:
T interpreter.get(String name, Class<T> javaClass)
* * *
The context: I use the library Jython and I define a class in Python who
implement MyInterface, then I capture this class in Java then I create
instances of them. That is why I need the class itself, not a instance of the
class.
The code is something like:
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("from cl.doman.python import MyInterface");
....
interpreter.exec(pythonCode);
Class<MyInterface> cc = interpreter.get("Myclass", Class.class);
MyInterface a = (MyInterface) cc.newInstance();
My code work fine But I can't suppress the warning.
Answer: Probably
Class<?> clazz = interpreter.get("Myclass", Class.class);
Class<? extends MyInterface> cc = clazz.asSubclass(MyInterface.class);
// look, Ma, no typecast!
MyInterface a = cc.newInstance();
|
rethinkdb aggregation based on sequence items
Question: I'm currently going through the [rethinkdb python
tutorial](http://rethinkdb.com/docs/tutorials/superheroes/).
Currently, I have 4 superheroes. In the example below, `heroes` is an alias
for `r.db("python_tutorial").table("heroes")`.
In[45]: list(heroes.run())
Out[44]:
[{u'appearances_count': 98,
u'hero': u'Wolverine',
u'id': u'28b6a53f-14c6-4a36-bb0b-45a6fb9c77c9',
u'magazine_titles': [u'Amazing Spider-Man vs. Wolverine',
u'Avengers',
u'X-MEN Unlimited',
u'Magneto War',
u'Prime'],
u'name': u"James 'Logan' Howlett"},
{u'aka': [u'Magnus', u'Erik Lehnsherr', u'Lehnsherr'],
u'appearances_count': 42,
u'hero': u'Magneto',
u'id': u'19274b39-f829-4daa-ba2b-24fd680e01c6',
u'magazine_titles': [u'Alpha Flight', u'Avengers', u'Avengers West Coast'],
u'name': u'Max Eisenhardt'},
{u'appearances_count': 72,
u'hero': u'Storm',
u'id': u'69848f10-2f5a-48f4-8d87-c310b88f9487',
u'magazine_titles': [u'Amazing Spider-Man vs. Wolverine',
u'Excalibur',
u'Fantastic Four',
u'Iron Fist'],
u'name': u'Ororo Monroe'},
{u'appearances_count': 72,
u'hero': u'Professor Xavier',
u'id': u'22dd3ab1-60d6-4679-9c39-2ad7da6e48d0',
u'magazine_titles': [u'Alpha Flight', u'Avengers', u'Bishop', u'Defenders'],
u'name': u'Charles Francis Xavier'}]
What I would _like_ to do is group heroes in accordance with the magazine
titles they were in. So, I'm trying to build a query, that would give
something like the following:
u'Prime'
{ u'name': u"James 'Logan' Howlett"}
u'Fantastic Four'
{ u'name': u'Ororo Monroe'}
u'Excalibur'
{ u'name': u'Ororo Monroe'}
u'Defenders'
{ u'name': u'Charles Francis Xavier'}
u'Magneto War'
{ u'name': u"James 'Logan' Howlett"}
u'Bishop'
{ u'name': u'Charles Francis Xavier'}
u'Avengers West Coast'
{ u'name': u'Max Eisenhardt'}
u'Amazing Spider-Man vs. Wolverine'
{ u'name': u"James 'Logan' Howlett"}
{ u'name': u'Ororo Monroe'}
u'X-MEN Unlimited'
{ u'name': u"James 'Logan' Howlett"}
u'Alpha Flight'
{ u'name': u'Charles Francis Xavier'}
{ u'name': u'Max Eisenhardt'}
u'Avengers'
{ u'name': u"James 'Logan' Howlett"}
{ u'name': u'Charles Francis Xavier'}
{ u'name': u'Max Eisenhardt'}
u'Iron Fist'
{ u'name': u'Ororo Monroe'}
I have managed to do this through _two_ separate queries. Here is essentially
what I did:
In[46]: titles = list(heroes.concat_map(lambda hero: hero["magazine_titles"]).distinct().run())
In[47]: titles
Out[46]:
[u'Alpha Flight',
u'Amazing Spider-Man vs. Wolverine',
u'Avengers',
u'Avengers West Coast',
u'Bishop',
u'Defenders',
u'Excalibur',
u'Fantastic Four',
u'Iron Fist',
u'Magneto War',
u'Prime',
u'X-MEN Unlimited']
The above gives me a list of all the titles. Then, I merely search the
database to see if the the titles are in a hero's `magazine_titles`. Like so:
In[48]: from collections import defaultdict
In[49]: title_data = defaultdict(list)
In[57]: for title in titles:
... title_data[title] = list(heroes.filter(lambda hero: hero["magazine_titles"].contains(title)).pluck("name").run())
In[59]: for title, heroes in title_data.items():
... pprint(title)
... pprint(heroes, indent=4)
However, I would like to do this in _one_ query. And regarding said query,
would it be more efficient than doing two separate queries like I did?
Answer: The [group](http://rethinkdb.com/api/python/group/) command with `multi`
should do what you want:
heroes.group('magazine_titles', multi=True)['name']
|
Python List comprehension: Single string to list
Question: I'm struggling with list comprehensions.
Basically I have a simple string:
string = "['a','b','c','d']"
Note, that the brackets,commas and quotation marks are part of the string.
What I need is a `list1` with a,b,c,d as elements (so i need to get rid of the
quotation marks, the commas and brackets.)
for entry in string:
list1 = [x.lstrip(" ' ") for x in string.split(',')]
list2 = [x.strip(" ' ") for x in list1]
This does not work at all. list1 gets created without the beginning `"'"`, but
when I try to print out list2 the quotations are there again. I did not even
start dealing with the brackets. Is there a nice way to get my list?
Answer: If your string is already built as a list object but with quotation marks as
you stated:
string = "['a','b','c','d']"
You can simply make
exec('list1='+string)
* * *
As an alternative, you can remove everything that is not commas, and end up
with
string = "a,b,c,d"
For instance
import re
string = re.sub(r"[^\w,]", "", string)
And then you use
>>> list1 = string.split(',')
>>> list1
['a','b','c','d']
|
Close main window after opening a new one
Question: I found this example of code here on stackoverflow and I would like to make
the first window close when a new one is opened. So what I would like is when
a new window is opened, the main one should be closed automatically.
#!/usr/bin/env python
import Tkinter as tk
from Tkinter import *
class windowclass():
def __init__(self,master):
self.master = master
self.frame = tk.Frame(master)
self.lbl = Label(master , text = "Label")
self.lbl.pack()
self.btn = Button(master , text = "Button" , command = self.command )
self.btn.pack()
self.frame.pack()
def command(self):
print 'Button is pressed!'
self.newWindow = tk.Toplevel(self.master)
self.app = windowclass1(self.newWindow)
class windowclass1():
def __init__(self , master):
self.master = master
self.frame = tk.Frame(master)
master.title("a")
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25 , command = self.close_window)
self.quitButton.pack()
self.frame.pack()
def close_window(self):
self.master.destroy()
root = Tk()
root.title("window")
root.geometry("350x50")
cls = windowclass(root)
root.mainloop()
Answer: You would withdraw the main window, but you have no way to close the program
after the button click in the Toplevel, when the main window is still open but
doesn't show Also pick one or the other of (but don't use both)
import Tkinter as tk
from Tkinter import *
This opens a 2nd Toplevel which allows you to exit the program
import Tkinter as tk
class windowclass():
def __init__(self,master):
self.master = master
##self.frame = tk.Frame(master) not used
self.lbl = tk.Label(master , text = "Label")
self.lbl.pack()
self.btn = tk.Button(master , text = "Button" , command = self.command )
self.btn.pack()
##self.frame.pack() not used
def command(self):
print 'Button is pressed!'
self.master.withdraw()
toplevel=tk.Toplevel(self.master)
tk.Button(toplevel, text="Exit the program",
command=self.master.quit).pack()
self.newWindow = tk.Toplevel(self.master)
self.app = windowclass1(self.newWindow)
class windowclass1():
def __init__(self , master):
""" note that "master" here refers to the TopLevel
"""
self.master = master
self.frame = tk.Frame(master)
master.title("a")
self.quitButton = tk.Button(self.frame,
text = 'Quit this TopLevel',
width = 25 , command = self.close_window)
self.quitButton.pack()
self.frame.pack()
def close_window(self):
self.master.destroy() ## closes this TopLevel only
root = tk.Tk()
root.title("window")
root.geometry("350x50")
cls = windowclass(root)
root.mainloop()
|
Why is [] faster than list()?
Question: I recently compared the processing speeds of `[]` and `list()` and was
surprised to discover that `[]` runs _more than three times faster_ than
`list()`. I ran the same test with `{}` and `dict()` and the results were
practically identical: `[]` and `{}` both took around 0.128sec / million
cycles, while `list()` and `dict()` took roughly 0.428sec / million cycles
each.
Why is this? Do `[]` and `{}` (probably `()` and `''`, too) immediately pass
back a copies of some empty stock literal while their explicitly-named
counterparts (`list()`, `dict()`, `tuple()`, `str()`) fully go about creating
an object, whether or not they actually have elements?
I have no idea how these two methods differ but I'd love to find out. I
couldn't find an answer in the `docs` or on SO, and searching for empty
brackets turned out to be more complicated than I'd expected.
I got my timing results by calling `timeit.timeit("[]")` and
`timeit.timeit("list()")`, and `timeit.timeit("{}")` and
`timeit.timeit("dict()")`, to compare lists and dictionaries, respectively.
I'm running Python 2.7.9.
I recently discovered "[Why is if True slower than if
1?](http://stackoverflow.com/questions/18123965/why-if-true-is-slower-than-
if-1)" that compares the performance of `if True` to `if 1` and seems to touch
on a similar literal-versus-global scenario; perhaps it's worth considering as
well.
Answer: Because `[]` and `{}` are _literal syntax_. Python can create bytecode just to
create the list or dictionary objects:
>>> import dis
>>> dis.dis(compile('[]', '', 'eval'))
1 0 BUILD_LIST 0
3 RETURN_VALUE
>>> dis.dis(compile('{}', '', 'eval'))
1 0 BUILD_MAP 0
3 RETURN_VALUE
`list()` and `dict()` are separate objects. Their names need to be resolved,
the stack has to be involved to push the arguments, the frame has to be stored
to retrieve later, and a call has to be made. That all takes more time.
For the empty case, that means you have at the very least a
[`LOAD_NAME`](https://docs.python.org/2/library/dis.html#opcode-LOAD_NAME)
(which has to search through the global namespace as well as the
[`__builtin__` module](https://docs.python.org/2/library/__builtin__.html))
followed by a
[`CALL_FUNCTION`](https://docs.python.org/2/library/dis.html#opcode-
CALL_FUNCTION), which has to preserve the current frame:
>>> dis.dis(compile('list()', '', 'eval'))
1 0 LOAD_NAME 0 (list)
3 CALL_FUNCTION 0
6 RETURN_VALUE
>>> dis.dis(compile('dict()', '', 'eval'))
1 0 LOAD_NAME 0 (dict)
3 CALL_FUNCTION 0
6 RETURN_VALUE
You can time the name lookup separately with `timeit`:
>>> import timeit
>>> timeit.timeit('list', number=10**7)
0.30749011039733887
>>> timeit.timeit('dict', number=10**7)
0.4215109348297119
The time discrepancy there is probably a dictionary hash collision. Subtract
those times from the times for calling those objects, and compare the result
against the times for using literals:
>>> timeit.timeit('[]', number=10**7)
0.30478692054748535
>>> timeit.timeit('{}', number=10**7)
0.31482696533203125
>>> timeit.timeit('list()', number=10**7)
0.9991960525512695
>>> timeit.timeit('dict()', number=10**7)
1.0200958251953125
So having to call the object takes an additional `1.00 - 0.31 - 0.30 == 0.39`
seconds per 10 million calls.
You can avoid the global lookup cost by aliasing the global names as locals
(using a `timeit` setup, everything you bind to a name is a local):
>>> timeit.timeit('_list', '_list = list', number=10**7)
0.1866450309753418
>>> timeit.timeit('_dict', '_dict = dict', number=10**7)
0.19016098976135254
>>> timeit.timeit('_list()', '_list = list', number=10**7)
0.841480016708374
>>> timeit.timeit('_dict()', '_dict = dict', number=10**7)
0.7233691215515137
but you never can overcome that `CALL_FUNCTION` cost.
|
How to create daily log folder in python logging
Question: I want to make the log file output into daily folder in python.
I can make the log path in hander like "../myapp/logs/20150514/xx.log" through
current date. But the problem is that the log path doesn't change when the
date changes.
I create the log instance while i start my **long-running** python script
xx.py, and now the instance's log path is "../myapp/logs/20150514/xx.log". But
on tomorrow, as the instance is not changed, so its path is still
"../myapp/logs/20150514/xx.log" which should be
"../myapp/logs/20150515/xx.log".
How can i make the log output into daily folder?
My get log instance codes:
import os
import utils
import logging
from logging.handlers import RotatingFileHandler
import datetime
def getInstance(file=None):
global logMap
if file is None:
file = 'other/default.log'
else:
file = file + '.log'
if(logMap.has_key(file)):
return logMap.get(file)
else:
visit_date = datetime.date.today().strftime('%Y-%m-%d')
date_file = os.path.join(visit_date,file)
log_path = utils.read_from_ini('log_path').strip()
log_path = os.path.join(log_path,date_file);
if not os.path.isdir(os.path.dirname(log_path)):
os.makedirs(os.path.dirname(log_path))
logging.basicConfig(datefmt='%Y-%m-%d %H:%M:%S',level=logging.INFO)
log_format = '[%(asctime)s][%(levelname)s]%(filename)s==> %(message)s'
formatter = logging.Formatter(log_format)
log_file = RotatingFileHandler(log_path, maxBytes=10*1024*1024,backupCount=5)
log_file.setLevel(logging.INFO)
log_file.setFormatter(formatter)
instance = logging.getLogger(file)
instance.addHandler(log_file)
logMap[file] = instance
return instance
Answer: Your `RotatingFileHandler` doesn't rotate on a time basis, but rather a size
basis. That's what the `maxBytes` argument is for. If you want to rotate based
on time, use a `TimedRotatingFileHandler` instead. Note that this works with
filenames, but not paths (as far as I know). You can have 20150505.log,
20150506.log, but not 20150505/mylog.log, 20150506/mylog.log.
If you want to rotate folder names you could probably do it by subclassing the
TimedRotatingFileHandler and adding your own logic.
|
AttributeError: 'dict' object has no attribute 'read'
Question: I am completely new to python. I am not able to run the following code as it
throws an attribute error. Could someone please help?
import tweepy
import urllib
import json
api_key = "VdG3NjsNKg49NbNb7GMHiX"
api_secret = "yBGKwe2K3QYk5lDny1eIKiyEQawVLQKX1HbRCTRfA9hK9"
access_token_key = "110456973-H8CAAET5CBoEa6FS4CKmk98XOADnJOsxK45"
access_token_secret = "wPUlfaxs1TFrTlXs2VqJIE5ffAfclhJCWmMlLPncb"
auth = tweepy.auth.OAuthHandler(api_key,api_secret)
auth.set_access_token(access_token_key,access_token_secret)
api=tweepy.API(auth,parser=tweepy.parsers.JSONParser())
results=api.search(q="microsoft",count=100)
print type(results)
print json.load(results)
Answer:
results=api.search(q="microsoft",count=100)
print type(results)
print json.load(results)
`results` here is already a `dict`.
There is no need to deserialize it as JSON.
See:
[`tweepy.api.API.search()`](http://pythonhosted.org//tweepy/api.html#API.search)
which reads:
> `API.search(q[, lang][, locale][, rpp][, page][, since_id][, geocode][,
> show_user])`
Returns tweets that match a specified query.
Parameters:
q – the search query string
lang – Restricts tweets to the given language, given by an ISO 639-1 code.
locale – Specify the language of the query you are sending. This is intended for language-specific clients and the default should work in the majority of cases.
rpp – The number of tweets to return per page, up to a max of 100.
page – The page number (starting at 1) to return, up to a max of roughly 1500 results (based on rpp * page.
geocode – Returns tweets by users located within a given radius of the given latitude/longitude. The location is preferentially taking from the Geotagging API, but will fall back to their Twitter profile. The parameter value is specified by “latitide,longitude,radius”, where radius units must be specified as either “mi” (miles) or “km” (kilometers). Note that you cannot use the near operator via the API to geocode arbitrary locations; however you can use this geocode parameter to search near geocodes directly.
show_user – When true, prepends “<user>:” to the beginning of the tweet. This is useful for readers that do not display Atom’s author field. The default is false.
Return type:
list of SearchResult objects
**NB:** The "Return type:"
|
Python global variable referenced before assigned a value
Question: I recently started to program in python, and I love it so far. I previously
programmed in c# and java, which is probably causing my problem. In c#, if you
have a public variable, it will change in each method. Sorry for the bad
explanation, but it will be easier to visualize the code.
This code is an example of what I want to happen in python in c# form. The
code does not actually work because it's only an example.
class Player
{
public var player; //create the variable
public var playerRectangle;
public var playerMovement;
public Player()
{
player = pygame.image.load("player.png"); //set the variables value
playerRectangle = player.get_rect();
playerMovement = new int[0,0];
}
public void Update()
{
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_w:
playerMovement[1] = -2 //use the variables value
if event.type == pygame.KEYDOWN and event.key == pygame.K_s:
playerMovement[1] = 2
if event.type == pygame.KEYDOWN and event.key == pygame.K_a:
playerMovement[0] = -2
if event.type == pygame.KEYDOWN and event.key == pygame.K_d:
playerMovement[0] = 2
if event.type == pygame.KEYUP and event.key == pygame.K_w:
playerMovement[1] = 0
if event.type == pygame.KEYUP and event.key == pygame.K_s:
playerMovement[1] = 0
if event.type == pygame.KEYUP and event.key == pygame.K_a:
playerMovement[0] = 0
if event.type == pygame.KEYUP and event.key == pygame.K_d:
playerMovement[0] = 0
playerRectangle = playerRectangle.move(playerMovement)
}
}
The actual python code is:
import pygame
class Player:
player = None #create the variable
playerRectangle = None
playerMovement = None
def __init__():
global player
player = pygame.image.load("player.png") #set the variables value
global playerRectangle
playerRectangle = player.get_rect()
global playerMovement
playerMovement = [0,0]
def update():
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_w:
playerMovement[1] = -2 #use the variables !!ERROR!!
if event.type == pygame.KEYDOWN and event.key == pygame.K_s:
playerMovement[1] = 2
if event.type == pygame.KEYDOWN and event.key == pygame.K_a:
playerMovement[0] = -2
if event.type == pygame.KEYDOWN and event.key == pygame.K_d:
playerMovement[0] = 2
if event.type == pygame.KEYUP and event.key == pygame.K_w:
playerMovement[1] = 0
if event.type == pygame.KEYUP and event.key == pygame.K_s:
playerMovement[1] = 0
if event.type == pygame.KEYUP and event.key == pygame.K_a:
playerMovement[0] = 0
if event.type == pygame.KEYUP and event.key == pygame.K_d:
playerMovement[0] = 0
playerRectangle = playerRectangle.move(playerMovement)
def returnTexture():
return player
def returnRectangle():
return playerRectangle
It says that the variable is referenced before it was given a value, but I
gave it a value in the constructor.
Answer: You have forgotten (_or have not read_) the use of `self` in your methods.
You need to put `self` in the method definitions and use `self.<attribute>` to
reference attributes on the instance.
**Example:**
class Player(object):
def __init__(self, name):
self.name = name
def update_name(self, name):
self.name = name
bob = Player("Bob")
print bob.name # Bob
bob.update_name("Bob Jones")
print bob.name # Bob Jones
**Note:** That the use of `self` in method definitions of classes in Python is
by convention only; you can use whatever name you like but we widely and
typically (_by convention_) use `self`.
See: [Classes](https://docs.python.org/2/tutorial/classes.html)
See Also: [What is the purpose of self in
Python?](http://stackoverflow.com/questions/2709821/what-is-the-purpose-of-
self-in-python)
**Side Note:** One of the reasons for this (_btw_) is that in Python we like
to be more explicit about how we write code. See the 2nd line of the [Zen of
Python](https://www.python.org/dev/peps/pep-0020/)
> The [Zen of Python](https://www.python.org/dev/peps/pep-0020/)
>
>
> Beautiful is better than ugly.
>
> Explicit is better than implicit.
>
> ...
>
**Update:** It's also worth nothing (_please read the documentation_) that
there is no notion of public vs. private members with Python's type system. We
define "private" members by convention only usually with a prefixed single
underscore; e.g: `def _foo(self):` as a private/inernal method.
|
AttributeError: 'str' object has no attribute 'words'
Question: I'm using Python34. I want to get frequency of words from CSV file but it show
an error. Here is my code.Anyone help me to solve this problem.
from textblob import TextBlob as tb
import math
words={}
def tfidf(word, blob, bloblist):
return tf(word, blob) * idf(word, bloblist)
def tf(word, blob):
return blob.words.count(word) / len(blob.words)
def n_containing(word, bloblist):
return sum(1 for blob in bloblist if word in blob)
def idf(word, bloblist):
return math.log(len(bloblist) / (1 + n_containing(words, bloblist)))
bloblist = open('afterstopwords.csv', 'r').read()
for i, blob in enumerate(bloblist):
print("Top words in document {}".format(i + 1))
scores = {word: tfidf(word, blob, bloblist) for word in blob.words}
sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)
for word, score in sorted_words[:3]:
print("\tWord: {}, TF-IDF: {}".format(word, round(score, 5)))
And the error is:
Top words in document 1
Traceback (most recent call last):
File "D:\Python34\tfidf.py", line 45, in <module>
scores = {word: tfidf(word, blob, bloblist) for word in blob.words}
AttributeError: 'str' object has no attribute 'words'
Answer: from <http://stevenloria.com/finding-important-words-in-a-document-using-tf-
idf/> some of the code for bloblist is:
bloblist = [document1, document2, document3]
don't change it. Plus, preceding it are code for the documents like:
document1 = tb("""blablabla""")
Here's what I did...I use a function for opening files in my python, where
openfile holds the file details.
txt =openfile()
document1=tb(txt)
bloblist = [document1]
THe rest of the original code is unchanged. This works BUT I have only been
able to get it to finish small files. It takes much too long for larger files.
And it doesn't look accurate at all. For word count I use
<https://rmtheis.wordpress.com/2012/09/26/count-word-frequency-with-python/>
and it has worked very quickly for 9999 rows each being 50-75 characters long.
Seems accurate too, results seem equivalent to wordcloud results.
|
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)
Question: I have a Python script which uses tinypng api to convert images recursively
and for some reason it does not work and I get:
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0:
> ordinal not in range(128)
What am I doing wrong?
import os
import base64
from os.path import dirname
from urllib2 import Request, urlopen
from base64 import b64encode
compress_png = True
compress_jpg = True
import_dir = '666\product'
output_dir = '666\product'
tiny_png_key = 'xxxxxx'
tiny_png_url = 'https://api.tinypng.com/shrink'
img_count = 0
file_count = 0
compress_count = 0
existing_count = 0
def compressImage(filepath, filedest, overwrite = True):
global compress_count
global existing_count
if not os.path.isfile(filedest) or overwrite:
status = ''
request = Request(tiny_png_url, open(filepath, "rb").read())
auth = b64encode(bytes("api:" + tiny_png_key)).decode("ascii")
request.add_header("Authorization", "Basic %s" % auth)
response = urlopen(request)
if response.getcode() == 201:
status = "success";
headers = response.info()
result = urlopen(headers["Location"]).read()
if not os.path.exists(os.path.dirname(filedest)):
os.makedirs(os.path.dirname(filedest))
open(filedest, "wb").write(result)
compress_count += 1
else:
status = "failed"
print 'Compressing: %s\nFile: %s\nStatus: %s\n'%(filepath, img_count, status)
else:
existing_count += 1
# loop througs files in import_dir recursively
for subdir, dirs, files in os.walk(import_dir):
for file in files:
filepath = os.path.join(subdir, file)
fileName, fileExtension = os.path.splitext(file)
file_count += 1
if(fileExtension == '.png' and compress_png) or (fileExtension == '.jpg' and compress_jpg):
img_count += 1
filedest = filepath.replace(import_dir, output_dir)
compressImage(filepath, filedest)
print '================'
print 'Total Files: %s'%(file_count)
print 'Total Images: %s'%(img_count)
print 'Images Compressed: %s'%(compress_count)
print 'Images Previously Compressed (Exist in output directory): %s'%(existing_count)
Full error:
Traceback (most recent call last):
File "C:\Users\Vygantas\Desktop\test.py", line 55, in <module> compressImage(filepath, filedest)
File "C:\Users\Vygantas\Desktop\test.py", line 28, in compressImage response = urlopen(request)
File "C:\Python27\lib\urllib2.py", line 126, in urlopen return _opener.open(url, data, timeout)
File "C:\Python27\lib\urllib2.py", line 391, in open response = self._open(req, data)
File "C:\Python27\lib\urllib2.py", line 409, in _open '_open', req)
File "C:\Python27\lib\urllib2.py", line 369, in _call_chain result = func(*args)
File "C:\Python27\lib\urllib2.py", line 1181, in https_open return self.do_open(httplib.HTTPSConnection, req)
File "C:\Python27\lib\urllib2.py", line 1142, in do_open h.request(req.get_method(), req.get_selector(), req.data, headers)
File "C:\Python27\lib\httplib.py", line 946, in request self._send_request(method, url, body, headers)
File "C:\Python27\lib\httplib.py", line 987, in _send_request self.endheaders(body)
File "C:\Python27\lib\httplib.py", line 940, in endheaders self._send_output(message_body)
File "C:\Python27\lib\httplib.py", line 801, in _send_output msg += message_body UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)
Answer: You have to encode the data but not the user name I would try something like:
def compressImage(filepath, filedest, overwrite = True):
global compress_count
global existing_count
if not os.path.isfile(filedest) or overwrite:
status = ''
data = open(filepath, "rb").read()
data = base64.b64encode(data)
request = Request(tiny_png_url, data)
request.add_header("Content-type", "application/x-www-form-urlencoded; charset=UTF-8")
auth = "api:" + tiny_png_key
request.add_header("Authorization", "Basic %s" % auth)
response = urlopen(request)
|
Django custom command error: unrecognized arguments
Question: I'm trying to create a command similar to `createsuperuser` which will take
two arguments (username and password)
Its working fine in django 1.7 but not in 1.8. (I'm also using python3.4)
this is the code I wrote
**myapp/management/commands/createmysuperuser.py**
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
class Command(BaseCommand):
help = 'Create a super user'
def handle(self, *args, **options):
if len(args) != 2:
raise CommandError('need exactly two arguments for username and password')
username, password = args
u, created = User.objects.get_or_create(username=username)
if created:
u.is_superuser = True
u.is_staff = True
u.set_password(password)
u.save()
else:
raise CommandError("user '%s' already exist" % username)
return "Password changed successfully for user '%s'" % u.username
and when I try to run this command
`$ python manage.py createmysuperuser myuser mypassword`
I get this error
usage: manage.py createmysuperuser [-h] [--version] [-v {0,1,2,3}]
[--settings SETTINGS]
[--pythonpath PYTHONPATH] [--traceback]
[--no-color]
manage.py createmysuperuser: error: unrecognized arguments: myuser mypassword
but when I dont pass any arguments it raises `CommandError` which is expected.
`CommandError: need exactly two arguments for username and password`
Answer: In django 1.8 you should [add
arguments](https://docs.djangoproject.com/en/1.8/releases/1.8/#extending-
management-command-arguments-through-command-option-list) to you command:
class Command(BaseCommand):
...
def add_arguments(self, parser):
parser.add_argument('username')
parser.add_argument('password')
`add_argument()` method of `argparse` is [documented
here](https://docs.python.org/3/library/argparse.html#the-add-argument-
method).
**UPDATE** : By default arguments are passed in the `options` parameter so the
`handle()` method should look like this:
def handle(self, *args, **options):
username = options['username']
password = options['password']
...
And you don't need to check the length of the `args` list - it is already done
by `argparse`. This is the recommended method but if you want to use the
`args` argument then you have to use the "compatibility mode" and name the
added argument as `args`:
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('args')
def handle(self, *args, **options):
if len(args) != 2:
...
Read the "Changed in Django 1.8" side note in the [first
chapter](https://docs.djangoproject.com/en/1.8/howto/custom-management-
commands/#module-django.core.management) of the docs (right after the
`closepoll.py` example).
**UPDATE2** : Here is the full working example:
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('username')
parser.add_argument('password')
def handle(self, *args, **options):
username = options['username']
password = options['password']
return u'Username: %s Password: %s' % (username, password)
|
PyMC3 & Theano - Theano code that works stop working after pymc3 import
Question: Some simple theano code that works perfectly, stop working when I import pymc3
Here some snipets in order to reproduce the error:
#Initial Theano Code (this works)
import theano.tensor as tsr
x = tsr.dscalar('x')
y = tsr.dscalar('y')
z = x + y
#Snippet 1
import pymc3 as pm
import theano.tensor as tsr
x = tsr.dscalar('x')
y = tsr.dscalar('y')
z = x + y
#Snippet 2
import theano.tensor as tsr
import pymc3 as pm
x = tsr.dscalar('x')
y = tsr.dscalar('y')
z = x + y
#Snippet 3
import pymc3 as pm
x = pm.theano.tensor.dscalar('x')
y = pm.theano.tensor.dscalar('y')
z = x + y
And I get the following error for each of the previous snippets:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/Users/tom/anaconda/lib/python3.4/site-packages/theano/gof/op.py in __call__(self, *inputs, **kwargs)
516 try:
--> 517 storage_map[ins] = [self._get_test_value(ins)]
518 compute_map[ins] = [True]
/Users/tom/anaconda/lib/python3.4/site-packages/theano/gof/op.py in _get_test_value(cls, v)
478
--> 479 raise AttributeError('%s has no test value' % v)
480
AttributeError: x has no test value
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
<ipython-input-2-ef8582b040f8> in <module>()
3 x = pm.theano.tensor.dscalar('x')
4 y = pm.theano.tensor.dscalar('y')
----> 5 z = x + y
/Users/tom/anaconda/lib/python3.4/site-packages/theano/tensor/var.py in __add__(self, other)
126 def __add__(self, other):
127 try:
--> 128 return theano.tensor.basic.add(self, other)
129 # We should catch the minimum number of exception here.
130 # Otherwise this will convert error when Theano flags
/Users/tom/anaconda/lib/python3.4/site-packages/theano/gof/op.py in __call__(self, *inputs, **kwargs)
523 run_perform = False
524 elif config.compute_test_value == 'raise':
--> 525 raise ValueError('Cannot compute test value: input %i (%s) of Op %s missing default value' % (i, ins, node))
526 elif config.compute_test_value == 'ignore':
527 # silently skip test
ValueError: Cannot compute test value: input 0 (x) of Op Elemwise{add,no_inplace}(x, y) missing default value
Any Ideas ? Thanks in advance
Answer: I think this is related to `pymc3` setting `theano.config.compute_test_value =
'raise'`: <https://github.com/pymc-devs/pymc3/blob/master/pymc3/model.py#L395>
You can explicitly set `theano.config.compute_test_value` back to `'ignore'`
to get rid of the error.
|
python error "Job information querying failed" on win10
Question: I'm running python scripts that connect and read some information from some
firmware (not so important for this question)
I'm using python 3.4.3, and scripts are working on win7,8, and even on win10
ver 10.0.10045.
But on newest win10 ver 10.0.10108 I get this above mentioned error.
Job information querying failed
I've googled it and found some opened issue here:
<https://bugs.python.org/issue24127> It has something to do with PIP (I'm new
to python - I don't know what exactly pip is) And I don't even know if this
issue is what I'm seeing , or I get this same error for another reason. I
don't even know how to debug the problem. Any help would be appreciated.
Answer: <https://bugs.python.org/issue24127> has been confirmed by a Windows dev to be
a bug in current builds of Windows 10, and the issue has been closed.
|
Django custom widget displaying escaped html
Question: I wrote a widget for Django forms in order to have a bootstrap3 multiple
checkbox directly in the template in order to reuse it in the future.
So I wrote an app `prettyforms` which contains all basic files (`__init__.py`,
`views.py` ...) and created a forms.py where I wrote the custom widget.
**the main form for the view item/forms.py is such as**
from django import forms
from django.utils.translation import ugettext as _
from mysite.item.models import Item, ItemCategory
from mysite.prettyforms import forms as prettyforms
class CreateItemForm(forms.ModelForm):
class Meta:
model = Item
fields = (
'categories',
)
widgets = {
'categories': prettyforms.PrettyCheckboxSelectMultiple(),
}
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(CreateItemForm, self).__init__(*args, **kwargs)
categories = ItemCategory.objects.all()
categories_choices = [ [category.pk, category.name] for category in categories ]
self.fields['categories'].choices = categories_choices
self.fields['categories'].error_messages = {
'required': _('At least one category must be selected')
}
**and the file containing the widget prettyforms/forms.py is such as:**
# -*- coding: utf-8 -*-
from django.forms.widgets import (
ChoiceInput, SelectMultiple, RendererMixin,
CheckboxChoiceInput, ChoiceFieldRenderer
)
from django.utils.encoding import (
force_str, force_text, python_2_unicode_compatible,
)
from django.utils.safestring import mark_safe
from django.forms.utils import flatatt
from django.utils.html import format_html, html_safe
@html_safe
@python_2_unicode_compatible
class PrettyChoiceInput(ChoiceInput):
def __str__(self):
return self.render()
def render(self, name=None, value=None, attrs=None, choices=()):
# NOTE: not sure if we need to compute this as we don't use it
if self.id_for_label:
label_for = format_html(' for="{}"', self.id_for_label)
else:
label_for = ''
attrs = dict(self.attrs, **attrs) if attrs else self.attrs
# TODO: create CSS for btn-checkbox for convention
return format_html(
'<label class="btn btn-primary">{} {}</label>',
self.tag(attrs),
self.choice_label
)
def tag(self, attrs=None):
attrs = attrs or self.attrs
final_attrs = dict(attrs, type=self.input_type, name=self.name, value=self.choice_value)
if self.is_checked():
final_attrs['checked'] = 'checked'
# added autocomplete off
return format_html('<input{} autocomplete="off" />', flatatt(final_attrs))
class PrettyCheckboxChoiceInput(PrettyChoiceInput):
input_type = 'checkbox'
def __init__(self, *args, **kwargs):
super(PrettyCheckboxChoiceInput, self).__init__(*args, **kwargs)
self.value = set(force_text(v) for v in self.value)
def is_checked(self):
return self.choice_value in self.value
@html_safe
@python_2_unicode_compatible
class PrettyChoiceFieldRenderer(ChoiceFieldRenderer):
outer_html = '<div class="btn-group" data-toggle="buttons"{id_attr}>{content}</div>'
inner_html = '{choice_value}{sub_widgets}'
def __getitem__(self, idx):
choice = self.choices[idx] # Let the IndexError propagate
return self.choice_input_class(self.name, self.value, self.attrs.copy(), choice, idx)
def __str__(self):
return self.render()
def render(self):
"""
Outputs a <ul> for this set of choice fields.
If an id was given to the field, it is applied to the <ul> (each
item in the list will get an id of `$id_$i`).
"""
id_ = self.attrs.get('id', None)
output = []
for i, choice in enumerate(self.choices):
choice_value, choice_label = choice
if isinstance(choice_label, (tuple, list)):
attrs_plus = self.attrs.copy()
if id_:
attrs_plus['id'] += '_{}'.format(i)
sub_ul_renderer = ChoiceFieldRenderer(name=self.name,
value=self.value,
attrs=attrs_plus,
choices=choice_label)
sub_ul_renderer.choice_input_class = self.choice_input_class
output.append(format_html(self.inner_html, choice_value=choice_value,
sub_widgets=sub_ul_renderer.render()))
else:
w = self.choice_input_class(self.name, self.value,
self.attrs.copy(), choice, i)
output.append(format_html(self.inner_html,
choice_value=force_text(w), sub_widgets=''))
return format_html(self.outer_html,
id_attr=format_html(' id="{}"', id_) if id_ else '',
content=mark_safe('\n'.join(output)))
class PrettyCheckboxFieldRenderer(PrettyChoiceFieldRenderer):
choice_input_class = PrettyCheckboxChoiceInput
class PrettyCheckboxSelectMultiple(RendererMixin, SelectMultiple):
renderer = PrettyCheckboxFieldRenderer
_empty_value = []
Most of the text in the classes and its methods is copied and pasted from
[widgets.py](https://github.com/django/django/blob/master/django/forms/widgets.py)
In the templates I simply put
{{ form.as_p }}
And the problem is that all fields are rendered in html but the 'categories'
field is escaped. Inspecting the html it results that only the `inner_html`
from `PrettyChoiceFieldRenderer` is escaped while the `outer_html` is not
which means that the html is not escaped by the template system but by the
widget renderer before. But I don't know where. That's where I am asking for
help, if anyone can spot something incorrect.
**This is the html of the 'categories' field**
_as you can see the`outer_html` is not escaped but the `inner_html` is_
<p>
<label for="id_categories_0">Categories:</label>
<div class="btn-group" data-toggle="buttons" id="id_categories">
<label class="btn btn-primary"><input id="id_categories_0" name="categories" type="checkbox" value="1" autocomplete="off" /> electronics</label><label class="btn
btn-primary"><input id="id_categories_1" name="categories" type="checkbox" value="2" autocomplete="off" /> bedroom and productivity</label> <label class="btn btn-primary"><input
id="id_categories_2" name="categories" type="checkbox" value="3" autocomplete="off" /> phone</label> <label class="btn btn-primary"><input id="id_categories_3"
name="categories" type="checkbox" value="4" autocomplete="off" /> office</label> <label class="btn btn-primary"><input id="id_categories_4" name="categories"
type="checkbox" value="6" autocomplete="off" /> Kitchen</label>
</div>
</p>
Thank you in advance
Answer: Alright, I fixed the issue. I removed the `force_text` in
output.append(format_html(
self.inner_html,
choice_value=force_text(w),
sub_widgets=''
))
so it gives
output.append(format_html(
self.inner_html,
choice_value=w,
sub_widgets=''
))
There must be a reason why Django has `force_text` in
<https://github.com/django/django/blob/master/django/forms/widgets.py#L728>
|
Run program from command line what prompts password and automatically provide password for it (cmd.exe, python)
Question: I have command line program what prompts password:
> cwrsync [email protected]:/src /cygdrive/c/dst
Output (when i run it from cmd.exe command line):
[email protected]'s password:
When i input password manually, all OK. Output:
skipping directory src
I want to provide password for it from command line or python script
automatically.
I tried:
One. From command line:
> echo pass|cwrsync -r [email protected]:/src /cygdrive/c/dst
Not working. Output:
[email protected]'s password:
Two. From python script. test.py:
import subprocess
cmd = "cwrsync -r [email protected]:/src /cygdrive/c/dst"
proc = subprocess.Popen(cmd1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, shell=True)
std1, std2 = proc.communicate("pass")
print std1print std2
Not workin. Output:
Permission denied, please try again.
Permission denied, please try again.
Permission denied (publickey,password).
rsync: connection unexpectedly closed (0 bytes received so far) [Receiver]
rsync error: unexplained error (code 255) at io.c(235) [Receiver=3.1.1]
Answer: It is common that security oriented programs ask for password on direct io
instead of reading stdin. And as :
echo pass|cwrsync -r [email protected]:/src /cygdrive/c/dst
did ask password, I presume that csrsync directly reads from console.
In that case you cannot automate it without some work and low level
programming, because you will have to simulate keyboard actions. You should
instead search the documentations, because as it looks like it uses an
underlying `ssh`, it is likely to accept a public key pair. If it accept one
without passphrase, you should be able to automate it.
|
case insensitive filtering of columns in pandas
Question: I am trying to match a string(column) in csv files in python using Python but
it does not match anything. I want the string to be match to be case
insensitive. I am quite new but this is what I tried to do
test = pd.read_csv("data.csv")
mytest= pd.DataFrame(test, columns=[re.search("[a-zA-Z1-9_]", "columnname1", re.IGNORECASE),])
print(mytest)
Any help will be highly appreciated
Answer: If I understand what you're after you can `filter` your df to only return the
columns where the name matches and make it case-insensitive:
In [298]:
df = pd.DataFrame({'columnname1':np.arange(5), 'ColumnName1':np.arange(5), 'columnname2':0, 'column name 1':0})
df
Out[298]:
ColumnName1 column name 1 columnname1 columnname2
0 0 0 0 0
1 1 0 1 0
2 2 0 2 0
3 3 0 3 0
4 4 0 4 0
In [299]:
import re
df.filter(regex=re.compile("columnname1", re.IGNORECASE))
Out[299]:
ColumnName1 columnname1
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
**EDIT**
For matching just the name without words preceding it, so matching on 'Test'
but not 'My Test':
In [52]:
df = pd.DataFrame({'Test':np.arange(5), 'ColumnName1':np.arange(5), 'My Test':0, 'My column name 1':0})
import re
df.filter(regex=re.compile(r"^Test$", re.IGNORECASE))
Out[52]:
Test
0 0
1 1
2 2
3 3
4 4
So the `^` looks for 'Test' at the beginning of the str and the `$` marks the
end of the pattern to search, there is a handy [cheat
sheet](http://regexlib.com/CheatSheet.aspx).
|
Python Flask - image proxy
Question: I'm looking for a way to get an image from the web and return it to client
(without saving to disk first). Something like that (taken from
[here](http://flask.pocoo.org/snippets/118/)):
import requests
from flask import Response, stream_with_context
@files_blueprint.route('/', methods=['GET'])
def get_image():
req = requests.get('http://www.example.com/image1.png', stream = True)
return Response(stream_with_context(req.iter_content()), content_type = req.headers['content-type'])
Above code is working but its really slow.
Any better way?
Answer: Why not use redis to cache and proxy your images? I've written a web app that
need to request images from an API server but may get 403 forbidden sometimes,
so I get the images from the API server and cache them.
* before: client -> API server:may get 403
* now with image proxy:
* not cached:
* client -> my server:don't find that
* my server -> API server:get the image,cache it,send to the client
* cached:
* client -> my server:find it and get the image from redis and send back
The difference is:
* before: client <-> API server
* now: client <-> my server <-> API server
before the client get images **directly** from API server, so may get
problems. Now, all the images point to **my server** so I can do more things.
You can also control the time to expire. With the powerful redis, you should
be easy.
I'll give you a basic example to help you understand it.
from StringIO import StringIO
from flask import send_file, Flask
import requests
import redis
app = Flask(__name__)
redis_server = redis.StrictRedis(host='localhost', port=6379)
@app.route('/img/<server>/<hash_string>')
def image(server, hash_string):
"""Handle image, use redis to cache image."""
image_url = 'http://www.example.com/blabla.jpg'
cached = redis_server.get(image_url)
if cached:
buffer_image = StringIO(cached)
buffer_image.seek(0)
else:
r = requests.get(image_url) # you can add UA, referrer, here is an example.
buffer_image = StringIO(r.content)
buffer_image.seek(0)
redis_server.setex(image_url, (60*60*24*7),
buffer_image.getvalue())
return send_file(buffer_image, mimetype='image/jpeg')
Note that the example above will get the image and cache it only when someone
visit it, so may cost some time at the first time. You can fetch the images
first by yourself. In my case(I use the way above), I'm fine with it.
The original idea is from [puppy-eyes](https://github.com/cameronmaske/puppy-
eyes). Read the source code for more details.
|
How to display the interfaces of a particular dbus bus name (/org/bluez) in python?
Question: I would like to find out what are the available objects and interfaces in the
bluez dbus bus. I wrote a simple python script to list all the bus names in
the dbus session.
import dbus
for service in dbus.SystemBus().list_names():
print(service)
However, I am only interested in the interfaces inside bluez /org/bluez. How
can a python script be written to list down the interfaces inside /org/bluez?
I am using Ubuntu 14.04 and python 2.7
Answer: You can try this:
system_bus = dbus.SystemBus()
objectManager = system_bus.get_object('org.bluez', '/')
om_iface = dbus.Interface(objectManager, 'org.freedesktop.DBus.ObjectManager')
ifacelist = om_iface.GetManagedObjects()
Where `ifacelist` is a Dict of {ObjectPath, Dictof{String, Variant}}}
|
boost python threading segmentation fault
Question: Consider the following straightforward python extension. When `start()-ed`,
`Foo` will just add the next sequential integer to a `py::list`, once a
second:
#include <boost/python.hpp>
#include <thread>
#include <atomic>
namespace py = boost::python;
struct Foo {
Foo() : running(false) { }
~Foo() { stop(); }
void start() {
running = true;
thread = std::thread([this]{
while(running) {
std::cout << py::len(messages) << std::end;
messages.append(py::len(messages));
std::this_thread::sleep_for(std::chrono::seconds(1));
}
});
}
void stop() {
if (running) {
running = false;
thread.join();
}
}
std::thread thread;
py::list messages;
std::atomic<bool> running;
};
BOOST_PYTHON_MODULE(Foo)
{
PyEval_InitThreads();
py::class_<Foo, boost::noncopyable>("Foo",
py::init<>())
.def("start", &Foo::start)
.def("stop", &Foo::stop)
;
}
Given the above, the following simple python script segfaults all the time,
never even printing anything:
>>> import Foo
>>> f = Foo.Foo()
>>> f.start()
>>> Segmentation fault (core dumped)
With the core pointing to:
namespace boost { namespace python {
inline ssize_t len(object const& obj)
{
ssize_t result = PyObject_Length(obj.ptr());
if (PyErr_Occurred()) throw_error_already_set(); // <==
return result;
}
}} // namespace boost::python
Where:
(gdb) inspect obj
$1 = (const boost::python::api::object &) @0x62d368: {<boost::python::api::object_base> = {<boost::python::api::object_operators<boost::python::api::object>> = {<boost::python::def_visitor<boost::python::api::object>> = {<No data fields>}, <No data fields>}, m_ptr = []}, <No data fields>}
(gdb) inspect obj.ptr()
$2 = []
(gdb) inspect result
$3 = 0
Why does this fail when run in a thread? `obj` looks fine, `result` gets set
correctly. Why does `PyErr_Occurred()` happen? Who sets that?
Answer: In short, there is a mutex around the CPython interpreter known as the [Global
Interpreter Lock](http://wiki.python.org/moin/GlobalInterpreterLock) (GIL).
This mutex prevents parallel operations to be performed on Python objects.
Thus, at any point in time, a max of one thread, the one that has acquired the
GIL, is allowed to perform operations on Python objects. When multiple threads
are present, invoking Python code whilst not holding the GIL results in
undefined behavior.
C or C++ threads are sometimes referred to as alien threads in the Python
documentation. The Python interpreter has no ability to control the alien
thread. Therefore, alien threads are responsible for managing the GIL to
permit concurrent or parallel execution with Python threads. With this in
mind, lets examine the original code:
while (running) {
std::cout << py::len(messages) << std::endl; // Python
messages.append(py::len(messages)); // Python
std::this_thread::sleep_for(std::chrono::seconds(1)); // No Python
}
As noted above, only two of the three lines in the thread body need to run
whilst the thread owns the GIL. One common way to handle this is to use an
[RAII](http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization)
classes to help manage the GIL. For example, with the following `gil_lock`
class, when a `gil_lock` object is created, the calling thread will acquire
the GIL. When the `gil_lock` object is destructed, it releases the GIL.
/// @brief RAII class used to lock and unlock the GIL.
class gil_lock
{
public:
gil_lock() { state_ = PyGILState_Ensure(); }
~gil_lock() { PyGILState_Release(state_); }
private:
PyGILState_STATE state_;
};
The thread body can then use explicit scope to control the lifetime of the
lock.
while (running) {
// Acquire GIL while invoking Python code.
{
gil_lock lock;
std::cout << py::len(messages) << std::endl;
messages.append(py::len(messages));
}
// Release GIL, allowing other threads to run Python code while
// this thread sleeps.
std::this_thread::sleep_for(std::chrono::seconds(1));
}
* * *
Here is a complete example based on the original code that
[demonstrates](http://coliru.stacked-crooked.com/a/ce1b6cad6c01aaf7) the
program working properly once the GIL is explicitly managed:
#include <thread>
#include <atomic>
#include <iostream>
#include <boost/python.hpp>
/// @brief RAII class used to lock and unlock the GIL.
class gil_lock
{
public:
gil_lock() { state_ = PyGILState_Ensure(); }
~gil_lock() { PyGILState_Release(state_); }
private:
PyGILState_STATE state_;
};
struct foo
{
foo() : running(false) {}
~foo() { stop(); }
void start()
{
namespace python = boost::python;
running = true;
thread = std::thread([this]
{
while (running)
{
{
gil_lock lock; // Acquire GIL.
std::cout << python::len(messages) << std::endl;
messages.append(python::len(messages));
} // Release GIL.
std::this_thread::sleep_for(std::chrono::seconds(1));
}
});
}
void stop()
{
if (running)
{
running = false;
thread.join();
}
}
std::thread thread;
boost::python::list messages;
std::atomic<bool> running;
};
BOOST_PYTHON_MODULE(example)
{
// Force the GIL to be created and initialized. The current caller will
// own the GIL.
PyEval_InitThreads();
namespace python = boost::python;
python::class_<foo, boost::noncopyable>("Foo", python::init<>())
.def("start", &foo::start)
.def("stop", &foo::stop)
;
}
Interactive usage:
>>> import example
>>> import time
>>> foo = example.Foo()
>>> foo.start()
>>> time.sleep(3)
0
1
2
>>> foo.stop()
>>>
|
How to parse complex json in python 2.7.5?
Question: I trying to list the names of my puppet classes from a Puppet Enterprise 3.7
puppet master, using Puppet's REST API.
Here is my script:
#!/usr/bin/env python
import requests
import json
url='https://ppt-001.example.com:4433/classifier-api/v1/groups'
headers = {"Content-Type": "application/json"}
data={}
cacert='/etc/puppetlabs/puppet/ssl/certs/ca.pem'
key='/etc/puppetlabs/puppet/ssl/private_keys/ppt-001.example.com.pem'
cert='/etc/puppetlabs/puppet/ssl/certs/ppt-001.example.com.pem'
result = requests.get(url,
data=data, #no data needed for this request
headers=headers, #dict {"Content-Type":"application/json"}
cert=(cert,key), #key/cert pair
verify=cacert
)
print json.dumps( result.json(), sort_keys=True, indent=4, separators=(',', ': '))
for i in result.json:
print i
Here is the error message I get when I execute the script:
Traceback (most recent call last):
File "./add-group.py", line 42, in <module>
for i in result.json:
TypeError: 'instancemethod' object is not iterable
Here is a sample of the data I get back from the REST API:
[
{
"classes": {},
"environment": "production",
"environment_trumps": false,
"id": "00000000-0000-4000-8000-000000000000",
"name": "default",
"parent": "00000000-0000-4000-8000-000000000000",
"rule": [
"and",
[
"~",
"name",
".*"
]
],
"variables": {}
},
{
"classes": {
"puppet_enterprise": {
"certificate_authority_host": "ppt-001.example.com",
"console_host": "ppt-001.example.com",
"console_port": "443",
"database_host": "ppt-001.example.com",
"database_port": "5432",
"database_ssl": true,
"mcollective_middleware_hosts": [
"ppt-001.example.com"
],
"puppet_master_host": "ppt-001.example.com",
"puppetdb_database_name": "pe-puppetdb",
"puppetdb_database_user": "pe-puppetdb",
"puppetdb_host": "ppt-001.example.com",
"puppetdb_port": "8081"
}
},
"environment": "production",
"environment_trumps": false,
"id": "52c479fe-3278-4197-91ea-9127ba12474e",
"name": "PE Infrastructure",
"parent": "00000000-0000-4000-8000-000000000000",
"variables": {}
},
.
.
.
How should I go about access the `name` key and getting the values like
`default` and `PE Infrastructure`?
I have read the other answers here on SO saying that one should use
`json.loads()` and I have tried using `parsed_json =
json.loads(result.json())` but results in this error message:
Traceback (most recent call last):
File "./add-group.py", line 38, in <module>
parsed_json = json.loads(result.json())
File "/usr/lib64/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib64/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer
Answer: `print json.dumps( result.json(), sort_keys=True, indent=4, separators=(',',
': '))` the first parameter of json.dumps must be a string or buffer, as
stated by the TypeError your getting (`TypeError: expected string or buffer`).
Your variable result is an instance of `Response`, and the method .json() will
return a dictionary. Since you're passing the result of `.json()` to
`json.dumps()`, you're getting an error. You could either just use
`result.json()` which is already a dictionary corresponding to your response,
or change your json.dumps line to `print json.dumps( result.text,
sort_keys=True, indent=4, separators=(',', ': '))` where `result.text` is your
JSON result as a string/unicode.
After the change, to access something like the `name` attribute, you could do
something like:
for item in r.json():
try:
print item['name']
expect KeyError:
print "There is no 'name' attribute"
|
Pivot Spark Dataframe
Question: I am starting to use Spark Dataframes and I need to be able to pivot the data
to create multiple columns out of 1 column with multiple rows. There is built
in functionality for that in Scalding and I believe in Pandas in python, but I
can't find anything for the new Spark Dataframe.
I assume I can write custom function of some sort that will do this but I'm
not even sure how to start, especially since I am a novice with Spark. I
anyone knows how to do this with built in functionality or suggestions for how
to write something in Scala, it is greatly appreciated.
Answer: [As mentioned](http://stackoverflow.com/a/33799008/1560062) by
[@user2000823](https://stackoverflow.com/users/2000823/user2000823) Spark
provides `pivot` function since version 1.6. General syntax looks as follows:
df
.groupBy(grouping_columns)
.pivot(pivot_column, [values])
.agg(aggregate_expressions)
Usage examples using [`nycflights13`](https://github.com/hadley/nycflights13)
and [`spark-csv`](https://github.com/databricks/spark-csv):
**Python** :
from pyspark.sql.functions import avg
flights = (sqlContext
.read
.format("com.databricks.spark.csv")
.options(inferSchema="true", header="true")
.load("flights.csv")
.na.drop())
flights.registerTempTable("flights")
sqlContext.cacheTable("flights")
gexprs = ("origin", "dest", "carrier")
aggexpr = avg("arr_delay")
flights.count()
## 336776
%timeit -n10 flights.groupBy(*gexprs ).pivot("hour").agg(aggexpr).count()
## 10 loops, best of 3: 1.03 s per loop
**Scala** :
val flights = sqlContext
.read
.format("com.databricks.spark.csv")
.options(Map("inferSchema" -> "true", "header" -> "true"))
.load("flights.csv")
flights
.groupBy($"origin", $"dest", $"carrier")
.pivot("hour")
.agg(avg($"arr_delay"))
**Performance considerations** :
Generally speaking pivoting is an expensive operation.
* if you can try to provide `values` list:
vs = list(range(25))
%timeit -n10 flights.groupBy(*gexprs ).pivot("hour", vs).agg(aggexpr).count()
## 10 loops, best of 3: 392 ms per loop
* [in some cases it proved to be beneficial](http://stackoverflow.com/q/35427812/1560062) to `repartition` and / or pre-aggregate the data
|
Python - efficiently find where something would land in a sorted list?
Question: I have a list:
x = ['c', 'a', 'e']
I can sort this list:
x_sorted = sorted(x)
`x_sorted` is now `['a', 'c', 'e']`
Now let's say I have a new variable `y = 'd'`
I want to find out where in `x_sorted` this new variable would fall. In this
example the new variable `y` contains the string `'d'` so it would be placed
as `['a', 'c', 'd', 'e']` in the index 2 of the list. I desire to find out
this index number as efficiently as possible (since I have to repeat this
process many times).
Here is a function I wrote which does the task very simply:
def f(x_sorted, y):
new_list = x_sorted[:] + [y]
return sorted(new_list).index(y)
This gives me the correct answer.
I am wondering if there is a better more efficient way of doing this, as `f`
will be called 100,000+ times.
Thanks in advance!
Answer: You can use [bisect](https://docs.python.org/2/library/bisect.html)
from bisect import bisect
l = ['a', 'c', 'e']
print(bisect(l,"d"))
2
To add it to the list:
from bisect import insort
l = ['a',"b", 'c', 'e']
insort(l, "d")
print(l)
insort(l, "f")
print(l)
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c', 'd', 'e', 'f']
If you want a faster insert you could use a
[blist](https://pypi.python.org/pypi/blist/?) where maintaining a sorted list
with insort is:
O(log**2 n) vs O(n)
from bisect import insort
from blist import blist
b = blist(["a", "b", "c", "e"])
insort(b, "f")
insort(b, "d")
print(b)
blist(['a', 'b', 'c', 'd', 'e', 'f'])
There is also a
[blist.sortedlist](http://stutzbachenterprises.com/blist/sortedlist.html#blist.sortedlist)
list where you can use
[.add](http://stutzbachenterprises.com/blist/sortedlist.html#blist.sortedlist.L.add):
from blist import sortedlist
l = ['b',"a", 'c', 'e']
b = sortedlist(l)
b.add("f")
print(b)
sortedlist(['a', 'b', 'c', 'e', 'f'])
There is also a
[sortedcontainers](http://www.grantjenks.com/docs/sortedcontainers/) library
that has a
[sortedlist](http://www.grantjenks.com/docs/sortedcontainers/sortedlist.html)
implementation.
|
How to force Pillow to resize an image to an arbitrary size?
Question: I need to resize images, from all different sizes to 144x144.
All sizes: from 968x565, from 25x48, from 400x400, etc. Don't know the input.
I'm using Pillow library from Python. I don't mind losing aspect ratio.
Problem is: when using `resize` method, some images get complete random sizes.
Not always, but just some of them don't respect the arbitrary size of 144x144
I gave to the method. [Here is a sample](http://imgur.com/DdxullE).
I tried resizing these images using Mac OS X Yosemite's Preview and it works
flawlessly. What do I need to do in Pillow to force 144x144 size and work at
least like Preview in mac?
I can't post the whole code, but the snippet that resizes is:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PIL import Image
im = Image.open('canvas_wheat.jpg')
im.resize((144, 144), Image.ANTIALIAS)
im.save('144.jpg', optimize=True, quality=20)
Answer: The problem you are getting there is that the `resize` method returns a _new_
image object, you are not storing anywhere. The original image `im` is the
same that has been loaded.
Check the examples on this interactive session:
>>> from PIL import Image
>>> img = Image.open("image.jpg")
>>> img.size
(952, 804)
>>> img2 = img.resize((144,144), Image.ANTIALIAS)
>>> img.size
(952, 804)
>>> img2.size
(144, 144)
>>>
|
Comparing python -V output for Python version checking in bash
Question: I am creating an install script where I would like to compare the version of
installed default Python with the version I need to have running. Currently
here is my code:
#!/bin/bash
PYTHON="$(python -V)"
if [[ "$PYTHON = 'Python 2.7.6' ]]
then echo "Python is installed."
else echo "Python is not installed."
fi
The response I keep getting is that Python is not installed, but that is the
output when I type in the command python -V.
Any help is greatly appreciated. Thank you in advance.
Answer: It seems that when you run `python -V`, it prints the version to _stderr_ ,
not to stdout. So, changing your attempt to capture the output into a variable
to this:
PYTHON=$(python -V 2>&1)
should do the trick. Another alternative, which tends to include additional
information about build dates, compilers, etc. would be:
python -c 'import sys; print sys.version'
or, as suggested by @chepner:
python -c 'import sys; print sys.version_info'
Both of these would require a little additional parsing to get the specific
information you want/need, though.
|
raise child_exception , OSError: [Errno 2] No such file or directory
Question:
import sys,os
import subprocess
import pdb
pdb.set_trace()
findCMD = 'find . -name "pcapdump0"'
print os.getcwd()
print findCMD
out = subprocess.Popen(findCMD,stdout=subprocess.PIPE)
(stdout, stderr) = out.communicate()
filelist = stdout.decode().split()
print filelist
I am getting this error
Traceback (most recent call last):
File "generatepcap.py", line 10, in <module>
out = subprocess.Popen(findCMD,stdout=subprocess.PIPE)
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Answer: Simply means what it says: popen can't find the command you specified, because
you did not split the string.
|
Why does dropna() not work?
Question: System: Spark 1.3.0 (Anaconda Python dist.) on Cloudera Quickstart VM 5.4
Here's a Spark DataFrame:
from pyspark.sql import SQLContext
from pyspark.sql.types import *
sqlContext = SQLContext(sc)
data = sc.parallelize([('Foo',41,'US',3),
('Foo',39,'UK',1),
('Bar',57,'CA',2),
('Bar',72,'CA',3),
('Baz',22,'US',6),
(None,75,None,7)])
schema = StructType([StructField('Name', StringType(), True),
StructField('Age', IntegerType(), True),
StructField('Country', StringType(), True),
StructField('Score', IntegerType(), True)])
df = sqlContext.createDataFrame(data,schema)
`data.show()`
Name Age Country Score
Foo 41 US 3
Foo 39 UK 1
Bar 57 CA 2
Bar 72 CA 3
Baz 22 US 6
null 75 null 7
However neither of these work!
df.dropna()
df.na.drop()
I get this message:
>>> df.show()
Name Age Country Score
Foo 41 US 3
Foo 39 UK 1
Bar 57 CA 2
Bar 72 CA 3
Baz 22 US 6
null 75 null 7
>>> df.dropna().show()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/spark/python/pyspark/sql/dataframe.py", line 580, in __getattr__
jc = self._jdf.apply(name)
File "/usr/lib/spark/python/lib/py4j-0.8.2.1-src.zip/py4j/java_gateway.py", line 538, in __call__
File "/usr/lib/spark/python/lib/py4j-0.8.2.1-src.zip/py4j/protocol.py", line 300, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o50.apply.
: org.apache.spark.sql.AnalysisException: Cannot resolve column name "dropna" among (Name, Age, Country, Score);
at org.apache.spark.sql.DataFrame$$anonfun$resolve$1.apply(DataFrame.scala:162)
at org.apache.spark.sql.DataFrame$$anonfun$resolve$1.apply(DataFrame.scala:162)
at scala.Option.getOrElse(Option.scala:120)
at org.apache.spark.sql.DataFrame.resolve(DataFrame.scala:161)
at org.apache.spark.sql.DataFrame.col(DataFrame.scala:436)
at org.apache.spark.sql.DataFrame.apply(DataFrame.scala:426)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:231)
at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:379)
at py4j.Gateway.invoke(Gateway.java:259)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:207)
at java.lang.Thread.run(Thread.java:745)
Has anybody else experienced this problem? What's the workaround? Pyspark
seems to thing that I am looking for a column called "na". Any help would be
appreciated!
Answer: **tl;dr** The methods `na` and `dropna` are only available since Spark 1.3.1.
Few mistakes you made:
1. `data = sc.parallelize([....('',75,'', 7 )])`, you intended to use `''` to represent `None`, however, it's just a String instead of null
2. `na` and `dropna` are both methods on dataFrame class, therefore, you should call it with your `df`.
Runnable Code:
data = sc.parallelize([('Foo',41,'US',3),
('Foo',39,'UK',1),
('Bar',57,'CA',2),
('Bar',72,'CA',3),
('Baz',22,'US',6),
(None, 75, None, 7)])
schema = StructType([StructField('Name', StringType(), True),
StructField('Age', IntegerType(), True),
StructField('Country', StringType(), True),
StructField('Score', IntegerType(), True)])
df = sqlContext.createDataFrame(data,schema)
df.dropna().show()
df.na.drop().show()
|
Calculating the square numbers within a range (python)
Question: I want to be able to execute the following code:
for i in Squares(5, 50):
print(i)
Now this is very easy to implement using a loop, however I want to use an
iterator.
So I have defined the following class:
import math
class Squares(object):
def __init__(self, start, stop):
self.start = start
self.stop = stop
def __iter__(self):
return self
def __next__(self):
start = self.start
stop = self.stop
squareroot = math.sqrt(start)
if self.start > self.stop:
raise StopIteration
if squareroot == math.ceil(squareroot):
start += 1
But at the moment this is returning `None` an infinite amount of times. This
means the none must be because the `StopIteration` is being executed even when
it shouldn't. I think my `if squareroot == math.ceil(squareroot):` condition
is correct because I tested it separately, but I can't figure out what to
change to get the output I want. Any help is appreciated.
EDIT: For a code such as:
for i in Squares(4, 16):
print(i)
I would expect the output to be:
4
9
16
Answer: Try creating a generator function:
from math import sqrt, ceil
def Squares(start, stop):
for i in range(start, stop+1):
sqrti = sqrt(i)
if sqrti == ceil(sqrti):
yield i
And then loop it:
for i in Squares(4, 20):
print i,
which prompts:
4 9 16
EDIT: edited to match the square definition, not the previous square power
(sorry :P). Added +1 to the range to match the question example of the OP.
|
Python - Create multidimensional array like in R
Question: I'm trying to create a multidimensional array of 5 dimensions like the "array"
function in R but in Python.
Here is my array function in R
myarray <- array(0,dim=c(A,B,C,D,E))
A=10, B=5, C=22, D=4 and E=2.
You can find an R image with the expected array as output in the following
link
<https://www.dropbox.com/sh/bkp10w62bb2xsqg/AABsFh5qv_7E5wLbg_Iux3jka?dl=0>
Thanks.
Raúl
Answer:
import numpy as np
myshape = (10,5,22,4,2)
myarray = np.zeros(myshape)
|
pycharm console unicode to readable string
Question: studying python with [this
tutorial](http://www.youtube.com/watch?v=ZxiJ92-4Qys&index=5&list=WL)
The problem is when i trying to get cyrillic characters i get unicode in
pycharm console.

import requests
from bs4 import BeautifulSoup
import operator
import codecs
def start(url):
word_list = []
source_code = requests.get(url).text
soup = BeautifulSoup(source_code)
for post_text in soup.findAll('a', {'class': 'b-tasks__item__title js-set-visited'}):
content = post_text.string
words = content.lower().split()
for each_word in words:
word_list.append(each_word)
clean_up_list(word_list)
def clean_up_list(word_list):
clean_word_list = []
for word in word_list:
symbols = "!@#$%^&*()_+{}|:<>?,./;'[]\=-\""
for i in range(0, len(symbols)):
word = word.replace(symbols[i], "")
if len(word) > 0:
clean_word_list.append(word)
create_dictionary(clean_word_list)
def create_dictionary(clean_word_list):
word_count = {}
for word in clean_word_list:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
for key, value in sorted(word_count.items(), key=operator.itemgetter(1)):
print(key, value)
When i am changing **print(key, value)** to **print(key.decode('utf8'),
value)** i am getting "UnicodeEncodeError: 'ascii' codec can't encode
characters in position 0-7: ordinal not in range(128)"

start('<https://youdo.com/tasks-all-opened-all-moscow-1>') There is some
suggestion on the internet about changing encoding in some files - don't
really get it. Can't i read it in console? OSX
**UPD** key.encode("utf-8") 
Answer: UTF-8 is sometimes painful. I created a file with a line in Latin caracters
and another one with Russian ones. The following code:
# encoding: utf-8
with open("testing.txt", "r", encoding='utf-8') as f:
line = f.read()
print(line)
outputs in PyCharm

Note the two `encoding` entries
Since you are getting data from a web page, you must make sure that you use
the right encoding as well. The following code
# encoding: utf-8
r = requests.get('http://www.pravda.ru/')
r.encoding = 'utf-8'
print(r.text)
outputs in PyCharm as

Please note that you must specifically set the encoding to match the one of
the page.
|
import flask on wsgi virtual host fails
Question: Having the following directory structure and setup:
.
├── app
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── static
│ ├── templates
│ │ ├── base.html
│ │ └── index.html
│ ├── views.py
│ └── views.pyc
├── flask
├── myapp.wsgi
├── run.py
├── run.pyc
└── tmp
**myapp.wsgi**
#!/usr/bin/python
import sys, os, logging
logging.basicConfig(stream=sys.stderr)
#sys.path.insert(0,"/var/www/otherStuff/myApp/")
sys.path.insert(0, os.path.dirname(__file__))
#from app import app
from app import app as application
application.secret_key = 'xyz'
if __name__ == '__main__':
app.run(host='0.0.0.0',debug=True)
**__init__.py**
from flask import Flask
app = Flask(__name__)
from app import views
**vhost.conf**
<VirtualHost *:80>
ServerName local.myapp.com
WSGIScriptAlias / /var/www/otherStuff/myApp/myappwsgi
<Directory /var/www/otherStuff/myApp/app>
Order allow,deny
Allow from all
</Directory>
#Alias /static /var/www/otherStuff/myApp/static
#<Directory /var/www/otherStuff/myApp/static>
# Order allow,deny
# Allow from all
#</Directory>
ErrorLog /var/www/logs/myApp-error.log
LogLevel warn
CustomLog /var/www/logs/myApp-access.log combined
</VirtualHost>
I can't seem to figure out, why the `Flask` dependency is not loaded and
therefore, it fails to run
mod_wsgi (pid=19668): Target WSGI script '/var/www/otherStuff/myApp/myapp.wsgi' cannot be loaded as Python module., referer: http://local.myapp.com/
mod_wsgi (pid=19668): Exception occurred processing WSGI script '/var/www/otherStuff/myApp/myapp.wsgi'., referer: http://local.myapp.com/
Traceback (most recent call last):, referer: http://local.myapp.com/
File "/var/www/otherStuff/myApp/myapp.wsgi", line 8, in <module>, referer: http://local.myapp.com/
from app import app as application, referer: http://local.myapp.com/
File "/var/www/otherStuff/myApp/app/__init__.py", line 1, in <module>, referer: http://local.myapp.com/
from flask import Flask, referer: http://local.myapp.com/
ImportError: No module named flask, referer: http://local.myapp.com/
**UPDATE**
`flask` is the virtualenv:
flask/
├── bin
├── include
├── lib
├── lib64 -> /home/alexb/www/otherStuff/faqColab/flask/lib
├── local
└── pyvenv.cfg
Answer: You need to tell mod_wsgi how to find packages in your virtual environment.
I'm not positive I have your folder structure exactly correct, but it should
be something like this.
WSGIPythonPath /var/www/otherStuff/myApp:/var/www/otherStuff/myApp/flask/lib/python2.7/site-packages
|
How to increment global variable from function in python
Question: I'm stuck by a simple increment function like
from numpy import *
from pylab import *
## setup parameters and state variables
T = 1000 # total time to simulate (msec)
dt = 1 # simulation time step (msec)
time = arange(0, T+dt, dt) # time array
Vr = -70 #reset
El = -70
## LIF properties
Vm = zeros(len(time)) # potential (V) trace over time
Rm = 10 # resistance (mOhm)
tau_m = 10 # time constant (msec)
Vth = -40 # spike threshold (V)
## Input stimulus
I = 3.1 # input current (nA)
Vm[0] = -70
Fr = 0
## iterate over each time step
def func(Ie, Vm, Fr):
for i, t in enumerate(time):
if i == 0:
Vm[i] = -70
else:
Vm[i] = Vm[i-1] + (El- Vm[i-1] + Ie*Rm) / tau_m * dt
if Vm[i] >= Vth:
Fr += 1
Vm[i] = El
return
Ie = 3.1
func( Ie, Vm, Fr)
print Fr
## plot membrane potential trace
plot(time, Vm)
title('Leaky Integrate-and-Fire')
ylabel('Membrane Potential (mV)')
xlabel('Time (msec)')
ylim([-70,20])
show()
Why after the func is called, the Fr is still 0?
I know it's simple but I have wasted long time on this
Thank you
Answer: You have two Fr variables in different scopes
Fr = 0
Is outside of your function, thus never changed.
Fr += 1
Is inside a function and will be incremented, but this is a different
variable.
Here is the solution (one of the possible ones):
def func(Ie, Vm, Fr):
for i, t in enumerate(time):
if i == 0:
Vm[i] = -70
else:
Vm[i] = Vm[i-1] + (El- Vm[i-1] + Ie*Rm) / tau_m * dt
if Vm[i] >= Vth:
Fr += 1
Vm[i] = El
return Fr
Then, just do
Fr = func(Ie, Vm, Fr)
One more tip. If your `Fr` variable is always 0 by default you can do this:
def func(Ie, Vm, Fr=0):
when defining the function, and pass the third paramenter only when you need
something different that 0.
|
Exporting plain text header and image to Excel
Question: I am fairly new to Python, but I'm getting stuck trying to pass an image file
into a header during the `DataFrame.to_excel()` portion of my file.
Basically what I want is a picture in the first cell of the Excel table,
followed by a couple of rows (5 to be exact) of text which will include a date
(probably from `datetime.date.today().ctime()` if possible).
I already have the code to output the table portion as:
mydataframe.to_excel(my_path_name, sheet_name= my_sheet_name, index=False, startrow=7,startcol=0)
Is there a way to output the image and text portion directly from Python?
UPDATE:
For clarity, `mydataframe` is exporting the meat and potatoes of the worksheet
(data rows and columns). I already have it starting on row 7 of the worksheet
in Excel. The header portion is the trouble spot.
Answer: I found the solution and thanks for all of the help.
The simple answer is to use the `xlsxwriter` package as the engine. In other
words assume that the image is saved at the path `/image.png`. Then the code
to insert the data into the excel file with the image located at the top of
the data would be:
# Importing packages and storing string for image file
import pandas as pd
import xlsxwriter
import numpy as np
image_file = '/image.png'
# Creating a fictitious data set since the actual data doesn't matter
dataframe = pd.DataFrame(np.random.rand(5,2),columns=['a','b'])
# Opening the xlsxwriter object to a path on the C:/ drive
writer = pd.ExcelWriter('C:/file.xlsx',engine='xlsxwriter')
dataframe.to_excel(writer,sheet_name = 'Arbitrary', startrow=3)
# Accessing the workbook / worksheet
workbook = writer.book
worksheet = writer.sheets['Arbitrary']
# Inserting the image into the workbook in cell A1
worksheet.insert_image('A1',image_file)
# Closing the workbook and saving the file to the specified path and filename
writer.save()
And now I have an image on the top of my excel file. Huzzah!
|
Python 3: AttributeError: 'module' object has no attribute '__path__' using urllib in terminal
Question: My code is runnning perfectly in PyCharm, but I have error messages while
trying to open it in terminal. What's wrong with my code, or where I made
mistakes?
import urllib.request
with urllib.request.urlopen('http://python.org/') as response:
html = response.read()
print(html)
Output from terminal:
λ python Desktop\url1.py
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 2218, in _find_and_load_unlocked
AttributeError: 'module' object has no attribute '__path__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "Desktop\url1.py", line 1, in <module>
import urllib.request
File "C:\Users\Przemek\Desktop\urllib.py", line 1, in <module>
import urllib.request
ImportError: No module named 'urllib.request'; 'urllib' is not a package
Answer: You called a file `C:\Users\Przemek\Desktop\urllib.py`, you need to rename it.
You are importing from that not the actual module. rename
`C:\Users\Przemek\Desktop\urllib.py` and remove any
`C:\Users\Przemek\Desktop\urllib.pyc`.
It is not the file you are running but you have the file in the same directory
so python checks the current directory first hence the error.
|
Write a map with key as int to json in scala using json4s
Question: I am trying to write a `Map` in key as `int` to json string but I am not able
to do so:
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.JsonDSL._
object MyObject {
def main(args: Array[String]) {
// Works fine
//val myMap = Map("a" -> List(3,4), "b" -> List(7,8))
// Does not work
val myMap = Map(4 -> Map("a" -> 5))
val jsonString = pretty(render(myMap))
println(jsonString)
}
I am receiving the following error:
[error] /my_stuff/my_file.scala:14: overloaded method value render with alternatives:
[error] (value: org.json4s.JValue)org.json4s.JValue <and>
[error] (value: org.json4s.JValue)(implicit formats: org.json4s.Formats)org.json4s.JValue
[error] cannot be applied to (scala.collection.immutable.Map[Int,scala.collection.immutable.Map[String,Int]])
[error] val jsonString = pretty(render(myMap))
[error] ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed
I vaguely understand the error message, it looks like render expects JValue as
an input, and I am not providing it, but I don't the first case either, and
the code works as I expect.
How do I write such map to json string?
**Edit:** My source of confusion
I am mostly a python programmer, and in python
In [1]: import json
In [2]: wrong = {2: 5}
In [3]: with open("wrong.json") as f:
...: json.dump(wrong, f)
works perfectly fine, of course python stringifies the `2`.
Answer: I think it is an expected result. If you check the [json
specification](http://json.org/) you will see that you need to use strings for
the names of the elements.
So I am afraid you will need something like:
val myMap = Map("4" -> Map("a" -> 5))
|
threading tkinter add label in frame during function execution
Question: I write a pipeline for a lab, so I know it is impossible to insert a "console"
in a GUI, so I made it with a Frame and I put label on it.
But the problem is, I am a beginner in threading, and I don't know how to use
it to put my label into my frame after a function execution in a loop.
So this is my code (python 3.x) :
########
# IMPORTS #
########
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import *
from tkinter.messagebox import *
import os
import glob
from datetime import date, time, datetime
#########
# FUNCTION #
#########
def OneFile(path1,DB,path2,seq,seq2,typ,path3):
"""
This function is very long, take all the sequences of the input file and BLAST it to the Library DATABASE
path : path to the library databse
DB : library database name
path2 : path of the file with the query sequences
seq : name of the file with the query sequences append with a job ID
seq2 : name of the file with the query sequence
Typ : Nucleotide or Proteine
"""
from datetime import date, time, datetime
import subprocess
import platform
import time
OS = platform.system()
if OS == 'Linux' or OS == 'Darwin':
pathLibrary = path1+'/'
pathSequence = path2+'/'
pathFolder = path3+'/'
if OS == 'Windows':
pathLibrary = path1+'\\'
pathSequence = path2+'\\'
if typ not in [(1,1),(2,2),(1,2),(2,1)]:
showerror('Error : Missing Type !', "You do not choose your type\n(nucleotides or proteins)")
else:
library = DB
if os.path.isfile(pathLibrary+library) != True:
showerror('Error : Missing File !', "You must choose a Library Database file")
else:
if os.path.isfile(pathSequence+seq2) != True:
showerror('Error : Missing File !', "You must choose your sequence file")
else:
if typ == (1,1):
typ = "blastn"
if typ == (2,2):
typ = "blastp"
if typ == (1,2):
typ = "blastx"
if typ == (2,1):
typ = "tblastn"
if OS == 'Linux' or OS == 'Darwin':
t0 = time.time()
query = str(seq2)
blast = str(seq)+'_Blast.txt'
seqs = str(seq)+'_seqs.txt'
subprocess.call(typ+" -query "+pathSequence+query+" -db "+pathLibrary+library+" -evalue 1e-10 -out "+pathFolder+blast, shell=True)
subprocess.call("grep '\(Sbjct\|>\)' "+pathFolder+blast+" > "+pathFolder+seqs, shell=True)
t1 = time.time()
print('Job finish in '+str(round(t1-t0,2))+' seconds')
if OS == 'Windows':
t0 = time.time()
query = str(seq2)
blast = str(seq)+'_Blast.txt'
seqs = str(seq)+'_seqs.txt'
subprocess.call(typ+' -query '+pathSequence+query+' -db '+pathLibrary+library+' -evalue 1e-10 -out '+pathSequence+blast, shell=True)
print('Fichier n° '+str(1)+' '+str(seq2))
subprocess.Popen('findstr "Sbjct >" '+pathSequence+blast+' > '+pathSequence+seqs, shell=True)
t1 = time.time()
print('Job finish in '+str(round(t1-t0,2))+' seconds')
#######
# CLASS #
#######
class GraphicalUserInterface():
#principal application
def __init__(self):
#constructor
self.fen = Tk()
self.fen.title("Starch Enzyme Pipeline")
#first label
self.label1 = Label(self.fen, text="Folder with your set(s) : ")
self.label1.grid(row=0, columnspan=2, sticky="W")
#first button
self.browse1 = Button(self.fen)
self.browse1.config(text="Browse",command=self.folderPath)
self.browse1.grid(row=1,column=0, sticky="W")
#label to show the path
self.varLabel1 = StringVar()
self.pathLabel1 = Label(self.fen, textvariable=self.varLabel1, relief=SUNKEN)
self.pathLabel1.grid(row=1,column=1, sticky="EW")
#second title
self.label2 = Label(self.fen, text="Folder with your library database(s) ")
self.label2.grid(row=2,column = 0, columnspan=2 , sticky="W")
#second button
self.browse2 = Button(self.fen)
self.browse2.config(text="Browse",command=self.folderPath2)
self.browse2.grid(row=3,column=0, sticky="W")
#label to show the path for database
self.varLabel2 = StringVar()
self.pathLabel2 = Label(self.fen, textvariable=self.varLabel2, relief=SUNKEN)
self.pathLabel2.grid(row=3,column=1, sticky = "EW")
#Frame wrappe listBox and other
self.frameListBoxAll = Frame(self.fen)
self.frameListBoxAll.grid(row=6,columnspan=2)
#list box label
self.labListBox1 = Label(self.frameListBoxAll, text="Your sets :",padx=10)
self.labListBox1.grid(row=0,column=0)
self.labListBox2 = Label(self.frameListBoxAll, text="Your library database :",padx=10)
self.labListBox2.grid(row=0,column=1)
#frame with listbox1
self.frame1 = Frame(self.frameListBoxAll, bd=2, relief=SUNKEN)
self.frame1.grid(row=1,column=0)
#frame with listbox1
self.frame2 = Frame(self.frameListBoxAll, bd=2, relief=SUNKEN)
self.frame2.grid(row=1,column=1)
#scrollbar listbox1
self.scrollbar1 = Scrollbar(self.frame1)
self.scrollbar1.grid(row=0,column=1, sticky="NS")
self.scrollbar2 = Scrollbar(self.frame2)
self.scrollbar2.grid(row=0,column=3, sticky="NS")
self.scrollbar3 = Scrollbar(self.frame1, orient=HORIZONTAL)
self.scrollbar3.grid(row=1,column=0, sticky="WE")
self.scrollbar4 = Scrollbar(self.frame2, orient=HORIZONTAL)
self.scrollbar4.grid(row=1,column=2, sticky="WE")
#liste box
self.listeBox1 = Listbox(self.frame1, selectmode=EXTENDED, exportselection=0, yscrollcommand=self.scrollbar1.set, xscrollcommand=self.scrollbar3.set)
self.listeBox1.grid(row=0,column = 0)
self.scrollbar1.config(command=self.listeBox1.yview)
self.scrollbar3.config(command=self.listeBox1.xview)
#liste box2
self.listeBox2 = Listbox(self.frame2, selectmode=EXTENDED, exportselection=0, yscrollcommand=self.scrollbar2.set, xscrollcommand=self.scrollbar4.set)
self.listeBox2.grid(row=0,column = 2)
self.scrollbar2.config(command=self.listeBox2.yview)
self.scrollbar4.config(command=self.listeBox2.xview)
#radioboutton list box 1
self.var = IntVar()
for item in [1,2]:
if item == 1:
self.rb = Radiobutton(self.frameListBoxAll, text='Nucleotides',value=item,variable=self.var)
self.rb.grid(row=2, column=0)
if item == 2:
self.rb = Radiobutton(self.frameListBoxAll, text='Proteins',value=item,variable=self.var)
self.rb.grid(row=3, column=0)
#radioboutton list box 2
self.var2 = IntVar()
for item in [1,2]:
if item == 1:
self.rb2 = Radiobutton(self.frameListBoxAll, text='Nucleotides',value=item,variable=self.var2)
self.rb2.grid(row=2, column=1)
if item == 2:
self.rb2 = Radiobutton(self.frameListBoxAll, text='Proteins',value=item,variable=self.var2)
self.rb2.grid(row=3, column=1)
#variables
self.path1 = str()
self.path2 = str()
self.path3 = str()
#RUN Buttun
self.runbutton = Button(self.fen, text="RUN",command=self.start_foo_thread).grid(row=7,column=0,columnspan=2)
#FRAME CONSOLE
self.console = Frame(self.fen)
self.console.config(relief=SUNKEN, bg="black", height=200, width=400)
self.console.grid(row=8, columnspan=10)
self.console.grid_propagate(False) #to block the size of the frame
#QUIT BUTTON
self.quitButton = Button(self.fen)
self.quitButton.config(text="QUIT", command=self.fen.destroy)
self.quitButton.grid(row=100,column=0)
def folderPath(self):
path = askdirectory(title='Choose your set folder')
self.varLabel1.set(path)
self.listeBox1.delete(0, END)
for filename in sorted(glob.glob(path+'/*')):
if os.path.isfile(filename):
#stockage of path
self.path1 = os.path.split(filename)[0]
name = os.path.split(filename)[1]
self.listeBox1.insert(END, name)
def folderPath2(self):
path = askdirectory(title="Choose your library database folder")
self.varLabel2.set(path)
self.listeBox2.delete(0, END)
for filename in sorted(glob.glob(path+'/*')):
if os.path.isfile(filename):
#stockage of path
self.path2 = os.path.split(filename)[0]
name = os.path.split(filename)[1]
self.listeBox2.insert(END, name)
def run(self):
self.fen.mainloop()
def createJobName():
job = str(datetime.now())
job = job.replace(" ","-")
return job
def typeNP(self):
liste = []
#selection of query files
valListBox1 = [self.listeBox1.get(idx) for idx in self.listeBox1.curselection()]
#selection of database file
valListBox2 = [self.listeBox2.get(idx) for idx in self.listeBox2.curselection()]
#selection of sequence type
typ = (self.var.get(),self.var2.get())
# loop
for i in range(len(valListBox2)):
job = GraphicalUserInterface.createJobName()
path1 = self.path2
path2 = self.path1
DB = valListBox2[i]
path3 = os.getcwd()+"/"+DB+job
if os.path.isdir(DB+job) == True:
showwarning('Warning', "The folder already exist \n or they are no folder name !\nChange or get the folder name")
else:
os.mkdir(DB+job)
for filename in valListBox1:
seq = filename+job
seq2 = filename
#stock data for OneFile function
liste.append([path1,DB,path2,seq,seq2,typ,path3])
return liste
def start_foo_thread(self):
liste = self.typeNP()
for i in range(len(liste)):
global foo_thread
import threading
print('Fichier n°'+str(i+1)+' '+str(liste[i][4]))
stringLabel = Label(self.console,text='Fichier n°'+str(i+1)+' '+str(liste[i][4]),bg='black', fg='white')
stringLabel.grid(row=i,sticky="W")
foo_thread = threading.Thread(target=OneFile(liste[i][0],liste[i][1],liste[i][2],liste[i][3],liste[i][4],liste[i][5],liste[i][6]))
foo_thread.daemon = True
foo_thread.start()
#########
# AUTORUN #
#########
if __name__ == '__main__':
app = GraphicalUserInterface()
app.run()
The problem is when the loop began in:
def start_foo_thread(self):
liste = self.typeNP()
for i in range(len(liste)):
With the print function, I see the function run, but the label does not go in
the frame when the iteration finishes. When the loops are completed, I see my
label in the frame. What is the correct code to have my label in my frame at
the same time my function runs in my loop?
Answer: You sometimes have to manually update the widget. You have posted too much
code to wade through, so this simple example should show the problem. Run as
is, the labels don't show up until the function returns. Run with
update_idletasks() uncommented does what I think you want. Also note that the
program stops until the call to subprocess returns.
import sys
if sys.version_info[0] < 3:
import Tkinter as tk ## Python 2.x
else:
import tkinter as tk ## Python 3.x
class GraphicalUserInterface():
def __init__(self):
#constructor
self.fen = tk.Tk()
self.fen.title("Starch Enzyme Pipeline")
self.console=tk.Frame(self.fen)
self.console.grid()
self.liste=["one", "two", "three"]
tk.Button(self.fen, text="Exit", command=self.fen.quit).grid(row=1)
self.start_foo_thread()
self.fen.mainloop()
def start_foo_thread(self):
for ctr in range(len(self.liste)):
lit='Fichier n %s' % (ctr)
print(lit)
stringLabel = tk.Label(self.console, text=lit,
bg='black', fg='white')
stringLabel.grid(row=ctr,sticky="W")
##self.console.update_idletasks()
print("Waiting 2 seconds")
self.fen.after(2000) ## wait 2 seconds to show effect
print("Return from function")
if __name__ == '__main__':
app = GraphicalUserInterface()
|
python requests handle error 302?
Question: I am trying to make a http request using `requests` library to the redirect
url (in response headers-Location). When using Chrome inspection, I can see
the response status is 302.
However, in python, `requests` always returns a 200 status. I added the
`allow_redirects=False`, but the status is still always 200.
* The url is `https://api.weibo.com/oauth2/authorize?redirect_uri=http%3A//oauth.weico.cc&response_type=code&client_id=211160679`
* the first line entered the test account: `[email protected]`
* the second line entered the password: `112358`
and then click the first button to login.
My Python code:
import requests
user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36'
session = requests.session()
session.headers['User-Agent'] = user_agent
session.headers['Host'] = 'api.weibo.com'
session.headers['Origin']='https://api.weibo.com'
session.headers['Referer'] ='https://api.weibo.com/oauth2/authorize?redirect_uri=http%3A//oauth.weico.cc&response_type=code&client_id=211160679'
session.headers['Connection']='keep-alive'
data = {
'client_id': api_key,
'redirect_uri': callback_url,
'userId':'[email protected]',
'passwd': '112358',
'switchLogin': '0',
'action': 'login',
'response_type': 'code',
'quick_auth': 'null'
}
resp = session.post(
url='https://api.weibo.com/oauth2/authorize',
data=data,
allow_redirects=False
)
code = resp.url[-32:]
print code
Answer: You are probably getting an API error message. Use `print resp.text` to see
what the server tells you is wrong here.
Note that you can always inspect `resp.history` to see if there were any
redirects; if there were any you'll find a list of response objects.
Do not set the `Host` or `Connection` headers; leave those to `requests` to
handle. I doubt the `Origin` or `Referer` headers here needed either. Since
this is an _API_ , the `User-Agent` header is probably also overkill.
|
get call stack for Model Classes in Django
Question: In Django, I would like to get call stacks of classes in Model; on call, and
log them. The Django Model uses _QuerySet API_ to access objects of the Model
class.
Say, we have defined Model `class Abc`, and it is called by other django apps
using _QuerySet API_.
For example -
Abc.objects.filter()
Abc.objects.get()
,etc.
I would like to add a traceback whenever that particular Model `class Abc` is
called via _QuerySetAPI_ .
Is traceback a correct approach here? Should I use something else?
I am using Python 2.7, Vegrant, Django 1.4.20 on Mac.
Answer: If I understood you right, this is my solution. Any call to queryset api
prints caller stack.
import inspect
from django.db import models
from django.db.models import Manager
class LogManager(Manager):
def get_queryset(self):
print inspect.stack() # in py3.4 the [2] element was the actual caller outside Manager so I used [2:]
return super(LogManager, self).get_queryset()
class Abc(models.Model):
objects = LogManager()
UPD.: For all django versions < 1.5 you should override `get_query_set`:
class LogManager(Manager):
def get_query_set(self):
print inspect.stack()
return super(LogManager, self).get_query_set()
|
Can this python code be more efficient?
Question: I have written some code to find how many substrings of a string are anagram
pairs. The function to find `anagram(anagramSolution)` is of complexity O(N).
The substring function has complexity less than N square. But, this code here
is the problem. Can it be more optimized?
for i in range(T):
x = raw_input()
alist = get_all_substrings(x)
for k, j in itertools.combinations(alist,2):
if(len(k) == len(j)):
if(anagramSolution(k,j)):
counter +=1
counterlist.append(counter)
counter = 0
The `alist` can have thousands of items (subsets). **The main problem is the
loop. It is taking a lot of time to iterate over all the items. Is there any
faster or more efficient way to do this?**
Answer: Define the _anagram class_ of a string to be the set of counts of how many
times each letter appears in the string. For example, `'banana'` has anagram
class `a: 3, b: 1, n: 2`. Two strings are anagrams of each other if they have
the same anagram class. We can count how many substrings of the string are in
each anagram class, then compute the number of pairs by computing `(n choose
2)` for every anagram class with n substrings:
from collections import Counter
anagram_class_counts = Counter()
for substring in get_all_substrings(x):
anagram_class_counts[frozenset(Counter(substring).viewitems())] += 1
anagram_pair_count = sum(x*(x-1)/2 for x in anagram_class_counts.viewvalues())
`frozenset(Counter(substring).viewitems())` builds a hashable representation
of a string's anagram class.
* `Counter` takes an iterable and builds a mapping representing how many times each item appeared, so
* `Counter(substring)` builds a mapping representing a string's anagram class.
* `viewitems()` gives a set-like collection of letter: count pairs, and
* `frozenset` turns that into an immutable set that can be used as a dict key.
These steps together take time proportional to the size of the substring; on
average, substrings are about a third of the size of the whole string, so on
average, processing each substring takes `O(len(x))` time. There are
`O(len(x)**2)` substrings, so processing all substrings takes `O(len(x)**3)`
time.
If there are `x` substrings with the same anagram class, they can be paired up
in `x*(x-1)/2` ways, so the `sum` goes through the number of occurrences of
each anagram class and computes the number of pairs. This takes `O(len(x)**2)`
time, since it has to go through each anagram class once, and there can't be
more anagram classes than substrings.
Overall, this algorithm takes `O(len(x)**3)` time, which isn't great, but it's
a lot better than the original. There's still room to optimize this, such as
by computing anagram classes in a way that takes advantage of the overlap
between substrings or by using a more efficient anagram class representation.
|
UTF-8 for URL, Java
Question: So I'm trying to scrape a grammar website that gives you conjugations of
verbs, but I'm having trouble accessing the pages that require accents, such
as the page for the verb "fág".
Here is my current code:
String url = "http://www.teanglann.ie/en/gram/"+ URLEncoder.encode("fág","UTF-8");
System.out.println(url);
I've tried this both with and without the URLEncoder.encode() method, and it
just keeps giving me a '?' in place of the 'á' when working with it, and my
URL search returns nothing. Basically, I was wondering if there was something
similar to Python's 'urllib.parse.quote_plus'. I've tried searching and tried
many different methods from StackOverflow, all to no avail. Any help would be
greatly appreciated.
Eventually, I'm going to replace the given string with a user inputed
argument. Just using it to test at the moment.
**Solution** : It wasn't Java, but IntelliJ.
Answer: Summary from comment
The test code works fine.
import java.io.UnsupportedEncodingException;
import static java.net.URLEncoder.encode;
public class MainApp {
public static void main(String[] args) throws UnsupportedEncodingException {
String url = "http://www.teanglann.ie/en/gram/"+ encode("fág", "UTF-8");
System.out.println(url);
}
}
It emits like below
> <http://www.teanglann.ie/en/gram/f%EF%BF%BDg>
Which would goto correct page.
Correct steps are
* Ensure that source code encoding is correct. (IntelliJ probably cannot guess it all correct)
* Run the program with appropriate encoding (utf-8 in this case)
(See [What is the default encoding of the
JVM?](http://stackoverflow.com/questions/1006276/what-is-the-default-encoding-
of-the-jvm) for a relevant discussion)
Edit from Wyzard's comment
Above code works by accident(say does not have whitespace). Correct way to get
encoded URL is like bellow ..
String url = "http://www.teanglann.ie/en/gram/fág";
System.out.println(new URI(url).toASCIIString());
This uses URI.toASCIIString() which adheres to [RFC
2396](https://www.ietf.org/rfc/rfc2396.txt), which talk about _Uniform
Resource Identifiers (URI): Generic Syntax_
|
Convert coordinates to name from mysql - Python / Angularjs
Question: Can someone help to get the the name/address of my coordinates?. I already
have these latitude and longitude and the next thing that I wanna do is to
convert it. Thank you.
Answer: You should use the module [geopy](https://geopy.readthedocs.org/en/1.10.0/).
Here is example code for finding nearest address to coordinates:
>>> from geopy.geocoders import Nominatim
>>> geolocator = Nominatim()
>>> location = geolocator.reverse("52.509669, 13.376294")
>>> location.address
"Potsdamer Platz, Mitte, Berlin, 10117, Deutschland, European Union"
|
Every time I run Python manage.py I get this error
Question:
pycharm@glenn-liveconsole3:~/mysite/quickstart$ django-admin.py syncdb
Traceback (most recent call last):
File "/home/pycharm/.virtualenvs/anchondo/bin/django-admin.py", line 5, in <module>
management.execute_from_command_line()
File "/home/pycharm/.virtualenvs/anchondo/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 453, in execute_from_command
_line
utility.execute()
File "/home/pycharm/.virtualenvs/anchondo/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/pycharm/.virtualenvs/anchondo/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 272, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/home/pycharm/.virtualenvs/anchondo/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 77, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/home/pycharm/.virtualenvs/anchondo/local/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/pycharm/.virtualenvs/anchondo/local/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 8, in <module>
from django.core.management.sql import custom_sql_for_model, emit_post_sync_signal
File "/home/pycharm/.virtualenvs/anchondo/local/lib/python2.7/site-packages/django/core/management/sql.py", line 9, in <module>
from django.db import models
File "/home/pycharm/.virtualenvs/anchondo/local/lib/python2.7/site-packages/django/db/__init__.py", line 11, in <module>
if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES:
File "/home/pycharm/.virtualenvs/anchondo/local/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/home/pycharm/.virtualenvs/anchondo/local/lib/python2.7/site-packages/django/conf/__init__.py", line 46, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment va
riable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
All I am doing is running python manage.py syncdb or python manage.py migrate
I am trying to update the website the models created a new model an am trying
to migrate the info website works but I can not do syncdb in the console
Answer: When you create your project with `django-admin startproject` a `manage.py`
will be generated that has a line like:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings")
where `my_project` is your project name. This points to your settings file.
Make sure the line exists and point to the right settings module.
Also use `manage.py` instead of `django-admin` to manage an existing project.
|
How to append rows to different variables before appending to a list in python
Question: I have a input file like this
input:
20
23 121 20
35 113 11
12 15 142
17 90 110
58 12 198
......
I want to create to a list with numbers in each row assigned to a different
variable. I'm trying to do like this..
def prog(inStr):
input = inStr.split()
N = int(input[0])
list = []
for i in range(N):
row1 = int(input[1])
row2 = int(input[2])
row3 = int(input[3])
r = prog(row1, row2, row3)
list.append(r)
But it's not working as it should, if executed like this..
row1 = int(input[i*3+1])
row2 = int(input[i*3+2])
row3 = int(input[i*3+3])
Throws an error, index out of range.
Appreciate your help.
Answer: Rather than split your input on all whitespace, split it on _line separators_
first:
def prog(inStr):
lines = inStr.splitlines()
N = int(lines[0])
result = []
for index in range(N):
row1, row2, row3 = map(int, lines[index + 1].split())
If `inStr` came from a file or standard input, you could read from the input
directly:
from itertools import islice
test_count = int(next(fileobj))
result = [r(*map(int, line.split())) for line in islice(fileobj, test_count)]
This uses a list comprehension,
[`itertools.islice()`](https://docs.python.org/3/library/itertools.html#itertools.islice)
to give a hard limit the number of iterations, and argument unpacking to
produce the result list.
|
time.ctime(os.path.getmtime(myFile)) results in TypeError: coercing to Unicode: need string or buffer, file found
Question: Newbie question here.
I'm trying the code provided from: [How to get file creation & modification
date/times in Python?](http://stackoverflow.com/questions/237079/how-to-get-
file-creation-modification-date-times-in-python)
The exact code I'm running is:
# -*- coding: utf-8 -*-
import os.path, time
myFile = open('IMG_4847.PNG', 'rb')
print "last modified: %s" % time.ctime(os.path.getmtime(myFile))
But, I'm getting the following error:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "last modified: %s" % time.ctime(os.path.getmtime(myFile))
File "C:\Python27\lib\genericpath.py", line 54, in getmtime
return os.stat(filename).st_mtime
TypeError: coercing to Unicode: need string or buffer, file found
What am I missing here?
Answer:
import os.path, time
print "last modified: %s" % time.ctime(os.path.getmtime('IMG_4847.PNG'))
You pass a filepath to `getmtime`, not a file object.
|
Python error : 'tuple' object has no attribute 'upper'
Question: I wanna make word count and list how many times word counted. But
* * *
f = open("Les.Miserable.txt", 'r')
words = f.read().split()
words.sort()
wordCount = ()
for i in range(len(words)):
words[i] = words[i].replace(".", ""), (",", ""), ("/", ""), ("?", ""), ("!", "")
words[i] = words[i].upper()
if words[i] not in wordCount:
wordCount[words[i]] = 1
else:
wordCount[words[i]] += 1
i can see error message 'tuple' object has no attribute 'upper' in
words[i] = words[i].upper()
here
and also error message 'tuple' object does not support item assignment in
wordCountint[words[i]] = 1
Please let me know know what is the problem
Answer: If you print the value of `words[i]` after your attempted character
replacements you will see that it is set to a `tuple`, e.g.
('word', (',', ''), ('/', ''), ('?', ''), ('!', ''))
So the line that tries to remove unwanted punctuation actually creates a tuple
because that's what the comma separated items are, i.e.
words[i].replace(".", ""), (",", ""), ("/", ""), ("?", ""), ("!", "")
is actually a tuple consisting of `words[i].replace(".", "")` followed by
`(",", "")`, etc.
You might have meant to chain a whole lot of replace operations together, but
that would need to look like this:
words[i].replace(".", "").replace(",", "").replace("/", "").replace("?", "").replace("!", "")
But that is pretty ugly, and it's restricted to just a few punctuation
symbols. `str.translate()` is better:
words[i] = words[i].translate(None, '.,/?!')
or, if you want to get rid of all punctuation you can use
`string.punctuation`:
import string
words[i] = words[i].translate(None, string.punctuation)
Or, if you are using Python 3:
import string
words[i] = words[i].({ord(c):None for c in string.punctuation})
There are other problems in your code, but see if you can correct this first
issue first.
|
Difference between two values in txt file, python
Question: I have some values in each line of a txt file. Now I want to calculate the
difference between
> line[1] - line[0], line[3] - line[2]
and so forth.
import sys
l = []
i = 0
f=open('Isotop1.txt')
# i = Zeilennummer, line = text der Zeile
for line in enumerate(f):
l.append(line)
for i in l:
c = l[i] - l[i-1]
print c
f.close()
later I want to store the solutions in a new text file. but now I get the
`list indices must be integers, not tuple` error. Can someone help?
this is a small sample from the text file. I want to calculate the differences
between 33 and 0, 94 and 61 and so on. Maybe I used a completey wrong approach
to this problem...
0
33
61
94
122
153
178
200
227
246
274
297
310
324
Answer:
with open("in.txt") as f:
# get first line/number
nxt = int(next(f))
for n in f:
print("absolute difference between {} and {} = {}"
.format(n.rstrip(), nxt, abs(int(nxt) - int(n))))
# set nxt equal to the next number
nxt = int(next(f,0))
Output:
absolute difference between 33 and 0 = 33
absolute difference between 94 and 61 = 33
absolute difference between 153 and 122 = 31
absolute difference between 200 and 178 = 22
absolute difference between 246 and 227 = 19
absolute difference between 297 and 274 = 23
absolute difference between 324 and 310 = 14
If you want to use each number:
def diff(fle):
with open(fle) as f:
nxt = int(next(f))
for n in f:
yield abs(int(nxt) - int(n))
nxt = int(next(f,0))
print(list(diff("in.txt")))
[33, 33, 31, 22, 19, 23, 14]
Or iterate over and get one number at a time:
for n in diff("words.txt"):
print(n)
Output:
33
33
31
22
19
23
14
Using `0` as a default value to `next` will avoid a StopIterationError.
If you are doing a lot of numerical computation numpy might be better:
import numpy as np
arr = np.loadtxt("words.txt", dtype=np.int)
diff = np.abs(np.diff(arr.reshape(-1,2)).flatten())
print(diff)
|
How does Python import really work? In a chain of import
Question: **Hi fellow Pythonista,**
While I have been coding with Python for quite some time now, recently I found
my some problem in my understanding of python's import mechanism.
I am hoping you guys can help me out. Thanks in advance. Your help is much
appreciated.
### Setup
myprogram
┠━run.py
┗━mypackage
┠━ __init__.py
┠━ foo.py
┗━ bar.py
The content of the python files are as follow:
# run.py
import sys
print sys.path
from mypackage import foo
# foo.py
import sys
print sys.path
import bar
# bar.py
import sys
print sys.path
Neither `myprogram` nor any of its sub directories is in the `PYTHONPATH`
environment variable.
### My Current Understanding
The flow of execute:
1. Start running `run.py`. The path to the containing directory, `PATH/myprogram` is added to the `sys.path`.
2. Executing the statement `from mypackage import foo`. Since we now have `PATH/myprogram` in the `sys.path`, the interpreter can find the `mypackage` and then locate the `foo.py` without problem.
3. Start running `foo.py`, the interpreter adds the path to the containing directory `PATH/myprogram/mypackage` to the `sys.path`.
4. At this point, both `PATH/myprogram` and `PATH/myprogram/mypackage` is included in `sys.path`.
5. Executing the statement `import bar`. Since we have `PATH/myprogram/mypackage` added to the `sys.path`, the import statement can execute successfully without problem.
### Question
After running the `run.py`, I discover all of the `print sys.path` statements
yield the same outputs. All of them contains `PATH/myprogram` but not
`PATH\myprogram\mypackage`, which contradicts to my understanding above.
It seems the home directory path is only added for the script that initialised
the process.But if that is the case, then how is the `import bar` statement in
`foo.py` execute successful if `PATH\myprogram\mypackage` is not in the search
path?
BTW, I am using python 2.7 on a MAC OS X machine.
Answer: sys.path is not a place to add anything by python itself.
The paths are added to modules cache, docs are clear about that:
<https://docs.python.org/release/2.7/reference/simple_stmts.html#import>
Print out the `sys.modules` and `sys.path_importer_cache` to get the overview.
The cache has the path to run.py and it can find other modules starting from
there.
|
Text file indexing using python 3.4.3
Question: I try to write a Python 3.4 code to index text document from external and this
my attempt. when run it error message:
> raw input is not defined
What I want is:
1. to tokenize the document which is out of python 34 folder
2. to remove stop words
3. to stem
4. indexing
The code:
import string
def RemovePunc():
line = []
i = 0
text_input = ""
total_text_input = "C:Users\Kelil\Desktop\IRS_Assignment\project.txt"
#This part removes the punctuation and converts input text to lowercase
while i != 1:
text_input = raw_input
if text_input == ".":
i = 1
else:
new_char_string = ""
for char in text_input:
if char in string.punctuation:
char = " "
new_char_string = new_char_string + char
line = line + [new_char_string.lower()]
#This is a list with all of the text that was entered in
total_text_input = (total_text_input + new_char_string).lower()
return line
def RemoveStopWords(line):
line_stop_words = []
stop_words = ['a','able','about','across','after','all','almost','also','am','among',
'an','and','any','are','as','at','be','because','been','but','by','can',
'cannot','could','dear','did','do','does','either','else','ever','every',
'for','from','get','got','had','has','have','he','her','hers','him','his',
'how','however','i','if','in','into','is','it','its','just','least','let',
'like','likely','may','me','might','most','must','my','neither','no','nor',
'not','of','off','often','on','only','or','other','our','own','rather','said',
'say','says','she','should','since','so','some','than','that','the','their',
'them','then','there','these','they','this','tis','to','too','twas','us',
'wants','was','we','were','what','when','where','which','while','who',
'whom', 'why', 'will', 'with', 'would', 'yet', 'you', 'your']
#this part removes the stop words for the list of inputs
line_stop_words = []
sent = ""
word = ""
test = []
for sent in line:
word_list = string.split(sent)
new_string = ""
for word in word_list:
if word not in stop_words:
new_string = new_string + word + " "
new_string = string.split(new_string)
line_stop_words = line_stop_words + [new_string]
return(line_stop_words)
def StemWords(line_stop_words):
leaf_words = "s","es","ed","er","ly","ing"
i=0
while i < 6:
count = 0
length = len(leaf_words[i])
while count < len(line_stop_words):
line = line_stop_words[count]
count2 = 0
while count2 < len(line):
#line is the particular list(or line) that we are dealing with, count if the specific word
if leaf_words[i] == line[count2][-length:]:
line[count2] = line[count2][:-length]
count2 = count2 + 1
line_stop_words[count] = line
count2 = 0
count = count + 1
count = 0
i = i + 1
return(line_stop_words)
def indexDupe(lineCount,occur):
if str(lineCount) in occur:
return True
else:
return False
def Indexing(line_stop_words):
line_limit = len(line_stop_words)
index = []
line_count = 0
while line_count < line_limit:
for x in line_stop_words[line_count]:
count = 0
while count <= len(index):
if count == len(index):
index = index + [[x,[str(line_count+1)]]]
break
else:
if x == index[count][0]:
if indexDupe(line_count+1,index[count][1]) == False:
index[count][1] += str(line_count+1)
break
count = count + 1
line_count = line_count + 1
return(index)
def OutputIndex(index):
print ("Index:")
count = 0
indexLength = len(index)
while count < indexLength:
print (index[count][0],)
count2 = 0
lineOccur = len(index[count][1])
while count2 < lineOccur:
print (index[count][1][count2],)
if count2 == lineOccur -1:
print ("")
break
else:
print (",",)
count2 += 1
count += 1
line = RemovePunc()
line_stop_words = RemoveStopWords(line)
line_stop_words = StemWords(line_stop_words)
index = Indexing(line_stop_words)
OutputIndex(index)
Answer: @smichak already put the right answer in the comments. `raw_input` was renamed
to `input` in Python 3. So you want:
text_input = input()
Don't forget those parentheses, since you want to call the function.
|
python 'self' is not defined
Question: File "database.py", line 6, in class data: File "database.py", line 17, in
data self.dbcommit() NameError: name 'self' is not defined
from sqlite3 import dbapi2 as sqlite
class data:
def __init__(self,dbname):
self.con=sqlite.connect(dbname)
def __del__(self):
self.con.close()
def dbcommit(self):
self.con.commit()
def createtable(self):
self.con.execute('create table db(ind,w)')
self.dbcommit()
e=data('search.db')
e.createtable()
Answer: It's an indentation issue. The `def`s after `__init__` need to be indented the
same amount for Python to consider them to be part of the class.
Try:
from sqlite3 import dbapi2 as sqlite
class data:
def __init__(self,dbname):
self.con=sqlite.connect(dbname)
def __del__(self):
self.con.close()
def dbcommit(self):
self.con.commit()
def createtable(self):
self.con.execute('create table db(ind,w)')
self.dbcommit()
e=data('search.db')
e.createtable()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.