title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
---|---|---|---|---|---|---|---|---|---|
python loadtxt with exotic format of table
| 39,621,800 |
<p>I have a file from simulation which reads like :</p>
<pre><code>5.2000 -0.01047 -0.02721 0.823400 -0.56669 1.086e-5 2.109e-5 -1.57e-5 -3.12e-5
0.823400 -0.56669 -0.02166 -0.01949 -2.28e-5 -2.66e-5 1.435e-5 1.875e-5
1.086e-5 2.109e-5 -2.28e-5 -2.66e-5 -0.01878 -0.01836 0.820753 -0.57065
-1.57e-5 -3.12e-5 1.435e-5 1.875e-5 0.820753 -0.57065 -0.01066 -0.02402
5.2005 -0.01045 -0.02721 0.823354 -0.56676 1.086e-5 2.109e-5 -1.57e-5 -3.12e-5
0.823354 -0.56676 -0.02167 -0.01947 -2.28e-5 -2.66e-5 1.435e-5 1.875e-5
1.086e-5 2.109e-5 -2.28e-5 -2.66e-5 -0.01878 -0.01833 0.820703 -0.57073
-1.57e-5 -3.12e-5 1.435e-5 1.875e-5 0.820703 -0.57073 -0.01063 -0.02401
5.2010 -0.01043 -0.02721 0.823309 -0.56683 1.087e-5 2.108e-5 -1.57e-5 -3.12e-5
0.823309 -0.56683 -0.02168 -0.01945 -2.28e-5 -2.66e-5 1.435e-5 1.874e-5
1.087e-5 2.108e-5 -2.28e-5 -2.66e-5 -0.01878 -0.01830 0.820654 -0.57080
-1.57e-5 -3.12e-5 1.435e-5 1.874e-5 0.820654 -0.57080 -0.01061 -0.02400
</code></pre>
<p>And I would like to get it as a float + an array of float (the float would be the '5.2000' and the array what is after (4x8 table)
but the numpy command loadtxt don't get this exotic kind of structure. Is there a solution to it ?</p>
| 2 |
2016-09-21T16:23:30Z
| 39,625,890 |
<p><code>genfromtxt</code> is generally much more versatile a module than <code>loadtxt</code></p>
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="nofollow">genfromtxt documentation</a> </p>
| 0 |
2016-09-21T20:20:37Z
|
[
"python",
"numpy"
] |
How to have python functions and classes available system-wide with an easy `import` statement
| 39,621,831 |
<h1>Introduction</h1>
<p>I thought I'd try my hand at making a python module to make some of my libraries and functions available system-wide.
Google and StackExchange provide ample "solutions" and how-toos. But for some reason none of them seem to work for me. Obviously, I'm doing something wrong. But after days of trial & error I've decided to show you guys what I have and let you point out the obvious error to me ;-) Your help is much appreciated.</p>
<h1>What I have</h1>
<p>My GitHub project directory contains this tree:</p>
<pre><code>$ tree /tmp/mausy5043-common-python
/tmp/mausy5043-common-python
âââ docs
âââ gitforcepull
âââ LICENSE
âââ mausy5043funcs
â  âââ __init__.py
âââ mausy5043libs
â  âââ __init__.py
â  âââ libdaemon3.py
â  âââ libsmart3.py
âââ README.md
âââ setup.py
âââ tests
</code></pre>
<p><code>libsmart3.py</code> is a python script that offers a <code>class SmartDisk():</code>. Both <code>__init__.py</code> scripts are empty. <code>libdaemon3.py</code> is a script that contains another class. It has the same problem but I'll use the <code>libsmart3</code> module as an example here.</p>
<p>I install this project as follows:</p>
<pre><code>$ sudo python3 setup.py install
running install
running build
running build_py
creating build
creating build/lib
creating build/lib/mausy5043libs
copying mausy5043libs/libdaemon3.py -> build/lib/mausy5043libs
copying mausy5043libs/libsmart3.py -> build/lib/mausy5043libs
running install_lib
copying build/lib/mausy5043libs/libsmart3.py -> /usr/local/lib/python3.4/dist-packages/mausy5043libs
copying build/lib/mausy5043libs/libdaemon3.py -> /usr/local/lib/python3.4/dist-packages/mausy5043libs
byte-compiling /usr/local/lib/python3.4/dist-packages/mausy5043libs/libsmart3.py to libsmart3.cpython-34.pyc
byte-compiling /usr/local/lib/python3.4/dist-packages/mausy5043libs/libdaemon3.py to libdaemon3.cpython-34.pyc
running install_egg_info
Removing /usr/local/lib/python3.4/dist-packages/mausy5043_common_python-0.1dev.egg-info
Writing /usr/local/lib/python3.4/dist-packages/mausy5043_common_python-0.1dev.egg-info
</code></pre>
<h1>What doesn't work</h1>
<p>Now I want to use this class <code>SmartDisk()</code> in another python script. To do this I expected (was hoping) that I would be able to import the class directly -- thanks to the presence of the <code>__init__py</code> -- thus:</p>
<pre><code>$ python3
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from mausy5043libs import SmartDisk
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'SmartDisk'
>>>
</code></pre>
<p><strong>OR</strong></p>
<pre><code>>>> from libsmart3 import SmartDisk
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'libsmart3'
>>>
</code></pre>
<h1>How I don't want it to work</h1>
<p>What <strong>does</strong> work is this:</p>
<p><code>>>> from mausy5043libs.libsmart3 import SmartDisk</code></p>
<p>but this is not how it was advertised (ref: <a href="http://mikegrouchy.com/blog/2012/05/be-pythonic-__init__py.html" rel="nofollow">http://mikegrouchy.com/blog/2012/05/be-pythonic-__init__py.html</a> )</p>
<h1>What else did I try</h1>
<p>I've tried to add <code>import libsmart3</code> in <code>mausy5043libs/__init__.py</code>. Doesn't work.</p>
<p>I've added <code>from libsmart3 import SmartDisk</code> in <code>mausy5043libs/__init__py</code>. No joy.</p>
<p>I've added an empty <code>__init__.py</code> in the project root under the assumption that python needs this. Didn't help.</p>
<p><strong>EDIT</strong>
changes made: to <code>mausy5043libs/__init__py</code> as suggested by @user2357112</p>
<pre><code>$ cat mausy5043libs/__init__.py
from .libsmart3 import SmartDisk
$ sudo python3 setup.py install
[... output removed ...]
$ python3
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from mausy5043libs import SmartDisk
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'SmartDisk'
</code></pre>
<p><strong>EDIT 2</strong> : It turns out the solution provided by @user2357112 <em>does</em> indeed work. There was, obviously, a small oversight on my part. In <code>setup.py</code> the entry <code>mausy5043libs/__init__</code> was missing in the <code>py_modules</code> list.</p>
| -1 |
2016-09-21T16:24:55Z
| 39,622,187 |
<p>You completely misread the sources you were working off of. If you want to be able to import <code>SmartDisk</code> directly from the <code>mausy5043libs</code> package, then <code>mausy5043libs/__init__.py</code> needs to import <code>SmartDisk</code>:</p>
<pre><code># in mausy5043libs/__init__.py
from .libsmart3 import SmartDisk
</code></pre>
<p>Then users of the package can import it the way you want:</p>
<pre><code># in code that wants to use SmartDisk
from mausy5043libs import SmartDisk
</code></pre>
<p>The article you linked includes this information under "What goes in <code>__init__.py</code>?", although they use pre-Python 3 implicit relative import syntax.</p>
| 1 |
2016-09-21T16:44:53Z
|
[
"python",
"python-3.x",
"python-import"
] |
Import data from xml file into two tables w/ foreign key at MySQL database
| 39,621,860 |
<p>I need to load file of the following format into MySQL database.</p>
<pre><code><item value="{$\emptyset $}">
<subitem value="(empty language)"></subitem>
<subitem value="(empty set)"></subitem>
</item>
<item value="{$\subseteq$ (subset)}">
</item>
<item value="{$\subset$ (proper subset)}">
</item>
<item value="{$:$ (such that)}">
</item>
<item value="{$\cap$ (set intersection)}">
</item>
<item value="{$\cup$ (set union)}">
</item>
<item value="{$-$ (set difference)}">
</item>
<item value="{$\left | \mskip \medmuskip \right |$}">
<subitem value="(flow value)"></subitem>
<subitem value="(length of a string)"></subitem>
<subitem value="(set cardinality)"></subitem>
</item>
</code></pre>
<p>I think in database it should be represented by two tables, Subitem table should contain foreign key:</p>
<p>Item <-- Subitem</p>
<p>I want to do it with python. Is it possible to accomplish it with MySQL instructions only, or it is better to load xml file in python, create both tables manually and then insert all entries into tables i want?</p>
| 1 |
2016-09-21T16:26:08Z
| 39,630,669 |
<p>I was able to do it by reading xml with python and then inserting it into MySQL database. First one need to install needed software:</p>
<pre><code>sudo apt install mysql-server
sudo apt-get install python-mysqldb
</code></pre>
<p>Then this py-file will do the job:</p>
<pre><code>import xml.etree.ElementTree
import MySQLdb
try:
db = MySQLdb.connect(host="localhost",
user="root",
passwd="!")
cur = db.cursor()
cur.execute("DROP DATABASE IF EXISTS i2a")
cur.execute("CREATE DATABASE i2a")
cur.execute("USE i2a")
print "Created database"
cur.execute("""
CREATE TABLE Item (
id INT NOT NULL AUTO_INCREMENT,
`value` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
)
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin""")
print "Created Item table"
cur.execute("""
CREATE TABLE Subitem (
id INT NOT NULL AUTO_INCREMENT,
item_id INT NOT NULL,
`value` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (item_id) REFERENCES Item(id) ON DELETE RESTRICT
)
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin""")
print "Created Subitem table"
e = xml.etree.ElementTree.parse('index.xml').getroot()
for item in e.findall('item'):
cur.execute("INSERT INTO Item (value) VALUES (%s)", [item.get('value')])
for subitem in item:
cur.execute("INSERT INTO Subitem (item_id, value) VALUES (%s, %s)", (db.insert_id(), subitem.get('value')))
print "All data are there!"
except Exception, e:
print str(e)
</code></pre>
| 0 |
2016-09-22T05:06:33Z
|
[
"python",
"mysql"
] |
Using a DLL exported from D
| 39,621,900 |
<p>I've created a simple encryption program in D, and I had the idea to make a DLL from it and try to import it to, for example, Python.</p>
<p>I've could simply call my <code>main</code> function, becouse it dosn't need any params. But when I get to my encrytion method, <strong>it uses dynamic-lenght <code>ubyte[]</code> arrays</strong>, but as far as I know, they <strong>don't exist in other C/C++ based langs</strong>.</p>
<p>For example, there's the first line of one of my funcs:<br>
<code>ubyte[] encode(ubyte[] data, ubyte[] key){</code></p>
<p>But I can't use an array without fixed lenght in other languages!
How can I import that function, for example, in Python?</p>
<p><strong>EDIT:</strong></p>
<p>I know that I can create a wrapper that takes a pointer and the lenght of the array, but isn't there a more elegant solution?<br>
(Where I don't need to use D to use a lib written in D)</p>
| 6 |
2016-09-21T16:28:32Z
| 39,625,571 |
<p>Well tbh. there's no real elegant way other than wrapping a pointer with a length or wrapping to C arrays and then to D.</p>
<p>However you can make a somewhat elegant purpose with the first way using a struct that has a pointer, a length and a property that converts it to a D array.</p>
<p>Then the function you export takes your struct, all that function should do is call an internal function that takes an actual D array and you'd simply pass the array to it and the conversion would happen at that moment through alias this and the conversion property.</p>
<p>An example usage is here:
module main;</p>
<pre><code>import core.stdc.stdlib : malloc;
import std.stdio;
struct DArray(T) {
T* data;
size_t length;
/// This field can be removed, only used for testing purpose
size_t offset;
@property T[] array() {
T[] arr;
foreach(i; 0 .. length) {
arr ~= data[i];
}
return arr;
}
alias array this;
/// This function can be removed, only used for testing purpose
void init(size_t size) {
data = cast(T*)malloc(size * T.sizeof);
length = size;
}
/// This function can be removed, only used for testing purpose
void append(T value) {
data[offset] = value;
offset++;
}
}
// This function is the one exported
void externalFoo(DArray!int intArray) {
writeln("Calling extern foo");
internalFoo(intArray);
}
// This function is the one you use
private void internalFoo(int[] intArray) {
writeln("Calling internal foo");
writeln(intArray);
}
void main() {
// Constructing our test array
DArray!int arrayTest;
arrayTest.init(10);
foreach (int i; 0 .. 10) {
arrayTest.append(i);
}
// Testing the exported function
externalFoo(arrayTest);
}
</code></pre>
<p>Here is an absolute minimum version of how to do it</p>
<pre><code>struct DArray(T) {
T* data;
size_t length;
@property T[] array() {
T[] arr;
foreach(i; 0 .. length) {
arr ~= data[i];
}
return arr;
}
alias array this;
}
// This function is the one exported
void externalFoo(DArray!int intArray) {
writeln("Calling extern foo");
internalFoo(intArray);
}
// This function is the one you use
private void internalFoo(int[] intArray) {
writeln("Calling internal foo");
writeln(intArray);
}
</code></pre>
| 1 |
2016-09-21T20:01:53Z
|
[
"python",
"dll",
"d"
] |
pd.read_csv ignores columns that don't have headers
| 39,621,914 |
<p>I have a .csv file that is generated by a third-party program. The data in the file is in the following format:</p>
<pre><code>%m/%d/%Y 49.78 85 6 15
03/01/1984 6.63368 82 7 9.8 34.29056405 2.79984079 2.110346498 0.014652412 2.304545521 0.004732732
03/02/1984 6.53368 68 0 0.2 44.61471002 3.21623666 2.990408898 0.077444779 2.793385466 0.02661873
03/03/1984 4.388344 55 6 0 61.14463457 3.637231063 3.484310818 0.593098236 3.224973641 0.214360796
</code></pre>
<p>There are 5 column headers (row 1 in excel, columns A-E) but 11 columns in total (row 1 columns F-K are empty, rows 2-N contain float values for columns A-K)</p>
<p>I was not sure how to paste the .csv lines in so they are easily replicable, sorry for that. An image of the excel sheet is shown here: <a href="http://i.stack.imgur.com/UsJnk.png" rel="nofollow">Excel sheet to read in</a></p>
<p>when I use the following code:</p>
<pre><code>FWInds=pd.read_csv("path.csv")
</code></pre>
<p>or:</p>
<pre><code>FWInds=pd.read_csv("path.csv", header=None)
</code></pre>
<p>the resulting dataframe FWInds does not contain the last 6 columns - it only contains the columns with headers (columns A-E from excel, column A as index values). </p>
<pre><code>FWIDat.shape
Out[48]: (245, 4)
</code></pre>
<p>Ultimately the last 6 columns are the only ones I even want to read in.</p>
<p>I also tried:</p>
<pre><code>FWInds=pd.read_csv('path,csv', header=None, index_col=False)
</code></pre>
<p>but got the following error</p>
<pre><code>CParserError: Error tokenizing data. C error: Expected 5 fields in line 2, saw 11
</code></pre>
<p>I also tried to ignore the first row since the column titles are unimportant:</p>
<pre><code>FWInds=pd.read_csv('path.csv', header=None, skiprows=0)
</code></pre>
<p>but get the same error.</p>
<p>Also no luck with the "usecols" parameter, it doesn't seem to understand that I'm referring to the column numbers (not names), unless I'm doing it wrong:</p>
<pre><code>FWInds=pd.read_csv('path.csv', header=None, usecols=[5,6,7,8,9,10])
</code></pre>
<p>Any tips? I'm sure it's an easy fix but I'm very new to python.</p>
| 2 |
2016-09-21T16:29:27Z
| 39,622,282 |
<p>You could do it as shown:</p>
<pre><code>col_name = list('ABCDEFGHIJK')
data = 'path.csv'
pd.read_csv(data, delim_whitespace=True, header=None, names=col_name, usecols=col_name[5:])
</code></pre>
<p><a href="http://i.stack.imgur.com/QqBJJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/QqBJJ.png" alt="Image"></a></p>
<p>To read all the columns from A â K, simply omit the <code>usecols</code> parameter.</p>
<hr>
<p>Data:</p>
<pre><code>data = StringIO(
'''
%m/%d/%Y,49.78,85,6,15
03/01/1984,6.63368,82,7,9.8,34.29056405,2.79984079,2.110346498,0.014652412,2.304545521,0.004732732
03/02/1984,6.53368,68,0,0.2,44.61471002,3.21623666,2.990408898,0.077444779,2.793385466,0.02661873
03/03/1984,4.388344,55,6,0,61.14463457,3.637231063,3.484310818,0.593098236,3.224973641,0.214360796
''')
col_name = list('ABCDEFGHIJK')
pd.read_csv(data, header=None, names=col_name, usecols=col_name[5:])
</code></pre>
| 1 |
2016-09-21T16:50:17Z
|
[
"python",
"csv",
"pandas"
] |
pd.read_csv ignores columns that don't have headers
| 39,621,914 |
<p>I have a .csv file that is generated by a third-party program. The data in the file is in the following format:</p>
<pre><code>%m/%d/%Y 49.78 85 6 15
03/01/1984 6.63368 82 7 9.8 34.29056405 2.79984079 2.110346498 0.014652412 2.304545521 0.004732732
03/02/1984 6.53368 68 0 0.2 44.61471002 3.21623666 2.990408898 0.077444779 2.793385466 0.02661873
03/03/1984 4.388344 55 6 0 61.14463457 3.637231063 3.484310818 0.593098236 3.224973641 0.214360796
</code></pre>
<p>There are 5 column headers (row 1 in excel, columns A-E) but 11 columns in total (row 1 columns F-K are empty, rows 2-N contain float values for columns A-K)</p>
<p>I was not sure how to paste the .csv lines in so they are easily replicable, sorry for that. An image of the excel sheet is shown here: <a href="http://i.stack.imgur.com/UsJnk.png" rel="nofollow">Excel sheet to read in</a></p>
<p>when I use the following code:</p>
<pre><code>FWInds=pd.read_csv("path.csv")
</code></pre>
<p>or:</p>
<pre><code>FWInds=pd.read_csv("path.csv", header=None)
</code></pre>
<p>the resulting dataframe FWInds does not contain the last 6 columns - it only contains the columns with headers (columns A-E from excel, column A as index values). </p>
<pre><code>FWIDat.shape
Out[48]: (245, 4)
</code></pre>
<p>Ultimately the last 6 columns are the only ones I even want to read in.</p>
<p>I also tried:</p>
<pre><code>FWInds=pd.read_csv('path,csv', header=None, index_col=False)
</code></pre>
<p>but got the following error</p>
<pre><code>CParserError: Error tokenizing data. C error: Expected 5 fields in line 2, saw 11
</code></pre>
<p>I also tried to ignore the first row since the column titles are unimportant:</p>
<pre><code>FWInds=pd.read_csv('path.csv', header=None, skiprows=0)
</code></pre>
<p>but get the same error.</p>
<p>Also no luck with the "usecols" parameter, it doesn't seem to understand that I'm referring to the column numbers (not names), unless I'm doing it wrong:</p>
<pre><code>FWInds=pd.read_csv('path.csv', header=None, usecols=[5,6,7,8,9,10])
</code></pre>
<p>Any tips? I'm sure it's an easy fix but I'm very new to python.</p>
| 2 |
2016-09-21T16:29:27Z
| 39,622,485 |
<p>There are a couple of parameters that can be passed to <code>pd.read_csv()</code>:</p>
<pre><code>import pandas as pd
colnames = list('ABCDEFGHIKL')
df = pd.read_csv('test.csv', sep='\t', names=colnames)
</code></pre>
<p>With this, I can actually import your data quite fine (and it is accessible via eg <code>df['K']</code> afterwards).</p>
| 1 |
2016-09-21T17:02:00Z
|
[
"python",
"csv",
"pandas"
] |
np reshape within pandas apply
| 39,621,965 |
<p>Arise Exception: Data must be 1-dimensional.</p>
<p>I'll present the problem with a toy example to be clear.</p>
<pre><code>import pandas as pd
import numpy as np
</code></pre>
<p>Initial dataframe:</p>
<pre><code>df = pd.DataFrame({"A": [[10,15,12,14],[20,30,10,43]], "R":[2,2] ,"C":[2,2]})
>>df
A C R
0 [10, 15, 12, 14] 2 2
1 [20, 30, 10, 43] 2 2
</code></pre>
<p>Conversion to numpy array and reshape:</p>
<pre><code>df['A'] = df['A'].apply(lambda x: np.array(x))
df.apply(lambda x: print(x[0],(x[1],x[2])) ,axis=1)
df['A_reshaped'] = df.apply(lambda x[['A','R','C']]: np.reshape(x[0],(x[1],x[2])),axis=1)
df
A C R A_reshaped
0 [10, 15, 12, 14] 2 2 [[10,15],[12,14]]
1 [20, 30, 10, 43] 2 2 [[20,30],[10,43]]
</code></pre>
<p>Someone know the reason? It seems to not accept 2 dimensional arrays in pandas cells but it's strange...</p>
<p>Thanks in advance for any help!!!</p>
| 2 |
2016-09-21T16:32:03Z
| 39,622,513 |
<p>Using <code>apply</code> directly doesn't work - the return value is a <code>numpy</code> 2d array, and placing it back in the DataFrame confuses Pandas, for some reason. </p>
<p>This seems to work, though:</p>
<pre><code>df['reshaped'] = pd.Series([a.reshape((c, r)) for (a, c, r) in zip(df.A, df.C, df.R)])
>>> df
A C R reshaped
0 [10, 15, 12, 14] 2 2 [[10, 15], [12, 14]]
1 [20, 30, 10, 43] 2 2 [[20, 30], [10, 43]]
</code></pre>
| 2 |
2016-09-21T17:03:46Z
|
[
"python",
"pandas",
"numpy",
"reshape"
] |
TypeError: unsupported operand type(s) for -: 'NoneType' and 'NoneType'
| 39,622,005 |
<p>For my course in Python, I am creating a program that calculates the distance between two cities bases on their coordinates. It has worked and suddenly I got the following error:</p>
<pre><code>Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
distance(+1, 52, 22, +1, 4, 32, +1, 45, 30, -1, 73, 35)
File "C:/Python27/flying_distances_1.py", line 26, in distance
distance = Haversine(lat_1, lat_2, lon_1, lon_2) * 6367.0
File "C:/Python27/flying_distances_1.py", line 4, in Haversine
a_1 = math.sin((lat_2 - lat_1)/2) ** 2
TypeError: unsupported operand type(s) for -: 'NoneType' and 'NoneType'
</code></pre>
<p>This is the code that goes with it: </p>
<pre><code>import math
def Haversine (lat_1, lat_2, lon_1, lon_2):
a_1 = math.sin((lat_2 - lat_1)/2) ** 2
a_2 = math.cos(lat_1) * math.cos(lat_2)
a_3 = math.sin((lon_2-lon_1)/2) ** 2
a_4 = a_1 + a_2 * a_3
b = 1 - a_4
d = 2 * math.atan2(math.sqrt(a_4), math.sqrt(b))
def conversion (sign, degrees, minutes):
minutes_to_degrees = 1/60.0 * minutes
total_degrees = minutes_to_degrees + degrees
radians = total_degrees * 1/180.0 * math.pi
total_radians = sign * radians
def distance (sign_lat_1, deg_lat_1, min_lat_1,
sign_lon_1, deg_lon_1, min_lon_1,
sign_lat_2, deg_lat_2, min_lat_2,
sign_lon_2, deg_lon_2, min_lon_2):
lat_1 = conversion(sign_lat_1, deg_lat_1, min_lat_1)
lon_1 = conversion(sign_lon_1, deg_lon_1, min_lon_1)
lat_2 = conversion(sign_lat_2, deg_lat_2, min_lat_2)
lon_2 = conversion(sign_lon_2, deg_lon_2, min_lon_2)
distance = Haversine(lat_1, lat_2, lon_1, lon_2) * 6367.0
return distance
</code></pre>
<p>I have searched and searched but I can't seem to find the error that causes the aforementioned message in my code. It probably is something really small (and possibly quite stupid ;)), but the person that can find the error will help me back on track!</p>
| -2 |
2016-09-21T16:34:29Z
| 39,622,313 |
<p>There is no return statement in the <code>conversion</code> function. At the moment, the radians value is calculated then forgotten when the function finishes. If you want the value of <code>total_radians</code> to be accessed from outside the function, add </p>
<pre><code> return total_radians
</code></pre>
<p>as the last line of the conversion function.</p>
| 0 |
2016-09-21T16:52:34Z
|
[
"python",
"typeerror"
] |
Problems with pickling data
| 39,622,014 |
<pre><code>import random
import pickle, shelve
import os
#import RPi.GPIO as GPIO | Raspberry pi only
import tkinter
import sys
import time
class Operator(object):
global list_name
def __init__(self):
print("Welcome to Python OS 1.0")
print("type 'help' to access help...") # ADD CODE OS.REMOVE("FILE")
def CheckDetails(self):
if not os.path.isfile( 'details.dat' ) :
data=[0]
data[0] = input('Enter Your Name: ' )
file= open( 'details.dat' , 'wb' )
pickle.dump( data , file )
file.close()
else :
File = open( 'details.dat' , 'rb' )
data = pickle.load( File )
file.close()
user = ""
while user != data[0]:
input("please enter your username...")
print( 'Welcome Back To Python OS, '+ data[0])
def Help(self):
print("""
write(sentence) - Prints the typed sentence on the screen
open(file, mode) - Opens the file and mode such as 'r'
create(listName) - creates the list, listName
add(data, listName) - adds the data to listName
remove(data, listName) - removes the selected data from listName
""")
def write(self, sentence):
print(sentence)
@classmethod
def create(self):
list_name = input("Please enter the list name...")
vars()[list_name] = []
time.sleep(1)
print("List (" + list_name + ") created")
def add(self):
data = input("Please specify the data to be added...")
list_name += data
def remove(self, data, list_name):
remove_data = input("Plese specify the data to be removed...")
list_name -= data
def main():
os = Operator()
os.CheckDetails()
ans = ""
ans = ans.lower()
while ans != "quit":
ans = input()
if ans == "write":
os.write()
elif ans == "help":
os.Help()
elif ans == "create":
os.create()
elif ans == "add":
os.add()
elif ans == "remove":
os.remove()
elif ans == "quit":
break
else:
print("Sorry, that command does not exist or it will be added into a future update...")
print("goodbye...")
main()
</code></pre>
<p>I am trying to make some sort of simplified python, but hitting errors only on the <code>CheckDetails()</code> function. I'm pickling data (which is fine) but getting errors when making the user check his or her username is correct, I've tested it and even though I have typed in the correct username, it carry's on asking for my username. Can anyone please help? </p>
| 0 |
2016-09-21T16:35:16Z
| 39,628,530 |
<p>You have a while loop that will execute forever because you are not assigning your user variable to anything.
while user != data[0]:
user = input("please enter your username...")
print( 'Welcome Back To Python OS, '+ data[0])</p>
| 0 |
2016-09-22T00:40:09Z
|
[
"python",
"python-3.x",
"pickle"
] |
How do I see/get the Number of subreddits I downloaded using reddits API
| 39,622,022 |
<pre><code>>>> import requests
>>> from pprint import pprint
>>> r = requests.get('http://www.reddit.com/reddits.json', headers= {'User-Agent': 'me'})
>>> data = r.json()
>>> pprint(data.keys())
</code></pre>
<p>This prints subreddits & im trying to figure out how much it prints out or if I can print out a certain number. Thanks !</p>
| 1 |
2016-09-21T16:35:31Z
| 39,622,248 |
<pre><code>import requests
r = requests.get('http://www.reddit.com/reddits.json', headers= {'User-Agent': 'me'})
data = r.json()
print(len(data['data']['children']))
</code></pre>
<p>The structure of the JSON is complicated, so I'm not entirely sure what you are trying to count, but <code>['data']['children']</code> appears to be the root of the subreddits.</p>
| 0 |
2016-09-21T16:48:31Z
|
[
"python",
"json",
"api",
"reddit-api"
] |
Slice numpy array to make it desired shaped
| 39,622,059 |
<p>Surprisingly, couldn't find the answer across the internet. I have an n-dimensional numpy array. E.g.: 2-D np array:</p>
<pre><code>array([['34.5500000', '36.9000000', '37.3200000', '37.6700000'],
['41.7900000', '44.8000000', '48.2600000', '46.1800000'],
['36.1200000', '37.1500000', '39.3100000', '38.1000000'],
['82.1000000', '82.0900000', '76.0200000', '77.7000000'],
['48.0100000', '51.2500000', '51.1700000', '52.5000000', '55.2500000'],
['39.7500000', '39.5000000', '36.8100000', '37.2500000']], dtype=object)
</code></pre>
<p>As you can see, the 5th row consists of 5 elemnts and <strong>i want to make the 5th dissapear</strong>, using something like this:</p>
<pre><code>np.slice(MyArray, [6,4])
</code></pre>
<p>[6,4] is a shape. I really DO not want to iterate threw dimensions and cut them. I tried the <code>resize</code> method, but it returns nothing!</p>
| 3 |
2016-09-21T16:37:45Z
| 39,622,690 |
<p>This is not a 2d array. It is a 1d array, whose elements are objects, in this case some 4 element lists and one 5 element one. And this lists contain strings.</p>
<pre><code>In [577]: np.array([['34.5500000', '36.9000000', '37.3200000', '37.6700000'],
...: ['41.7900000', '44.8000000', '48.2600000', '46.1800000'],
...: ['36.1200000', '37.1500000', '39.3100000', '38.1000000'],
...: ['82.1000000', '82.0900000', '76.0200000', '77.7000000'],
...: ['48.0100000', '51.2500000', '51.1700000', '52.5000000', '55.25
...: 00000'],
...: ['39.7500000', '39.5000000', '36.8100000', '37.2500000']], dtyp
...: e=object)
Out[577]:
array([['34.5500000', '36.9000000', '37.3200000', '37.6700000'],
['41.7900000', '44.8000000', '48.2600000', '46.1800000'],
['36.1200000', '37.1500000', '39.3100000', '38.1000000'],
['82.1000000', '82.0900000', '76.0200000', '77.7000000'],
['48.0100000', '51.2500000', '51.1700000', '52.5000000', '55.2500000'],
['39.7500000', '39.5000000', '36.8100000', '37.2500000']], dtype=object)
In [578]: MyArray=_
In [579]: MyArray.shape
Out[579]: (6,)
In [580]: MyArray[0]
Out[580]: ['34.5500000', '36.9000000', '37.3200000', '37.6700000']
In [581]: MyArray[5]
Out[581]: ['39.7500000', '39.5000000', '36.8100000', '37.2500000']
In [582]: MyArray[4]
Out[582]: ['48.0100000', '51.2500000', '51.1700000', '52.5000000', '55.2500000']
In [583]:
</code></pre>
<p>To <code>slice</code> this you need to iterate on the elements of the array</p>
<pre><code>In [584]: [d[:4] for d in MyArray]
Out[584]:
[['34.5500000', '36.9000000', '37.3200000', '37.6700000'],
['41.7900000', '44.8000000', '48.2600000', '46.1800000'],
['36.1200000', '37.1500000', '39.3100000', '38.1000000'],
['82.1000000', '82.0900000', '76.0200000', '77.7000000'],
['48.0100000', '51.2500000', '51.1700000', '52.5000000'],
['39.7500000', '39.5000000', '36.8100000', '37.2500000']]
</code></pre>
<p>Now with all the sublists the same length, <code>np.array</code> will create a 2d array:</p>
<pre><code>In [585]: np.array(_)
Out[585]:
array([['34.5500000', '36.9000000', '37.3200000', '37.6700000'],
['41.7900000', '44.8000000', '48.2600000', '46.1800000'],
['36.1200000', '37.1500000', '39.3100000', '38.1000000'],
['82.1000000', '82.0900000', '76.0200000', '77.7000000'],
['48.0100000', '51.2500000', '51.1700000', '52.5000000'],
['39.7500000', '39.5000000', '36.8100000', '37.2500000']],
dtype='<U10')
</code></pre>
<p>Still strings, though</p>
<pre><code>In [586]: np.array(__,dtype=float)
Out[586]:
array([[ 34.55, 36.9 , 37.32, 37.67],
[ 41.79, 44.8 , 48.26, 46.18],
[ 36.12, 37.15, 39.31, 38.1 ],
[ 82.1 , 82.09, 76.02, 77.7 ],
[ 48.01, 51.25, 51.17, 52.5 ],
[ 39.75, 39.5 , 36.81, 37.25]])
</code></pre>
| 2 |
2016-09-21T17:13:30Z
|
[
"python",
"arrays",
"numpy"
] |
Slice numpy array to make it desired shaped
| 39,622,059 |
<p>Surprisingly, couldn't find the answer across the internet. I have an n-dimensional numpy array. E.g.: 2-D np array:</p>
<pre><code>array([['34.5500000', '36.9000000', '37.3200000', '37.6700000'],
['41.7900000', '44.8000000', '48.2600000', '46.1800000'],
['36.1200000', '37.1500000', '39.3100000', '38.1000000'],
['82.1000000', '82.0900000', '76.0200000', '77.7000000'],
['48.0100000', '51.2500000', '51.1700000', '52.5000000', '55.2500000'],
['39.7500000', '39.5000000', '36.8100000', '37.2500000']], dtype=object)
</code></pre>
<p>As you can see, the 5th row consists of 5 elemnts and <strong>i want to make the 5th dissapear</strong>, using something like this:</p>
<pre><code>np.slice(MyArray, [6,4])
</code></pre>
<p>[6,4] is a shape. I really DO not want to iterate threw dimensions and cut them. I tried the <code>resize</code> method, but it returns nothing!</p>
| 3 |
2016-09-21T16:37:45Z
| 39,622,939 |
<p>Here's an almost* vectorized approach -</p>
<pre><code>def slice_2Dobject_arr(arr,out_shape):
lens = np.array(map(len,arr))
id_arr = np.ones(lens.sum(),dtype=int)
id_arr[lens[:-1].cumsum()] = -lens[:-1]+1
mask = id_arr.cumsum()<=out_shape[1]
vals = np.concatenate(arr)
return vals[mask].reshape(-1,out_shape[1])[:out_shape[0]]
</code></pre>
<p>*: Almost because of the use of <code>map</code> at the start to get the lengths of the lists in the input array, which seems isn't a vectorized operation. But, computationally that should be comparatively negligible.</p>
<p>Sample runs -</p>
<pre><code>In [92]: arr
Out[92]: array([[3, 4, 5, 3], [3, 7, 8], [4, 9, 6, 4, 2], [3, 9, 4]], dtype=object)
In [93]: slice_2Dobject_arr(arr,(4,3))
Out[93]:
array([[3, 4, 5],
[3, 7, 8],
[4, 9, 6],
[3, 9, 4]])
In [94]: slice_2Dobject_arr(arr,(3,3))
Out[94]:
array([[3, 4, 5],
[3, 7, 8],
[4, 9, 6]])
In [95]: slice_2Dobject_arr(arr,(3,2))
Out[95]:
array([[3, 4],
[3, 7],
[4, 9]])
</code></pre>
| 1 |
2016-09-21T17:25:59Z
|
[
"python",
"arrays",
"numpy"
] |
Pandas Dataframe automatic typecasting
| 39,622,081 |
<p>I am working with a pandas dataframe and need several columns (x & y in the example below) to be an integer and one column to be a float (l). It appears that assigning a new row with a float in it recasts the whole dataframe as a float. Why is this and how do I prevent it?</p>
<pre><code>data = pd.DataFrame(data=[[3103, 1189, 1]],index = None, columns = ['y', 'x', 'l'], dtype = int)
print data.y
data.ix[1] = (3, 3, 3.4)
print data.y
</code></pre>
<p>Which produces: </p>
<pre><code>0 3103
Name: y, dtype: int32
0 3103
1 3
Name: y, dtype: float64
</code></pre>
| 3 |
2016-09-21T16:39:06Z
| 39,622,269 |
<p>You can recast all of the other columns after each addition using:</p>
<pre><code>data['y'] = data['y'].astype(int)
</code></pre>
<p>Not the most efficient solution if you need to add a lot of columns on the fly. Alternatively you could create the entire data frame using Series in advance and type the whole thing a creation time instead if that's an option.</p>
| 1 |
2016-09-21T16:49:37Z
|
[
"python",
"pandas",
"dataframe",
"casting"
] |
How to load a pre-trained Word2vec MODEL File?
| 39,622,106 |
<p>I'm going to use a pre-trained <code>word2vec</code> model, but I don't know how to load it in python.</p>
<p>This file is a MODEL file (703 MB).
<a href="http://devmount.github.io/GermanWordEmbeddings/" rel="nofollow">http://devmount.github.io/GermanWordEmbeddings/</a></p>
| 1 |
2016-09-21T16:40:18Z
| 39,622,188 |
<p>You can use <code>gensim</code> like this:</p>
<pre><code>import gensim
# Load pre-trained Word2Vec model.
model = gensim.models.Word2Vec.load("filename.model")
</code></pre>
<p>More info <a href="http://mccormickml.com/2016/04/12/googles-pretrained-word2vec-model-in-python/" rel="nofollow">here</a></p>
| 1 |
2016-09-21T16:44:53Z
|
[
"python",
"model",
"word2vec"
] |
How do you store an entire array into another array
| 39,622,176 |
<p>How do you store an entire array into another array</p>
<p>suppose I have an array </p>
<pre><code>data = np.array([], dtype=float, ndmin=2)
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
</code></pre>
<p>How do you store the values such that</p>
<pre><code>data = [ [1,2,3],
[4,5,6] ]
</code></pre>
<p>My current method is </p>
<pre><code>data= np.append(data, a)
data= np.append(data, b)
</code></pre>
<p>However this results in [ 1,2,3,4,6]</p>
| 1 |
2016-09-21T16:44:16Z
| 39,622,294 |
<p>You mean like:</p>
<pre><code>>>> data = np.array([a,b])
>>> data
array([[1, 2, 3],
[4, 5, 6]])
</code></pre>
<p>If you want to do it stepwise, you <em>can</em> use append, but you need to make sure all your arguments are rank 2 (or wrapped in a list). Right now, <code>a</code> and <code>b</code> are both rank 1 so if you try to append along a particular axis, you'll get an error. I.e. what you need to do is:</p>
<pre><code>>>> data = np.empty([0,3]); data
array([], shape=(0, 3), dtype=float64)
>>> data = np.append(data, np.array([a]), axis=0); data
array([[ 1., 2., 3.]])
>>> data = np.append(data, np.array([b]), axis=0); data
array([[ 1., 2., 3.],
[ 4., 5., 6.]])
</code></pre>
<p><hr>
PS. However, if the number of rows in <code>data</code> are known (say, 100), you're probably better off preallocating, i.e. initializing it as <code>np.empty([100,3])</code> and filling by index, (e.g. <code>data[0,:] = a</code>)</p>
| 1 |
2016-09-21T16:51:07Z
|
[
"python",
"arrays",
"numpy"
] |
How do you store an entire array into another array
| 39,622,176 |
<p>How do you store an entire array into another array</p>
<p>suppose I have an array </p>
<pre><code>data = np.array([], dtype=float, ndmin=2)
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
</code></pre>
<p>How do you store the values such that</p>
<pre><code>data = [ [1,2,3],
[4,5,6] ]
</code></pre>
<p>My current method is </p>
<pre><code>data= np.append(data, a)
data= np.append(data, b)
</code></pre>
<p>However this results in [ 1,2,3,4,6]</p>
| 1 |
2016-09-21T16:44:16Z
| 39,622,336 |
<p>So you are looking for <code>np.vstack</code>:</p>
<pre><code>a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
data = np.vstack([a,b])
</code></pre>
| 2 |
2016-09-21T16:53:24Z
|
[
"python",
"arrays",
"numpy"
] |
How to convert dictionary list values uniformly in Python 3?
| 39,622,263 |
<p>I have a yaml file with a couple of fields that are lists.</p>
<p>It looks kind of like this:</p>
<pre><code>key0: "value0"
key1: ["value1-0", "value1-1", "value1-2"]
key2: ["value2-0", "value2-1", "value2-2"]
key3: "value3"
</code></pre>
<p>This is naturally converted to a Python dictionary with the PyYAML library.</p>
<p>Eventually I want to get a string of keys and values smashed together as follows:</p>
<p><code>--key0 value0 --key1 value1-0 --key1 value1-1 --key1 value1-2 ... --key3 value3</code></p>
<p>I came up with a solution that is dependent on the fact that I'm dealing with lists but something bugs me and makes me want to ask if there is a more clean, generic and elegant way?</p>
<p>UPD: after @senchuk answer I wanted to make myself a little more clear.</p>
<p>The question is not about ANY solution. This is merely an opinion-based question for people who are more experienced with Python than I am. I'm constantly hearing about this "pythonic" way. This is what I'm looking for! Something with a hipster functional thingy would do. There's no limitation on data transformation whatsoever. If the best way is to convert all of the scalar values to lists and then convert everything to a string, so be it. I'm really curious how this is done today in modern Python.</p>
| 1 |
2016-09-21T16:49:14Z
| 39,622,440 |
<p>If you already have something that converts what you've got into a dictionary, then this should do what you want</p>
<pre><code>d = {'key1' : 'value1', 'key2' : 'value2'}
stringFinal = ''
tempString = ''
for k, v in d.items():
tempString = str(k) + ' ' + str(v)
stringFinal ='--' + tempString + ' ' + stringFinal
tempString = ''
print(stringFinal)
</code></pre>
| 0 |
2016-09-21T16:59:17Z
|
[
"python",
"python-3.x",
"refactoring"
] |
How to convert dictionary list values uniformly in Python 3?
| 39,622,263 |
<p>I have a yaml file with a couple of fields that are lists.</p>
<p>It looks kind of like this:</p>
<pre><code>key0: "value0"
key1: ["value1-0", "value1-1", "value1-2"]
key2: ["value2-0", "value2-1", "value2-2"]
key3: "value3"
</code></pre>
<p>This is naturally converted to a Python dictionary with the PyYAML library.</p>
<p>Eventually I want to get a string of keys and values smashed together as follows:</p>
<p><code>--key0 value0 --key1 value1-0 --key1 value1-1 --key1 value1-2 ... --key3 value3</code></p>
<p>I came up with a solution that is dependent on the fact that I'm dealing with lists but something bugs me and makes me want to ask if there is a more clean, generic and elegant way?</p>
<p>UPD: after @senchuk answer I wanted to make myself a little more clear.</p>
<p>The question is not about ANY solution. This is merely an opinion-based question for people who are more experienced with Python than I am. I'm constantly hearing about this "pythonic" way. This is what I'm looking for! Something with a hipster functional thingy would do. There's no limitation on data transformation whatsoever. If the best way is to convert all of the scalar values to lists and then convert everything to a string, so be it. I'm really curious how this is done today in modern Python.</p>
| 1 |
2016-09-21T16:49:14Z
| 39,622,847 |
<p>You can iterate through the dictionary to build a string. if the item is a list, you have to iterate through its elements.</p>
<p>NOTE: since dictionary is an unordered collection, the output may vary.</p>
<pre><code>dict={"key0": "value0", "key1": ["value1-0", "value1-1", "value1-2"], "key2": ["value2-0", "value2-1", "value2-2"], "key3": "value3"}
s = ''
for k,v in dict.items():
print(k, v)
if type(v) is list:
for elem in v:
s+= '--' + k + ' ' + str(elem) + ' '
else:
s+= '--' + k + ' ' + str(v) + ' '
print(s)
>>> --key1 value1-0 --key1 value1-1 --key1 value1-2 --key0 value0 --key3 value3 --key2 value2-0 --key2 value2-1 --key2 value2-2
</code></pre>
| 0 |
2016-09-21T17:21:11Z
|
[
"python",
"python-3.x",
"refactoring"
] |
capture one frame from a video file after every 10 seconds
| 39,622,281 |
<p>I want to capture from a video file one frame after every 10 seconds, So if anyone can help me for that i will be very thankful. my python code is like that:</p>
<pre><code>import cv2
print(cv2.__version__)
vidcap = cv2.VideoCapture('Standoff.avi')
vidcap.set(cv2.CAP_PROP_POS_MSEC,96000)
success,image = vidcap.read()
count = 0
success = True
while success:
success,image = vidcap.read()
print 'Read a new frame: ', success
cv2.imwrite("frame%d.jpg" % count, image) # save frame as JPEG file
cv2.waitKey(200)
count += 1
</code></pre>
| 1 |
2016-09-21T16:50:15Z
| 39,658,034 |
<p>If you can get the framerate of the video from the file the following should work (You may need to check the syntax as I have not tested it):</p>
<pre class="lang-js prettyprint-override"><code>import numpy as np
import cv2
cap = cv2.VideoCapture('Standoff.avi')
framerate = cap.get(cv2.cv.CV_CAP_PROP_FPS)
framecount = 0
while(True):
# Capture frame-by-frame
success, image = cap.read()
frame count += 1
# Check if this is the frame closest to 10 seconds
if framecount = (framerate * 10)
framecont = 0
cv2.imshow('image',image)
# Check end of video
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
</code></pre>
| 0 |
2016-09-23T10:04:01Z
|
[
"python",
"video",
"video-capture"
] |
Why exhausted generators raise StopIteration more than once?
| 39,622,288 |
<p>Why is it that when an exhausted generator is called several times, <code>StopIteration</code> is raised every time, rather than just on the first attempt? Aren't subsequent calls meaningless, and indicate a likely bug in the caller's code?</p>
<pre><code>def gen_func():
yield 1
yield 2
gen = gen_func()
next(gen)
next(gen)
next(gen) # StopIteration as expected
next(gen) # why StopIteration and not something to warn me that I'm doing something wrong
</code></pre>
<p>This also results in this behavior when someone accidentally uses an expired generator:</p>
<pre><code>def do_work(gen):
for x in gen:
# do stuff with x
pass
# here I forgot that I already used up gen
# so the loop does nothing without raising any exception or warning
for x in gen:
# do stuff with x
pass
def gen_func():
yield 1
yield 2
gen = gen_func()
do_work(gen)
</code></pre>
<p>If second and later attempts to call an exhausted generator raised a different exception, it would have been easier to catch this type of bugs.</p>
<p>Perhaps there's an important use case for calling exhausted generators multiple times and getting <code>StopIteration</code>?</p>
| 3 |
2016-09-21T16:50:42Z
| 39,622,498 |
<blockquote>
<p>Perhaps there's an important use case for calling exhausted generators multiple times and getting <code>StopIteration</code>?</p>
</blockquote>
<p>There is, specifically, when you want to perform multiple loops on the same iterator. Here's an example from the <a href="https://docs.python.org/3/library/itertools.html" rel="nofollow"><code>itertools</code></a> docs that relies on this behavior:</p>
<pre><code>def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
</code></pre>
| 2 |
2016-09-21T17:03:09Z
|
[
"python",
"python-3.x",
"generator"
] |
Why exhausted generators raise StopIteration more than once?
| 39,622,288 |
<p>Why is it that when an exhausted generator is called several times, <code>StopIteration</code> is raised every time, rather than just on the first attempt? Aren't subsequent calls meaningless, and indicate a likely bug in the caller's code?</p>
<pre><code>def gen_func():
yield 1
yield 2
gen = gen_func()
next(gen)
next(gen)
next(gen) # StopIteration as expected
next(gen) # why StopIteration and not something to warn me that I'm doing something wrong
</code></pre>
<p>This also results in this behavior when someone accidentally uses an expired generator:</p>
<pre><code>def do_work(gen):
for x in gen:
# do stuff with x
pass
# here I forgot that I already used up gen
# so the loop does nothing without raising any exception or warning
for x in gen:
# do stuff with x
pass
def gen_func():
yield 1
yield 2
gen = gen_func()
do_work(gen)
</code></pre>
<p>If second and later attempts to call an exhausted generator raised a different exception, it would have been easier to catch this type of bugs.</p>
<p>Perhaps there's an important use case for calling exhausted generators multiple times and getting <code>StopIteration</code>?</p>
| 3 |
2016-09-21T16:50:42Z
| 39,622,585 |
<p>It is a part of the iteration protocol:</p>
<blockquote>
<p>Once an iteratorâs <code>__next__()</code> method raises StopIteration, it must
continue to do so on subsequent calls. Implementations that do not
obey this property are deemed broken.</p>
</blockquote>
<p>Source: <a href="https://docs.python.org/3/library/stdtypes.html#iterator-types" rel="nofollow">https://docs.python.org/3/library/stdtypes.html#iterator-types</a></p>
| 3 |
2016-09-21T17:07:34Z
|
[
"python",
"python-3.x",
"generator"
] |
Barrier after spawned mpi4py process
| 39,622,415 |
<p>I have a piece of code that uses mpi4py to spawn several instances of an mpi exectuable. I want the code to halt while these processes complete, and then call a second group of the same executable.</p>
<p>The problem is that all calls to the mpi executable get spawned immediately.</p>
<p>It seems like there is no way to use a barrier to prevent this from happening. Does anyone know if this is correct, and if so does anyone have a bright idea to get the result I need.</p>
<pre><code>#!/usr/bin/env python
from mpi4py import MPI
import numpy
import sys
import os
rank = MPI.COMM_WORLD.Get_rank()
new_comm = MPI.COMM_WORLD.Split(color=rank, key=rank)
print(new_comm.Get_rank())
cwd=os.getcwd()
directory=os.path.join(cwd,str(rank))
print(rank,directory)
os.chdir(directory)
new_comm.Spawn("SOME_F90_MPI_EXECUTABLE",
args=None,
maxprocs=4)
'''I want to pause here until the spawned processes finish running...'''
new_comm.Barrier()
MPI.COMM_WORLD.Barrier()
print(new_comm.Get_rank())
cwd=os.getcwd()
directory=os.path.join(cwd,str(rank))
print(rank,directory)
os.chdir(directory+"_2")
new_comm.Spawn("SOME_F90_MPI_EXECUTABLE",
args=["> output"],
maxprocs=4)
new_comm.Disconnect()
print("All finished here.....")
</code></pre>
<p>Thanks!</p>
| 0 |
2016-09-21T16:57:55Z
| 39,636,470 |
<p>You must use the <em>intercommunicator</em> returned by <code>Spawn</code>:</p>
<pre><code>child_comm = MPI.COMM_WORLD.Spawn("./spawnchild.py", args=None, maxprocs=2)
child_comm.Barrier()
</code></pre>
<p>For the child, get the parent <em>intercommunicator</em> (similarly in Fortran):</p>
<pre><code>parent = MPI.COMM_WORLD.Get_parent()
assert(parent != MPI.COMM_NULL)
parent.Barrier();
</code></pre>
<p>Note that an <em>intercommunicator</em>, which consists of processes from two groups, behaves different than a traditional <em>intercommunicator</em>. E.g. for the Barrier, the following semantics apply:</p>
<blockquote>
<p>If comm is an intercommunicator, <code>MPI_BARRIER</code> involves two groups. The call returns at processes in one group (group A) of the intercommunicator only after all members of the other group (group B) have entered the call (and vice versa). A process may return from the call before all processes in its own group have entered the call.</p>
</blockquote>
<p>(<a href="http://mpi-forum.org/docs/" rel="nofollow">MPI 3.1 Standard</a>, 5.3)</p>
| 1 |
2016-09-22T10:21:54Z
|
[
"python",
"parallel-processing",
"mpi",
"mpi4py"
] |
Cumulative Set in PANDAS
| 39,622,487 |
<p>I have a dataframe of tweets and I'm looking to group the dataframe by date and generate a column that contains a cumulative list of all the unique users who have posted up to that date. None of the existing functions (e.g., cumsum) would appear to work for this. Here's a sample of the original tweet dataframe, where the index (created_at) is in datetime format:</p>
<pre><code>In [3]: df
Out[3]:
screen_name
created_at
04-01-16 Bob
04-01-16 Bob
04-01-16 Sally
04-01-16 Sally
04-02-16 Bob
04-02-16 Miguel
04-02-16 Tim
</code></pre>
<p>I can collapse the dataset by date and get a column with the unique users per day:</p>
<pre><code>In [4]: df[['screen_name']].groupby(df.index.date).aggregate(lambda x: set(list(x)))
Out[4]: from_user_screen_name
2016-04-02 {Bob, Sally}
2016-04-03 {Bob, Miguel, Tim}
</code></pre>
<p>So far so good. But what I'd like is to have a "cumulative set" like this:</p>
<pre><code>Out[4]: Cumulative_list_up_to_this_date Cumulative_number_of_unique_users
2016-04-02 {Bob, Sally} 2
2016-04-03 {Bob, Sally, Miguel, Tim} 4
</code></pre>
<p>Ultimately, what I am really interested in is the cumulative number in the last column so I can plot it. I've considered looping over dates and other things but can't seem to find a good way. Thanks in advance for any help. </p>
| 0 |
2016-09-21T17:02:06Z
| 39,623,235 |
<p>You cannot add sets, but can add lists! So build a list of users, then take the cumulative sum and finally apply the set constructor to get rid of duplicates.</p>
<pre><code>cum_names = (df['screen_name'].groupby(df.index.date)
.agg(lambda x: list(x))
.cumsum()
.apply(set))
# 2016-04-01 {Bob, Sally}
# 2016-04-02 {Bob, Miguel, Tim, Sally}
# dtype: object
cum_count = cum_names.apply(len)
# 2016-04-01 2
# 2016-04-02 4
# dtype: int64
</code></pre>
| 3 |
2016-09-21T17:43:40Z
|
[
"python",
"pandas"
] |
Python 3.5.2 internet explorer control
| 39,622,496 |
<p>how do i open a download link like <a href="http://ops.epo.org/3.1/rest-services/published-data/images/EP/1000000/A1/thumbnail?Range=1" rel="nofollow">http://ops.epo.org/3.1/rest-services/published-data/images/EP/1000000/A1/thumbnail?Range=1</a> in the Internet Explorer and save it without pushing 'save' in a file like '1.jpg'?
I heard about the 'internet explorer control'.
Can you help me? </p>
<p>I would like to have a programm that can download a lot of images like in this link automatically without pushing every time 'save'.</p>
| 0 |
2016-09-21T17:03:09Z
| 39,731,291 |
<p>It looks like its a PDF file. This could be achieved using basic request example</p>
<pre><code>import requests
url='http://ops.epo.org/3.1/rest-services/published-data/images/EP/1000000/A1/thumbnail?Range=1'
r = requests.get(url)
with open('1.pdf', 'wb') as fh:
fh.write(r.content)
</code></pre>
| 0 |
2016-09-27T17:53:31Z
|
[
"python",
"image",
"download"
] |
Python 3.2+ converting int to bytes
| 39,622,527 |
<p>I'm having a problem converting int to bytes in Python. </p>
<p>This works - </p>
<pre><code>>>> (1024).to_bytes(2, 'big')
b'\x04\x00'
</code></pre>
<p>However this does not work as I would expect - </p>
<pre><code>>>> (33).to_bytes(2, 'big')
b'\x00!'
</code></pre>
<p>What am I not understanding?</p>
| 1 |
2016-09-21T17:04:30Z
| 39,622,597 |
<p><code>!</code> has the decimal value 33 by ascii standarts, so that python-shell can show it without escape codes, and so it does.</p>
<pre><code>>>> x = b'\x00\x21'
>>> x
b'\x00!'
</code></pre>
| 5 |
2016-09-21T17:08:25Z
|
[
"python",
"python-3.2"
] |
Python 3.2+ converting int to bytes
| 39,622,527 |
<p>I'm having a problem converting int to bytes in Python. </p>
<p>This works - </p>
<pre><code>>>> (1024).to_bytes(2, 'big')
b'\x04\x00'
</code></pre>
<p>However this does not work as I would expect - </p>
<pre><code>>>> (33).to_bytes(2, 'big')
b'\x00!'
</code></pre>
<p>What am I not understanding?</p>
| 1 |
2016-09-21T17:04:30Z
| 39,622,602 |
<p>You're not understanding that <code>!</code> is ASCII character 33, equivalent to <code>\x21</code>. This bytestring is exactly the bytestring you asked for; it just isn't displayed the way you were expecting.</p>
| 1 |
2016-09-21T17:08:33Z
|
[
"python",
"python-3.2"
] |
Python 3.2+ converting int to bytes
| 39,622,527 |
<p>I'm having a problem converting int to bytes in Python. </p>
<p>This works - </p>
<pre><code>>>> (1024).to_bytes(2, 'big')
b'\x04\x00'
</code></pre>
<p>However this does not work as I would expect - </p>
<pre><code>>>> (33).to_bytes(2, 'big')
b'\x00!'
</code></pre>
<p>What am I not understanding?</p>
| 1 |
2016-09-21T17:04:30Z
| 39,622,731 |
<p>According to documentation -> <a href="https://docs.python.org/3.3/library/stdtypes.html" rel="nofollow">https://docs.python.org/3.3/library/stdtypes.html</a></p>
<pre><code> >>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
>>> (1024).to_bytes(10, byteorder='big')
b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
>>> (-1024).to_bytes(10, byteorder='big', signed=True)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
>>> x = 1000
>>> x.to_bytes((x.bit_length() // 8) + 1, byteorder='little')
b'\xe8\x03'
</code></pre>
| 0 |
2016-09-21T17:15:15Z
|
[
"python",
"python-3.2"
] |
numpy array as datatype in a structured array?
| 39,622,533 |
<p>I was wondering if it is possible to have a numpy.array as a datatype in a structured array. This is the idea:</p>
<pre><code>import numpy
raw_data = [(1, numpy.array([1,2,3])),
(2, numpy.array([4,5,6])),
(3, numpy.array([7,8,9]))]
data = numpy.array(raw_data, dtype=[('num', float),
('arr', numpy.array)])
</code></pre>
<p>I have a list of tuples consisting of an integer and an array and would like to turn this into a structured array. Right now, Python complains that it does not understand the 'numpy.array' datatype. Is there another way to refer to the array datatype?</p>
<p>The motivation behind is to be able to do things like:</p>
<pre><code>print numpy.min(data['arr'], axis=0)
print numpy.min(data['arr'], axis=1)
</code></pre>
<p>and other operations.</p>
| 0 |
2016-09-21T17:04:45Z
| 39,622,632 |
<p>Yes, you can create compound fields that look like arrays within the structured array; for example:</p>
<pre><code>import numpy as np
raw_data = [(1, np.array([1,2,3])),
(2, np.array([4,5,6])),
(3, np.array([7,8,9]))]
tp = np.dtype([('id', int), ('arr', float, (3,))])
x = np.array(raw_data, dtype=tp)
</code></pre>
<p>Result looks like this:</p>
<pre><code>>>> x
array([(1, [1.0, 2.0, 3.0]), (2, [4.0, 5.0, 6.0]), (3, [7.0, 8.0, 9.0])],
dtype=[('id', '<i8'), ('arr', '<f8', (3,))])
</code></pre>
| 1 |
2016-09-21T17:10:12Z
|
[
"python",
"arrays",
"numpy",
"structured-array"
] |
Python: Document results and figures into tex document
| 39,622,537 |
<p>I currently have written a script that produces several figures. I was wondering if there is a way to publish these figures directly into a tex file, say in eps format without including all of the python code verbatim. I also want to include the values of some variables. I looked at the module pweave (<a href="http://mpastell.com/pweave/" rel="nofollow">http://mpastell.com/pweave/</a>) but I couldn't figure out a way to exclude code chunks. I'm new to python so any help would be much appreciated!</p>
| 1 |
2016-09-21T17:04:54Z
| 39,623,365 |
<p>You can use pweave. If you want a code chunk to be executed but not formatted, set the echo property to false. See
<a href="http://mpastell.com/pweave/chunks.html#envvar-echo=Trueor(False)" rel="nofollow">http://mpastell.com/pweave/chunks.html#envvar-echo=Trueor(False)</a></p>
| 0 |
2016-09-21T17:50:36Z
|
[
"python",
"documentation",
"pweave"
] |
Interest Calculator looping issue Python
| 39,622,596 |
<p>beginner here. I've made an interest calculator program to help me with my loans of different sorts. I'm having two issues to finalize my program. Here's the program. I tried looking up the problems but I wasn't sure how to word it so I thought I'd just ask a question in total.</p>
<pre><code>x=1
while x==1:
import math
loan=input("Enter Loan amount: ")
rate=input("Enter rate: ")
if rate.isalpha() or loan.isalpha():
print("Hey that's not a number!")
break
rate=rate.replace("%","")
loan=float(loan)
rate=float(rate)*0.01
amount1y=round(loan*(math.e**(rate*1)),2)
amount5y=round(loan*(math.e**(rate*5)),2)
amount10y=round(loan*(math.e**(rate*10)),2)
monthlypay=round(amount1y-loan,2)
print("Year 1 without pay: " + str(amount1y))
print("Year 5 without pay: " + str(amount5y))
print("Year 10 without pay: " + str(amount10y))
print("Amount to pay per year: " + str(monthlypay))
print("Want to do another? Y/N?")
ans=input('')
ans=ans.lower()
y=True
while y==True:
if ans=="n" or ans=="no":
x=0
break
elif ans=="y" or ans=="yes":
y=False
else:
print("You gotta tell me Yes or No fam...")
print("I'll just assume that mean's yes.")
break
</code></pre>
<p>My issue is in two locations. First during the</p>
<pre><code>if rate.isalpha() or loan.isalpha():
print("Hey that's not a number!")
break
</code></pre>
<p>How do I write this so that instead of it ending the program all together, it instead restarts from the top until they put in a number. Also as a side just for fun and knowledge. Lets say they enter text three times in a row, and at that point it just executes the program how would I go about doing that also?
Finally during this part of the code:</p>
<pre><code> while y==True:
if ans=="n" or ans=="no":
x=0
break
elif ans=="y" or ans=="yes":
y=False
else:
print("You gotta tell me Yes or No fam...")
print("I'll just assume that mean's yes.")
break
</code></pre>
<p>the else at the end, without that break, will continue printing "You gotta tell me Yes or No fam..." forever. How do I make it so that instead of breaking the while statement, it'll just restart the while statement asking the question again?</p>
<p>Thanks for your help!
P.S. This is python 3.4.2</p>
| 0 |
2016-09-21T17:08:22Z
| 39,622,893 |
<p>On both of your examples, I believe your looking for Python's <code>continue</code> <a href="https://docs.python.org/3/reference/simple_stmts.html#continue" rel="nofollow">statement</a>. From the Python Docs:</p>
<p>(emphasis mine)</p>
<blockquote>
<p>continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition or finally clause within that loop. <strong>It continues with the next cycle of the nearest enclosing loop.</strong>
When continue passes control out of a try statement with a finally clause, that finally clause is executed before really starting the next loop cycle.</p>
</blockquote>
<p>This basically means it will "restart" your <code>for/while</code>-loop.</p>
<hr>
<p>To address your side note of breaking the loop if they get the input wrong after three tries, use a counter variable. increment the counter variable each time the user provides the wrong input, and then check and see if the counter variable is greater than 3. Example:</p>
<pre><code>counter = 0
running = True:
while running:
i = input("Enter number: ")
if i.isalpha():
print("Invalid input")
counter+=1
if counter >= 3:
print("Exiting loop")
break
</code></pre>
<p><strong>Unrelated notes:</strong></p>
<ul>
<li>Why not use a boolean value for <code>x</code> as well?</li>
<li>I usually recommend putting any imports at the module level for the structure an readability of one's program.</li>
</ul>
| 0 |
2016-09-21T17:23:31Z
|
[
"python"
] |
Interest Calculator looping issue Python
| 39,622,596 |
<p>beginner here. I've made an interest calculator program to help me with my loans of different sorts. I'm having two issues to finalize my program. Here's the program. I tried looking up the problems but I wasn't sure how to word it so I thought I'd just ask a question in total.</p>
<pre><code>x=1
while x==1:
import math
loan=input("Enter Loan amount: ")
rate=input("Enter rate: ")
if rate.isalpha() or loan.isalpha():
print("Hey that's not a number!")
break
rate=rate.replace("%","")
loan=float(loan)
rate=float(rate)*0.01
amount1y=round(loan*(math.e**(rate*1)),2)
amount5y=round(loan*(math.e**(rate*5)),2)
amount10y=round(loan*(math.e**(rate*10)),2)
monthlypay=round(amount1y-loan,2)
print("Year 1 without pay: " + str(amount1y))
print("Year 5 without pay: " + str(amount5y))
print("Year 10 without pay: " + str(amount10y))
print("Amount to pay per year: " + str(monthlypay))
print("Want to do another? Y/N?")
ans=input('')
ans=ans.lower()
y=True
while y==True:
if ans=="n" or ans=="no":
x=0
break
elif ans=="y" or ans=="yes":
y=False
else:
print("You gotta tell me Yes or No fam...")
print("I'll just assume that mean's yes.")
break
</code></pre>
<p>My issue is in two locations. First during the</p>
<pre><code>if rate.isalpha() or loan.isalpha():
print("Hey that's not a number!")
break
</code></pre>
<p>How do I write this so that instead of it ending the program all together, it instead restarts from the top until they put in a number. Also as a side just for fun and knowledge. Lets say they enter text three times in a row, and at that point it just executes the program how would I go about doing that also?
Finally during this part of the code:</p>
<pre><code> while y==True:
if ans=="n" or ans=="no":
x=0
break
elif ans=="y" or ans=="yes":
y=False
else:
print("You gotta tell me Yes or No fam...")
print("I'll just assume that mean's yes.")
break
</code></pre>
<p>the else at the end, without that break, will continue printing "You gotta tell me Yes or No fam..." forever. How do I make it so that instead of breaking the while statement, it'll just restart the while statement asking the question again?</p>
<p>Thanks for your help!
P.S. This is python 3.4.2</p>
| 0 |
2016-09-21T17:08:22Z
| 39,622,900 |
<p>You make an infinite loop, that you <code>break</code> out of when all is well. Simplified:</p>
<pre><code>while True:
x_as_string = input("Value")
try:
x = float(x_as_string)
except ValueError:
print("I can't convert", x_as_string)
else:
break
</code></pre>
<p>It is easier to ask forgiveness than permission: You try to convert. If conversion fails you print a notice and continue looping <code>else</code> you <code>break</code> out of the loop.</p>
| 1 |
2016-09-21T17:23:56Z
|
[
"python"
] |
Interest Calculator looping issue Python
| 39,622,596 |
<p>beginner here. I've made an interest calculator program to help me with my loans of different sorts. I'm having two issues to finalize my program. Here's the program. I tried looking up the problems but I wasn't sure how to word it so I thought I'd just ask a question in total.</p>
<pre><code>x=1
while x==1:
import math
loan=input("Enter Loan amount: ")
rate=input("Enter rate: ")
if rate.isalpha() or loan.isalpha():
print("Hey that's not a number!")
break
rate=rate.replace("%","")
loan=float(loan)
rate=float(rate)*0.01
amount1y=round(loan*(math.e**(rate*1)),2)
amount5y=round(loan*(math.e**(rate*5)),2)
amount10y=round(loan*(math.e**(rate*10)),2)
monthlypay=round(amount1y-loan,2)
print("Year 1 without pay: " + str(amount1y))
print("Year 5 without pay: " + str(amount5y))
print("Year 10 without pay: " + str(amount10y))
print("Amount to pay per year: " + str(monthlypay))
print("Want to do another? Y/N?")
ans=input('')
ans=ans.lower()
y=True
while y==True:
if ans=="n" or ans=="no":
x=0
break
elif ans=="y" or ans=="yes":
y=False
else:
print("You gotta tell me Yes or No fam...")
print("I'll just assume that mean's yes.")
break
</code></pre>
<p>My issue is in two locations. First during the</p>
<pre><code>if rate.isalpha() or loan.isalpha():
print("Hey that's not a number!")
break
</code></pre>
<p>How do I write this so that instead of it ending the program all together, it instead restarts from the top until they put in a number. Also as a side just for fun and knowledge. Lets say they enter text three times in a row, and at that point it just executes the program how would I go about doing that also?
Finally during this part of the code:</p>
<pre><code> while y==True:
if ans=="n" or ans=="no":
x=0
break
elif ans=="y" or ans=="yes":
y=False
else:
print("You gotta tell me Yes or No fam...")
print("I'll just assume that mean's yes.")
break
</code></pre>
<p>the else at the end, without that break, will continue printing "You gotta tell me Yes or No fam..." forever. How do I make it so that instead of breaking the while statement, it'll just restart the while statement asking the question again?</p>
<p>Thanks for your help!
P.S. This is python 3.4.2</p>
| 0 |
2016-09-21T17:08:22Z
| 39,623,048 |
<p>Your problem is straightforward. You have to use <a href="https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops" rel="nofollow"><code>continue</code></a> or <a href="https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops" rel="nofollow"><code>break</code></a> wisely. These are called control flow statements. They control the normal flow of execution of your program. So <code>continue</code> will jump to the top-most line in your loop and <code>break</code> will simply jump <em>out</em> of your loop completely, be it a <code>for</code> or <code>while</code> loop. </p>
<p>Going back to your code: </p>
<blockquote>
<p>How do I write this so that instead of it ending the program all together, it instead restarts from the top until they put in a number.</p>
</blockquote>
<pre><code>if rate.isalpha() or loan.isalpha():
print("Hey that's not a number!")
continue
</code></pre>
<p>This way, you jump back (you continue) in your loop to the first line: <code>import math</code>. Doing imports inside a loop isn't useful this way the import statement is useless as your imported module is already in <code>sys.modules</code> list as such the <code>import</code> statement won't bother to import it; if you're using <code>reload</code> from <code>imp</code> in 3.X or available in <code>__builtin__</code> in Python 2.x, then this might sound more reasonable here. </p>
<p><em>Ditto:</em> </p>
<pre><code>if ans=="n" or ans=="no":
x=0
break
elif ans=="y" or ans=="yes":
continue
else:
print("You gotta tell me Yes or No fam...")
print("I'll just assume that mean's yes.")
continue
</code></pre>
<p>To state this snippet in English: if <code>ans</code> is equal to <code>"n"</code> or <code>"no"</code> then break the loop; else if <code>ans</code> is equal to <code>"y"</code> or <code>"yes"</code> then continue. If nothing of that happened, then (<code>else</code>) <code>continue</code>. The nested <code>while</code> loop isn't needed.</p>
<blockquote>
<p>Lets say they enter text three times in a row, and at that point it just executes the program how would I go about doing that also? </p>
</blockquote>
<p>Not sure if I understood your question, you can take input three times in different ways: </p>
<pre><code>for line in range(3):
in = input("Enter text for lineno", line)
...do something...
</code></pre>
| 0 |
2016-09-21T17:33:42Z
|
[
"python"
] |
BeautifulSoup4 is not working even though I have successfully installed it using pip Linux Mint Sarah
| 39,622,609 |
<p>I am a brand new linux user using linux mint sarah and I just installed python 3.5 as well as BeautifulSoup to do some web scraping.</p>
<p>However, when I type in the following command I receive a traceback error:</p>
<p>from bs4 import BeautifulSoup</p>
<p>The error tells me that there is no module bs4.</p>
<p>I have also tried:
import bs4
from BeautifulSoup import BeautifulSoup
import beautifulsoup</p>
<p>This is weird because if I go into terminal and give the command pip list, it shows me a list of all my programs and it states that I have beautifulsoup4 (4.5.1)</p>
<p>I successfully used pip in the same exact way to install a module called requests and it was successful.</p>
<p>One thing that I think may be getting in the way is that Linux mint comes with python 2.7 installed and my modules are going into a 2.7 folder which seems odd. (However, the requests module that I can successfully use is in the same folder as the BeautifulSoup4 module) </p>
<p>I must admit I have not tried easy_install because it gives me some error about the directory not existing when I try to install BeautifulSoup4 that way.</p>
<p>I'm muddying the waters too much so I will leave it at that. Hopefully, somebody can help me figure out whats going on so that people who have this problem in the future can benefit.</p>
<p>Thanks!</p>
| 0 |
2016-09-21T17:08:51Z
| 39,622,872 |
<p>You need to install <strong>BeautifulSoup4</strong> for <strong>Python 3.5</strong>.</p>
<p><strong>Option 1:</strong></p>
<ul>
<li>Download <a href="https://bootstrap.pypa.io/get-pip.py" rel="nofollow">https://bootstrap.pypa.io/get-pip.py</a> file to server.</li>
<li>Run <code>python3 get-pip.py</code></li>
<li>Run <code>pip3 install beautifulsoup4</code></li>
</ul>
<p><strong>Option 2:</strong></p>
<ul>
<li>Download <a href="https://pypi.python.org/pypi/beautifulsoup4" rel="nofollow">https://pypi.python.org/pypi/beautifulsoup4</a> to server.</li>
<li><p>Extract tar.gz: <code>tar -xvzf beautifulsoup4-4.5.1.tar.gz</code></p></li>
<li><p>Go to folder: <code>cd beautifulsoup4-4.5.1/</code></p></li>
<li><p>Install from source: <code>python3 setup.py install</code></p></li>
</ul>
| 0 |
2016-09-21T17:22:42Z
|
[
"python",
"linux",
"bs4"
] |
How to break numpy array into smaller chunks/batches, then iterate through them
| 39,622,639 |
<p>Suppose i have this numpy array</p>
<pre><code>[[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]]
</code></pre>
<p>And i want to split it in 2 batches and then iterate:</p>
<pre><code>[[1, 2, 3], Batch 1
[4, 5, 6]]
[[7, 8, 9], Batch 2
[10, 11, 12]]
</code></pre>
<p>What is the simplest way to do it?</p>
<p>EDIT: <strong>I'm deeply sorry i missed putting such info</strong>: Once i intend to carry on with the iteration, the original array would be destroyed due to splitting and iterating over batches. Once the batch iteration finished, i need to restart again from the first batch hence <strong>I should preserve that the original array wouldn't be destroyed</strong>. The whole idea is to be consistent with Stochastic Gradient Descent algorithms which require iterations over batches. In a typical example, I could have a 100000 iteration For loop for just 1000 batch that should be replayed again and again.</p>
| 2 |
2016-09-21T17:10:32Z
| 39,622,748 |
<p>do like this:</p>
<pre><code>a = [[1, 2, 3],[4, 5, 6],
[7, 8, 9],[10, 11, 12]]
b = a[0:2]
c = a[2:4]
</code></pre>
| 0 |
2016-09-21T17:15:59Z
|
[
"python",
"pandas",
"numpy"
] |
How to break numpy array into smaller chunks/batches, then iterate through them
| 39,622,639 |
<p>Suppose i have this numpy array</p>
<pre><code>[[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]]
</code></pre>
<p>And i want to split it in 2 batches and then iterate:</p>
<pre><code>[[1, 2, 3], Batch 1
[4, 5, 6]]
[[7, 8, 9], Batch 2
[10, 11, 12]]
</code></pre>
<p>What is the simplest way to do it?</p>
<p>EDIT: <strong>I'm deeply sorry i missed putting such info</strong>: Once i intend to carry on with the iteration, the original array would be destroyed due to splitting and iterating over batches. Once the batch iteration finished, i need to restart again from the first batch hence <strong>I should preserve that the original array wouldn't be destroyed</strong>. The whole idea is to be consistent with Stochastic Gradient Descent algorithms which require iterations over batches. In a typical example, I could have a 100000 iteration For loop for just 1000 batch that should be replayed again and again.</p>
| 2 |
2016-09-21T17:10:32Z
| 39,622,821 |
<p>consider array <code>a</code></p>
<pre><code>a = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]])
</code></pre>
<p><strong><em>Option 1</em></strong><br>
use <code>reshape</code> and <code>//</code></p>
<pre><code>a.reshape(a.shape[0] // 2, -1, a.shape[1])
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]]])
</code></pre>
<p><strong><em>Option 2</em></strong><br>
if you wanted groups of two rather than two groups</p>
<pre><code>a.reshape(-1, 2, a.shape[1])
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]]])
</code></pre>
<p><strong><em>Option 3</em></strong><br>
Use a generator</p>
<pre><code>def get_every_n(a, n=2):
for i in range(a.shape[0] // 2):
yield a[2*i:2*(i+1)]
for sa in get_every_n(a):
print sa
[[1 2 3]
[4 5 6]]
[[ 7 8 9]
[10 11 12]]
</code></pre>
| 3 |
2016-09-21T17:19:43Z
|
[
"python",
"pandas",
"numpy"
] |
How to break numpy array into smaller chunks/batches, then iterate through them
| 39,622,639 |
<p>Suppose i have this numpy array</p>
<pre><code>[[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]]
</code></pre>
<p>And i want to split it in 2 batches and then iterate:</p>
<pre><code>[[1, 2, 3], Batch 1
[4, 5, 6]]
[[7, 8, 9], Batch 2
[10, 11, 12]]
</code></pre>
<p>What is the simplest way to do it?</p>
<p>EDIT: <strong>I'm deeply sorry i missed putting such info</strong>: Once i intend to carry on with the iteration, the original array would be destroyed due to splitting and iterating over batches. Once the batch iteration finished, i need to restart again from the first batch hence <strong>I should preserve that the original array wouldn't be destroyed</strong>. The whole idea is to be consistent with Stochastic Gradient Descent algorithms which require iterations over batches. In a typical example, I could have a 100000 iteration For loop for just 1000 batch that should be replayed again and again.</p>
| 2 |
2016-09-21T17:10:32Z
| 39,623,292 |
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html" rel="nofollow"><code>numpy.split</code></a> to split along the first axis <code>n</code> times, where <code>n</code> is the number of desired batches. Thus, the implementation would look like this -</p>
<pre><code>np.split(arr,n,axis=0) # n is number of batches
</code></pre>
<p>Since, the default value for <code>axis</code> is <code>0</code> itself, so we can skip setting it. So, we would simply have -</p>
<pre><code>np.split(arr,n)
</code></pre>
<p>Sample runs -</p>
<pre><code>In [132]: arr # Input array of shape (10,3)
Out[132]:
array([[170, 52, 204],
[114, 235, 191],
[ 63, 145, 171],
[ 16, 97, 173],
[197, 36, 246],
[218, 75, 68],
[223, 198, 84],
[206, 211, 151],
[187, 132, 18],
[121, 212, 140]])
In [133]: np.split(arr,2) # Split into 2 batches
Out[133]:
[array([[170, 52, 204],
[114, 235, 191],
[ 63, 145, 171],
[ 16, 97, 173],
[197, 36, 246]]), array([[218, 75, 68],
[223, 198, 84],
[206, 211, 151],
[187, 132, 18],
[121, 212, 140]])]
In [134]: np.split(arr,5) # Split into 5 batches
Out[134]:
[array([[170, 52, 204],
[114, 235, 191]]), array([[ 63, 145, 171],
[ 16, 97, 173]]), array([[197, 36, 246],
[218, 75, 68]]), array([[223, 198, 84],
[206, 211, 151]]), array([[187, 132, 18],
[121, 212, 140]])]
</code></pre>
| 3 |
2016-09-21T17:46:35Z
|
[
"python",
"pandas",
"numpy"
] |
AES / RSA implementation from Python to C#
| 39,622,646 |
<p>I want to migrate following python code into c#.
The entry point is the method encrypted_request</p>
<p>I have no real clue about aes/rsa in python or in c#.
Maybe someone could explain the different code sections and if possible give me a hint how to implement that in c#.
Especially the magic numbers used here and there I do not understand.</p>
<pre><code>modulus = ('00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7'
'b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280'
'104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932'
'575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b'
'3ece0462db0a22b8e7')
nonce = '0CoJUm6Qyw8W8jud'
pubKey = '010001'
def encrypted_request(text):
text = json.dumps(text)
secKey = createSecretKey(16)
encText = aesEncrypt(aesEncrypt(text, nonce), secKey)
encSecKey = rsaEncrypt(secKey, pubKey, modulus)
data = {'params': encText, 'encSecKey': encSecKey}
return data
def aesEncrypt(text, secKey):
pad = 16 - len(text) % 16
text = text + chr(pad) * pad
encryptor = AES.new(secKey, 2, '0102030405060708')
ciphertext = encryptor.encrypt(text)
ciphertext = base64.b64encode(ciphertext).decode('u8')
return ciphertext
def rsaEncrypt(text, pubKey, modulus):
text = text[::-1]
rs = pow(int(binascii.hexlify(text), 16), int(pubKey, 16)) % int(modulus, 16)
return format(rs, 'x').zfill(256)
def createSecretKey(size):
return binascii.hexlify(os.urandom(size))[:16]
</code></pre>
<p>Source: <a href="https://github.com/darknessomi/musicbox/blob/master/NEMbox/api.py" rel="nofollow">https://github.com/darknessomi/musicbox/blob/master/NEMbox/api.py</a></p>
<p><strong>My current state in c#:</strong></p>
<pre><code>private byte[] hex2Binary(string hex) {
byte[] binaryVal = new byte[hex.Length];
for (int i = 0; i < hex.Length; i++) {
string byteString = hex.Substring(i, 1);
byte b = Convert.ToByte(byteString, 16);
binaryVal[i] = b;
}
return binaryVal;
}
private string aesEncryptBase64(String plainText, string key) {
return aesEncryptBase64(plainText, hex2Binary(key));
}
private string aesEncryptBase64(String plainText, byte[] key) {
//pad = 16 - len(text) % 16
//text = text + chr(pad) * pad
int pad = 16 - plainText.Length % 16;
for (int i=0; i<pad; i++) {
plainText = plainText + ((char)pad);
}
byte[] plainBytes = null;
RijndaelManaged aes = new RijndaelManaged();
//aes.KeySize = 16;
aes.Mode = CipherMode.CBC;
aes.Key = key;
aes.IV = hex2Binary(client.neteaseFix.encryptInfo.iv);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(plainBytes, 0, plainBytes.Length);
cs.Close();
byte[] encryptedBytes = ms.ToArray();
return Convert.ToBase64String(encryptedBytes); //decode("u8")
}
</code></pre>
| 0 |
2016-09-21T17:11:01Z
| 39,640,476 |
<p>Here are a couple of things I see right off the bat, but the question is a bit too open-ended:</p>
<ul>
<li>In <code>aesEncryptBase64</code> you are manually applying padding. The AES implementation in .NET does that for you. If you prefer to do it yourself you need to set <code>aes.Padding = PaddingMode.None</code></li>
<li>In <code>aesEncryptBase64</code> you create a <code>RijndaelManaged</code> object. Don't do that. You want AES, just use <code>AES.Create()</code>, which returns an AES object (not a Rijndael object).
<ul>
<li>.NET had support for the larger Rijndael algorithm before AES; and Rijndael with a block size of 128 bits is what got selected as AES, but Rijndael supports modes that AES does not, and you shouldn't really use them interchangeably (though many samples do).</li>
</ul></li>
<li>In <code>aesEncryptBase64</code> your <code>aes</code>, <code>ms</code>, and <code>cs</code> objects are all <code>IDisposable</code>, so you should have them in using statements.</li>
<li>The <code>rsaEncrypt</code> method in Python is doing raw RSA, which isn't supported in .NET (nor generally considered a good idea). Unless it's only called by routines which do the padding (and then it's just a pit of side-channel vulnerabilities).</li>
</ul>
<p>If your rsaEncrypt (in Python) is only being called from routines which do the signature or encryption (or PSS or OAEP) padding then your .NET equivalent would be (using your method naming casing, instead of the normal ones in .NET)</p>
<pre><code>private static rsaEncrypt(string text, string pubKey, string modulus)
{
RSAParameters rsaParams = new RSAParameters
{
Exponent = hex2Binary(pubKey),
Modulus = hex2Binary(modulus),
};
using (RSA rsa = RSA.Create())
{
rsa.ImportParameters(rsaParams);
return rsa.Encrypt(Encoding.ASCII.GetBytes(text), YOUNEEDTOPICKTHEPADDINGMODE);
}
}
</code></pre>
<p>It would be worlds better to improve all of the code around this, though, so that it doesn't have to do so much string re-parsing. </p>
| 0 |
2016-09-22T13:30:50Z
|
[
"c#",
"python",
"encryption",
"aes",
"rsa"
] |
How to make spawnSync and fs.readFile to execute one after other?
| 39,622,647 |
<p>I have a python script which returns a <code>JSON</code> file as output by taking a FILE as input.</p>
<p>I have 10 files, I am using <strong>spawnSync</strong> inside <strong>for loop</strong> and inside loop I have <strong>fs.readFile</strong> for reading JSON file which is coming from the python script. </p>
<p>But the problem is <strong>spawnSync</strong> is blocking <strong>fs.readFile</strong> until it executes python scripts with all 10 files. Since both <strong>spawnSync</strong> and <strong>fs.readFile</strong> are inside <strong>for loop</strong>, I want <strong>fs.readFile</strong> to read a JSON file as soon as first python script executes and outputs JSON file.</p>
<p>But it is not happening. <strong>spawnSync</strong> is blocking and it is continuing with next file to execute python script.<strong>fs.reafFile</strong> should prints data as soon as the file gets executes. please help, Here is my code snippet. </p>
<pre><code>var spawn = require('child_process').spawnSync;
var fs = require('fs');
var filename = ['first.txt','second.txt','third.txt',....]
for(var i=0;i<10;i++)
{
var myscript = spawn('python',['/pathToPython/myPython.py',filename[i]]);
fs.readFile('/pathToPython/' + filename[i] + '.json','utf8',function(err,data){
if(err){
console.log(err);
}else{
console.log(data);
}
});
}
</code></pre>
| 0 |
2016-09-21T17:11:02Z
| 39,623,150 |
<p>If you are rely to use third party module then I recommend to use <a href="http://caolan.github.io/async/docs.html#.eachSeries" rel="nofollow">async.eachSeries</a> the method of the <a href="https://github.com/caolan/async" rel="nofollow">async</a> module to resolve this issue</p>
<pre><code>var filename = ['first.txt','second.txt','third.txt',....]
async.eachSeries(filename, function(item, next) {
var myscript = spawn('python', ['/pathToPython/myPython.py', item]);
fs.readFile('/pathToPython/' + item + '.json', 'utf8', function(err, data) {
if (err) {
console.log(err);
} else {
console.log(data);
next();
}
});
})
</code></pre>
| 1 |
2016-09-21T17:39:21Z
|
[
"javascript",
"python",
"json",
"node.js",
"express"
] |
String variable just refuses to be turned into an integer
| 39,622,738 |
<p>I am writing a python GUI application which takes an entry from the user, converts it into an integer, and then uses that integer with the datetime module. However I have run into a problem which hopefully you can help with.</p>
<p>I am using Tkinter to construct a GUI with 3 elements, an entry box, a "GO!" button, and a "quit" button. Here is my simplified code:</p>
<pre><code>class MyFirstGUI:
def __init__(self, master):
numberdate = StringVar()
Label(root,text="Enter the Number of days you would like to search in").grid(row=0)
self.a = Entry(root,textvariable=numberdate )
self.a.grid(row=0, column=1)
self.close_button = Button(master, text="Close", command=master.quit)
self.close_button.grid(row=3, column=1)
self.macro_button = Button(master, text="GO!", command=self.macro)
self.macro_button.grid(row=4, column=1)
</code></pre>
<p>Now this seems simple enough, I know I have saved the variable as a StringVar but I will address that later. Now when the "GO!" button is pressed, it executes another portion of code, this is as follows:</p>
<pre><code>numberdate = self.a.get()
int(numberdate)
date_threshold = datetime.datetime.today() - datetime.timedelta(days=numberdate)
</code></pre>
<p>However whenever I run this code, python throws the following error at me:</p>
<pre><code>TypeError: unsupported type for timedelta days component: str
</code></pre>
<p>Now obviously this means the variable numberdate hasn't been converted into an integer, it is still a number, but for the life of me I can't work out why.</p>
<p>I've tried saving the variable as an IntVar in the first half of the code, but still no luck.</p>
<p>Is there an obvious mistake in my code that I am missing, or am I just going mad?</p>
| 1 |
2016-09-21T17:15:41Z
| 39,622,794 |
<p>The conversion happens, but nobody was listening. You have to rebind the name to the return value:</p>
<pre><code>numberdate = int(numberdate)
</code></pre>
| 5 |
2016-09-21T17:18:28Z
|
[
"python",
"python-3.x",
"tkinter"
] |
Flush to zero and/or significant digits in python floats
| 39,622,871 |
<p>I'm trying to conduct an ICA application using audio files (.wavs). When using scipy wavfile, I have noticed from using cprofile, that my load_wav function performs very poorly. It takes 30 minutes to process a 44100 stereo .wav file at a CPU speed of 4.5 Ghz. Bear in mind, the .wav file is only 10 seconds in duration. Here is my function for reference:</p>
<pre><code>def load_wav(filename,samplerate=44100):
# load file
rate, data = wavfile.read(filename)
# convert stereo to mono
if len(data.shape) > 1:
data = data[:,0]/2 + data[:,1]/2
# re-interpolate samplerate
ratio = float(samplerate) / float(rate)
data = resample(data, len(data) * ratio)
return samplerate, data.astype(np.int16)
</code></pre>
<p>it's primarily the re-interpolate section that takes forever. I researched what I could on it, and it seems that not all computers are adept at dealing with numerous floats. Some floats may be close to zero but not quite. In my audio example, this could be the result of pauses in a person's speech, or could happen at the beginning or end of a file, and the list goes on. </p>
<p>So to get down to it, can someone share something like this c++ workaround in Python? They call this issue "denormals" and they suggest flush to zero.</p>
<p><a href="http://blog.audio-tk.com/2016/09/20/audio-toolkit-handling-denormals/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+eifelle%2FCPPV+%28Matt%27s+blog%29" rel="nofollow">http://blog.audio-tk.com/2016/09/20/audio-toolkit-handling-denormals/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+eifelle%2FCPPV+%28Matt%27s+blog%29</a></p>
<p>And it would also be peace of mind to know whether or not zero is the only number to be wary of. Maybe, I should set significant digits for all numbers? Would that make a difference in audio applications? If so, how would that look in Python? Obviously we may want to avoid going overboard, like using integers only, which would probably result in a lot of sound degradation.</p>
<p>Anyway, I think you get the idea of my question, I want the computation speed to be within reason, but still be able to have a half decent numpy representation of the .wav.</p>
<p>Please help out if you can,</p>
<p>Thank you</p>
<p>
Imports are as follows:</p>
<pre><code>import numpy as np
from scipy.io import wavfile
from scipy.signal import resample
</code></pre>
<p>also if you want to view the jupyter notebook to see the ICA application in its entirety, you can do so here:
<a href="http://web.archive.org/web/20150314223948/http://shogun-toolbox.org/static/notebook/current/bss_audio.html" rel="nofollow">http://web.archive.org/web/20150314223948/http://shogun-toolbox.org/static/notebook/current/bss_audio.html</a></p>
<p>**the link uses Python 2.7, I'm using Python 3.5, so things may vary slightly.</p>
<p>--Edit</p>
<p>Well. sorry for the confusion. The answer to why the shape of X changed is due to the fact the example notebook took the dot product differently than the way I was used to. They used <code>S=(np.c_[s1,s2,s3]).T</code> then <code>np.dot(A,S)</code>. I usually use <code>S=np.c_[s1,s2,s3]</code> then <code>np.dot(S,A.T)</code>. So all I had to do was transform a few things to get the desired shape of X. Classic case of not looking before I leaped. I was wrong to have blamed <code>np.delete(data,-1)</code> for causing that shape mishap. It has proven to work for handling primes, guaranteeing data will be an even number. I will delete some of my unnecessary comments to restore clarity to my post.</p>
<p>The verdict is still out on flush to zero / significant digit thresholds in terms of audio processing code efficiency. I hope this particular aspect of my question is revisited sometime soon. Until then, I will be using <code>np.delete(data,-1)</code> as a quick and dirty solution when dealing with large/prime numbers.</p>
| 0 |
2016-09-21T17:22:35Z
| 39,625,702 |
<p>As AndyG already commented, <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.resample.html#scipy.signal.resample" rel="nofollow">the documentation for <code>scipy.signal.resample</code></a> warns you that</p>
<blockquote>
<p>... resample uses FFT transformations, which can be very slow if the number of input samples is large and prime, see <code>scipy.fftpack.fft</code>.</p>
</blockquote>
<p>441263 is both large and prime.</p>
<p>If you have a version of scipy >= 0.18.0 you could try <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.resample_poly.html#scipy.signal.resample_poly" rel="nofollow"><code>resample_poly</code></a> instead:</p>
<blockquote>
<p>This polyphase method will likely be faster than the Fourier method in scipy.signal.resample when the number of samples is large and prime, or when the number of samples is large and up and down share a large greatest common denominator.</p>
</blockquote>
<p>For example:</p>
<pre><code>import numpy
from scipy.signal import resample, resample_poly
x = np.random.randn(441263)
%timeit resample(x, x.shape[0] // 4)
# 1 loop, best of 3: 2min 18s per loop
%timeit resample_poly(x, 10, 40)
# 100 loops, best of 3: 9.05 ms per loop
</code></pre>
| 1 |
2016-09-21T20:09:16Z
|
[
"python",
"c++",
"audio",
"scipy",
"signal-processing"
] |
Simple if/elif statement + raw_input why dosen't work
| 39,622,882 |
<p>I have a problem with simple if statement. I want user to press a key '1','2' or '3' to choose any option then program will do something. For a test it just prints text for example "Wybrano 2" after pressing '2'.</p>
<p>Here is my code:</p>
<pre><code>if raw_input() == '1':
print "Wybrano 1"
elif raw_input() == '2':
print "Wybrano 2"
elif raw_input() == '3':
print "Wybrano 3"
</code></pre>
<p>So if I press 1 it correctly prints "Wybrano 1" but when I press 2 or 3 the program does nothing. </p>
| 0 |
2016-09-21T17:23:02Z
| 39,623,647 |
<p><strong>When i press 2 or 3 program does not nothing</strong> is wrong. It is waiting for you for next input.</p>
<p>Let me tell you how this is working.</p>
<ul>
<li><code>raw_input</code> is python function for accepting user input.(I know you are aware of this :) )</li>
<li>When you execute code, first it will go to "<code>if</code>" statement. <code>'if'</code> statement has <code>'raw_input'</code> function after it. So, it waits for your input.</li>
<li>When you enter '1', <code>"1" = "1"</code>, it gives you expected output and come out of code.</li>
<li>However, next time when you again execute code, again <code>'raw_input'</code> after <code>'if'</code> is executed waiting for your input. When you input '2' and since <code>'1' == '2'</code> is false, code goes to next <code>'elif'</code> statement. After <code>'elif'</code> there is <code>'raw_input'</code> function which is waiting for input again. </li>
<li><strong>Therefore, you got feel, program does nothing.</strong></li>
<li>Same happens when you enter '3'.</li>
</ul>
<p><strong>Example of above explained behavior</strong></p>
<pre><code>if raw_input("Enter number : ") == '1':
print "Wybrano 1"
elif raw_input("Enter number : ") == '2':
print "Wybrano 2"
elif raw_input("Enter number : ") == '3':
print "Wybrano 3"
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>C:\Users\dinesh_pundkar\Desktop>python c.py
Enter number : 1
Wybrano 1
C:\Users\dinesh_pundkar\Desktop>python c.py
Enter number : 2
Enter number : 2
Wybrano 2
C:\Users\dinesh_pundkar\Desktop>python c.py
Enter number : 3
Enter number : 3
Enter number : 3
Wybrano 3
</code></pre>
<p><strong>How to make your code working ?</strong></p>
<p>Answer is simple. As explained by <strong>@MooingRawr</strong> in first comment, just save user input in some variable and then check.</p>
<pre><code>x = raw_input("Enter number : ")
if x == '1':
print "Wybrano 1"
elif x == '2':
print "Wybrano 2"
elif x == '3':
print "Wybrano 3"
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>C:\Users\dinesh_pundkar\Desktop>python c.py
Enter number : 1
Wybrano 1
C:\Users\dinesh_pundkar\Desktop>python c.py
Enter number : 2
Wybrano 2
C:\Users\dinesh_pundkar\Desktop>python c.py
Enter number : 3
Wybrano 3
C:\Users\dinesh_pundkar\Desktop>
</code></pre>
| 3 |
2016-09-21T18:07:42Z
|
[
"python",
"python-2.7"
] |
Pandas groupby over list
| 39,622,884 |
<p>I have a pandas data frame in the following format:</p>
<pre><code>Arrival Departure Park Station Count
8 10 5 [1,2] 1
5 12 6 [3,4] 1
8 10 5 [1,2] 1
</code></pre>
<p>I want to groupby this data frame by arrival, departure, park and station but since station is a list, I am getting an error. The output should look like:</p>
<pre><code> Arrival Departure Park Station Count
8 10 5 [1,2] 2
5 12 6 [3,4] 1
</code></pre>
<p>Could you please let me know if there is any way to solve this issue? </p>
| 1 |
2016-09-21T17:23:14Z
| 39,623,134 |
<p>The problem is that a <a href="http://stackoverflow.com/questions/19371358/python-typeerror-unhashable-type-list">Python <code>list</code> is a mutable type, and hence unhashable</a>. In the place you'd put in the <code>groupby</code> criterion <code>df.Station</code>, put instead <code>df.Station.apply(tuple)</code>. This will transform the lists into tuples, which are hashable (and immutable).</p>
<p>For example:</p>
<pre><code>In [66]: df = pd.DataFrame({'Arrival': [8, 5, 4], 'Station': [[1, 2], [3, 4], [1, 2]]})
In [67]: df.groupby([df.Arrival, df.Station.apply(tuple)]).Arrival.sum()
Out[67]:
Arrival Station
4 (1, 2) 4
5 (3, 4) 5
8 (1, 2) 8
Name: Arrival, dtype: int64
</code></pre>
<p>Conversely,</p>
<pre><code>df.groupby([df.Arrival, df.Station]).Arrival.sum()
</code></pre>
<p>won't work.</p>
| 3 |
2016-09-21T17:38:28Z
|
[
"python",
"list",
"pandas",
"dataframe"
] |
Pandas groupby over list
| 39,622,884 |
<p>I have a pandas data frame in the following format:</p>
<pre><code>Arrival Departure Park Station Count
8 10 5 [1,2] 1
5 12 6 [3,4] 1
8 10 5 [1,2] 1
</code></pre>
<p>I want to groupby this data frame by arrival, departure, park and station but since station is a list, I am getting an error. The output should look like:</p>
<pre><code> Arrival Departure Park Station Count
8 10 5 [1,2] 2
5 12 6 [3,4] 1
</code></pre>
<p>Could you please let me know if there is any way to solve this issue? </p>
| 1 |
2016-09-21T17:23:14Z
| 39,623,209 |
<pre><code>import pandas as pd
df = pd.DataFrame({'arrival':[8,5,8], 'departure':[10,12,10], \
'park':[5,6,5], 'station':[[1,2], [3,4], [1,2]]})
df['arrival_station'] = df.station.apply(lambda x: x[0])
df['departure_station'] = df.station.apply(lambda x: x[1])
print df
arrival departure park station arrival_station departure_station
0 8 10 5 [1, 2] 1 2
1 5 12 6 [3, 4] 3 4
2 8 10 5 [1, 2] 1 2
</code></pre>
<p>Now your station data is free and you can groupby as normal. </p>
| 1 |
2016-09-21T17:42:11Z
|
[
"python",
"list",
"pandas",
"dataframe"
] |
Django - problems with URLS mapping and dispatcher
| 39,622,971 |
<p>I'm learning Django and I would like to build an application with the calendar and tasks, where every task has a separate link via <code>get_absolute_url</code>. I've created a list of activities and url link to each of them, but when I pick one of them there is no reaction, not even an error message. </p>
<p>Please find my code below.</p>
<pre><code>from django.db import models
from django.utils import timezone
from django.core.urlresolvers import reverse
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,self).get_queryset().order_by('hour')
class Activity(models.Model):
STATUS_CHOICES = (
('30 min', '30 min'),
('1:00 h', '1:00 h'),
('1:30 h', '1:30 h'),
('2:00 h', '2:00 h'),
('2:30 h', '2:30 h'),
('3:00 h', '3:00 h'),
('3:30 h', '3:30 h'),
('4:00 h', '4:00 h'),
('4:30 h', '4:30 h'),
('5:00 h', '5:00 h'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='hour')
body = models.TextField()
hour = models.DateTimeField(default=timezone.now())
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
objects = models.Manager()
duration = models.CharField(max_length=10, choices=STATUS_CHOICES, default='30 min')
published = PublishedManager()
class Meta:
ordering = ('-hour',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('core_tm:activity_detail',
args=[self.slug])
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^', views.activity_list, name='activity_list'),
url(r'^(?P<activity>[-\w]+)/$',
views.activity_detail, name='activity_detail')
from django.shortcuts import render, get_object_or_404
from .models import Activity
def activity_list(request):
activities = Activity.published.all()
return render(request, 'core_tm/activity/list.html', {'activities' : activities})
def activity_detail(request, activity):
activity = get_object_or_404(Activity, slug=activity)
return render(request, 'core_tm/activity/detail.html', {'activity' : activity})
</code></pre>
<p>List template:</p>
<pre><code>{% extends "core_tm/base.html" %}
{% block title %}<h1>Lista aktywnoÅci</h1>{% endblock %}
{% block content %}
{% for activnes in activities %}
<h2>
<a href="{{ activnes.get_absolute_url }}">
{{ activnes.title }}
</a>
</h2>
<p class="date">
Data rozpoczÄcia : {{ activnes.hour }}
Czas trwania : {{ activnes.duration }}
</p>
{{ activnes.body|truncatewords:30|linebreaks }}
{% endfor %}
{% endblock %}
</code></pre>
<p>Detail template:</p>
<pre><code>{% extends "core_tm/base.html" %}
{% block title %}{{ activity.title }}{% endblock %}
{%block content %}
<h1>{{ activity.title }}</h1>
<p class="date">
Data rozpoczÄcia : {{ activity.hour }}
Czas trwania : {{ activity.duration }}
</p>
{{ activity.body|linebreaks }}
{% endblock %}
</code></pre>
| 1 |
2016-09-21T17:28:01Z
| 39,624,465 |
<p>You need to terminate your activity_list URL:</p>
<pre><code>url(r'^$', views.activity_list, name='activity_list'),
</code></pre>
<p>Otherwise this will simply match all paths, including those that are supposed to point to your activities.</p>
| 0 |
2016-09-21T18:57:28Z
|
[
"python",
"django",
"url"
] |
How to plot (or update) a matplot figure and continue python code immediately (don't wait for the plot)?
| 39,622,994 |
<p>I am trying to write python code that continuously gets data from machine and plots these data in a figure window. I am using matplotlib with interactive plotting enabled / ion().</p>
<p>There is quite a bit of data, so plotting may take a while. Since the python code does not continue until the plot is updated, data acquisition is stopped while the plot updated.</p>
<p>I'd like to avoid the data gaps resulting from the updating of the plots. Is there a (simple and reliable) way to update the figure/plot without blocking the execution of the code until the plot is updated on screen?</p>
<p>EDIT 23.9.2015:</p>
<p>I tried threading as suggested below. I put this in a script:</p>
<pre><code>import threading
import matplotlib.pyplot as plt
def plotter():
print 'Starting plot...'
plt.plot([1,2,3,4])
plt.show()
print '...plot done.'
return
t = threading.Thread(target=plotter)
t.start()
</code></pre>
<p>Executing this script results in a crash (Mac OS X with Python 2.7 from MacPorts; see below). The script works smoothly and as expected if I comment out plt.plot(...) and plt.show(). Any help or suggestions what's wrong?</p>
<pre><code>$ python plot_in_own_thread.py
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')
Starting plot...
2016-09-23 08:43:19.433 Python[89176:39798237] *** Assertion failure in +[NSUndoManager _endTopLevelGroupings], /Library/Caches/com.apple.xbs/Sources/Foundation/Foundation-1259/Misc.subproj/NSUndoManager.m:359
2016-09-23 08:43:19.433 Python[89176:39798237] +[NSUndoManager(NSInternal) _endTopLevelGroupings] is only safe to invoke on the main thread.
2016-09-23 08:43:19.435 Python[89176:39798237] (
0 CoreFoundation 0x00007fff8cbb14f2 __exceptionPreprocess + 178
1 libobjc.A.dylib 0x00007fff9f7ab73c objc_exception_throw + 48
2 CoreFoundation 0x00007fff8cbb61ca +[NSException raise:format:arguments:] + 106
3 Foundation 0x00007fff9ba2d856 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 198
4 Foundation 0x00007fff9b9b2af1 +[NSUndoManager(NSPrivate) _endTopLevelGroupings] + 170
5 AppKit 0x00007fff98061e22 -[NSApplication run] + 844
6 _macosx.so 0x000000010d3494a2 show + 210
7 Python 0x000000010aff2539 PyEval_EvalFrameEx + 27929
8 Python 0x000000010afeb52a PyEval_EvalCodeEx + 1690
9 Python 0x000000010aff6e36 fast_function + 118
10 Python 0x000000010aff23b8 PyEval_EvalFrameEx + 27544
11 Python 0x000000010afeb52a PyEval_EvalCodeEx + 1690
12 Python 0x000000010af771cc function_call + 364
13 Python 0x000000010af514c3 PyObject_Call + 99
14 Python 0x000000010af5e526 instancemethod_call + 182
15 Python 0x000000010af514c3 PyObject_Call + 99
16 Python 0x000000010afac5fb slot_tp_call + 171
17 Python 0x000000010af514c3 PyObject_Call + 99
18 Python 0x000000010aff2c8c PyEval_EvalFrameEx + 29804
19 Python 0x000000010afeb52a PyEval_EvalCodeEx + 1690
20 Python 0x000000010aff6e36 fast_function + 118
21 Python 0x000000010aff23b8 PyEval_EvalFrameEx + 27544
22 Python 0x000000010afeb52a PyEval_EvalCodeEx + 1690
23 Python 0x000000010af771cc function_call + 364
24 Python 0x000000010af514c3 PyObject_Call + 99
25 Python 0x000000010aff2c8c PyEval_EvalFrameEx + 29804
26 Python 0x000000010aff6f16 fast_function + 342
27 Python 0x000000010aff23b8 PyEval_EvalFrameEx + 27544
28 Python 0x000000010aff6f16 fast_function + 342
29 Python 0x000000010aff23b8 PyEval_EvalFrameEx + 27544
30 Python 0x000000010afeb52a PyEval_EvalCodeEx + 1690
31 Python 0x000000010af771cc function_call + 364
32 Python 0x000000010af514c3 PyObject_Call + 99
33 Python 0x000000010af5e526 instancemethod_call + 182
34 Python 0x000000010af514c3 PyObject_Call + 99
35 Python 0x000000010aff68b5 PyEval_CallObjectWithKeywords + 165
36 Python 0x000000010b030cb6 t_bootstrap + 70
37 libsystem_pthread.dylib 0x00007fff9b92b99d _pthread_body + 131
38 libsystem_pthread.dylib 0x00007fff9b92b91a _pthread_body + 0
39 libsystem_pthread.dylib 0x00007fff9b929351 thread_start + 13
)
2016-09-23 08:43:19.436 Python[89176:39798237] *** Assertion failure in +[NSUndoManager _endTopLevelGroupings], /Library/Caches/com.apple.xbs/Sources/Foundation/Foundation-1259/Misc.subproj/NSUndoManager.m:359
2016-09-23 08:43:19.438 Python[89176:39798237] An uncaught exception was raised
2016-09-23 08:43:19.438 Python[89176:39798237] +[NSUndoManager(NSInternal) _endTopLevelGroupings] is only safe to invoke on the main thread.
2016-09-23 08:43:19.438 Python[89176:39798237] (
0 CoreFoundation 0x00007fff8cbb14f2 __exceptionPreprocess + 178
1 libobjc.A.dylib 0x00007fff9f7ab73c objc_exception_throw + 48
2 CoreFoundation 0x00007fff8cbb61ca +[NSException raise:format:arguments:] + 106
3 Foundation 0x00007fff9ba2d856 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 198
4 Foundation 0x00007fff9b9b2af1 +[NSUndoManager(NSPrivate) _endTopLevelGroupings] + 170
5 AppKit 0x00007fff98061ebe -[NSApplication run] + 1000
6 _macosx.so 0x000000010d3494a2 show + 210
7 Python 0x000000010aff2539 PyEval_EvalFrameEx + 27929
8 Python 0x000000010afeb52a PyEval_EvalCodeEx + 1690
9 Python 0x000000010aff6e36 fast_function + 118
10 Python 0x000000010aff23b8 PyEval_EvalFrameEx + 27544
11 Python 0x000000010afeb52a PyEval_EvalCodeEx + 1690
12 Python 0x000000010af771cc function_call + 364
13 Python 0x000000010af514c3 PyObject_Call + 99
14 Python 0x000000010af5e526 instancemethod_call + 182
15 Python 0x000000010af514c3 PyObject_Call + 99
16 Python 0x000000010afac5fb slot_tp_call + 171
17 Python 0x000000010af514c3 PyObject_Call + 99
18 Python 0x000000010aff2c8c PyEval_EvalFrameEx + 29804
19 Python 0x000000010afeb52a PyEval_EvalCodeEx + 1690
20 Python 0x000000010aff6e36 fast_function + 118
21 Python 0x000000010aff23b8 PyEval_EvalFrameEx + 27544
22 Python 0x000000010afeb52a PyEval_EvalCodeEx + 1690
23 Python 0x000000010af771cc function_call + 364
24 Python 0x000000010af514c3 PyObject_Call + 99
25 Python 0x000000010aff2c8c PyEval_EvalFrameEx + 29804
26 Python 0x000000010aff6f16 fast_function + 342
27 Python 0x000000010aff23b8 PyEval_EvalFrameEx + 27544
28 Python 0x000000010aff6f16 fast_function + 342
29 Python 0x000000010aff23b8 PyEval_EvalFrameEx + 27544
30 Python 0x000000010afeb52a PyEval_EvalCodeEx + 1690
31 Python 0x000000010af771cc function_call + 364
32 Python 0x000000010af514c3 PyObject_Call + 99
33 Python 0x000000010af5e526 instancemethod_call + 182
34 Python 0x000000010af514c3 PyObject_Call + 99
35 Python 0x000000010aff68b5 PyEval_CallObjectWithKeywords + 165
36 Python 0x000000010b030cb6 t_bootstrap + 70
37 libsystem_pthread.dylib 0x00007fff9b92b99d _pthread_body + 131
38 libsystem_pthread.dylib 0x00007fff9b92b91a _pthread_body + 0
39 libsystem_pthread.dylib 0x00007fff9b929351 thread_start + 13
)
2016-09-23 08:43:19.438 Python[89176:39798237] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+[NSUndoManager(NSInternal) _endTopLevelGroupings] is only safe to invoke on the main thread.'
*** First throw call stack:
(
0 CoreFoundation 0x00007fff8cbb14f2 __exceptionPreprocess + 178
1 libobjc.A.dylib 0x00007fff9f7ab73c objc_exception_throw + 48
2 CoreFoundation 0x00007fff8cbb61ca +[NSException raise:format:arguments:] + 106
3 Foundation 0x00007fff9ba2d856 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 198
4 Foundation 0x00007fff9b9b2af1 +[NSUndoManager(NSPrivate) _endTopLevelGroupings] + 170
5 AppKit 0x00007fff98061ebe -[NSApplication run] + 1000
6 _macosx.so 0x000000010d3494a2 show + 210
7 Python 0x000000010aff2539 PyEval_EvalFrameEx + 27929
8 Python 0x000000010afeb52a PyEval_EvalCodeEx + 1690
9 Python 0x000000010aff6e36 fast_function + 118
10 Python 0x000000010aff23b8 PyEval_EvalFrameEx + 27544
11 Python 0x000000010afeb52a PyEval_EvalCodeEx + 1690
12 Python 0x000000010af771cc function_call + 364
13 Python 0x000000010af514c3 PyObject_Call + 99
14 Python 0x000000010af5e526 instancemethod_call + 182
15 Python 0x000000010af514c3 PyObject_Call + 99
16 Python 0x000000010afac5fb slot_tp_call + 171
17 Python 0x000000010af514c3 PyObject_Call + 99
18 Python 0x000000010aff2c8c PyEval_EvalFrameEx + 29804
19 Python 0x000000010afeb52a PyEval_EvalCodeEx + 1690
20 Python 0x000000010aff6e36 fast_function + 118
21 Python 0x000000010aff23b8 PyEval_EvalFrameEx + 27544
22 Python 0x000000010afeb52a PyEval_EvalCodeEx + 1690
23 Python 0x000000010af771cc function_call + 364
24 Python 0x000000010af514c3 PyObject_Call + 99
25 Python 0x000000010aff2c8c PyEval_EvalFrameEx + 29804
26 Python 0x000000010aff6f16 fast_function + 342
27 Python 0x000000010aff23b8 PyEval_EvalFrameEx + 27544
28 Python 0x000000010aff6f16 fast_function + 342
29 Python 0x000000010aff23b8 PyEval_EvalFrameEx + 27544
30 Python 0x000000010afeb52a PyEval_EvalCodeEx + 1690
31 Python 0x000000010af771cc function_call + 364
32 Python 0x000000010af514c3 PyObject_Call + 99
33 Python 0x000000010af5e526 instancemethod_call + 182
34 Python 0x000000010af514c3 PyObject_Call + 99
35 Python 0x000000010aff68b5 PyEval_CallObjectWithKeywords + 165
36 Python 0x000000010b030cb6 t_bootstrap + 70
37 libsystem_pthread.dylib 0x00007fff9b92b99d _pthread_body + 131
38 libsystem_pthread.dylib 0x00007fff9b92b91a _pthread_body + 0
39 libsystem_pthread.dylib 0x00007fff9b929351 thread_start + 13
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Abort trap: 6
</code></pre>
| 0 |
2016-09-21T17:29:54Z
| 39,623,353 |
<p>You can use threading which will make it to run independently, see <a href="https://docs.python.org/3/library/threading.html" rel="nofollow">https://docs.python.org/3/library/threading.html</a> for more details</p>
| 0 |
2016-09-21T17:50:06Z
|
[
"python",
"asynchronous",
"matplotlib",
"background",
"blocking"
] |
How can I read 10-bit Raw image? which contain RGB-IR data
| 39,623,001 |
<p>I want to know how extract the rgb image from my 10-bit raw (it has rgb-ir imagedata) data?</p>
<p>How can I read in Python or MATLAB?</p>
<p>The camera resolution at the time of capture were 1280x720:
indoor photo <a href="https://drive.google.com/file/d/0B0givAGTBMIweWMzbWFzd0xSQ2M/view?usp=sharing" rel="nofollow">Image for download</a>
outdoor photo <a href="https://drive.google.com/drive/folders/0B0givAGTBMIwSkVJT1B5bHJoYkk?usp=sharing" rel="nofollow">Image 2 for download</a></p>
<p>camera Model: e-CAM40_CUMI4682_MOD </p>
<p>Thanks a lot </p>
| 0 |
2016-09-21T17:30:17Z
| 39,627,104 |
<p>I used the following image processing stages: </p>
<ul>
<li>Bayer mosaic color channel separation.</li>
<li>Linear stretching each color channel.</li>
<li>Simple white balance.</li>
<li>Replace IR color channel with green (convert image to standard Bayer format).</li>
<li>Restore Bayer mosaic.</li>
<li>Simple gamma correction.</li>
<li>Demosaic</li>
</ul>
<p>Instead of processing the IR color channel, I replaced it with green color channel.</p>
<p>According to the RGB image you added, I found the <a href="https://en.wikipedia.org/wiki/Color_filter_array" rel="nofollow">CFA</a> order.<br>
The CFA (color filter array) order is:</p>
<pre><code>B | G
-- --
IR| R
</code></pre>
<p>The following Matlab code process the image to RGB: </p>
<pre class="lang-matlab prettyprint-override"><code>srcN = 1280;
srcM = 720;
f = fopen('image_raw.raw', 'r');
%Read as transposed matrix dimensions, and transpose the matrix.
%The reason for that, is that Matlab memory oreder is column major, and
%raw image is stored in row major (like C arrays).
I = fread(f, [srcN, srcM], 'uint16');
fclose(f);
I = I';
%Convert from range [0, 1023] range [0, 1] (working in double image format).
I = I/(2^10-1);
%Bayer mosaic color channel separation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Assume input format is GBRG Bayer mosaic format.
%Separate to color components.
B = I(1:2:end, 1:2:end);
G = I(1:2:end, 2:2:end);
IR = I(2:2:end, 1:2:end);
R = I(2:2:end, 2:2:end);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Linear stretching each color channel.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Linear streatch blue color channel.
B = imadjust(B, stretchlim(B, [0.02 0.98]),[]);
%Linear streatch green channel.
G = imadjust(G, stretchlim(G, [0.02 0.98]),[]);
%Linear streatch red color channel.
R = imadjust(R, stretchlim(R, [0.02 0.98]),[]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Simple white balance
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Median or R, G and B.
rgb_med = [median(R(:)), median(G(:)), median(B(:))];
rgb_scale = max(rgb_med)./rgb_med;
%Scale each color channel, to have the same median.
R = R*rgb_scale(1);
G = G*rgb_scale(2);
B = B*rgb_scale(3);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Restore Bayer mosaic.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Insert streached color channnels back into I.
I(1:2:end, 1:2:end) = B;
I(1:2:end, 2:2:end) = G;
%I(2:2:end, 1:2:end) = G; %Replace IR with Green.
I(2:2:end, 2:2:end) = R;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Replace IR with green - resize green to full size of image first.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
T = imresize(G, [srcM, srcN]); %T - temporary green, size 1280x720
I(2:2:end, 1:2:end) = T(2:2:end, 1:2:end); %Replace IR with Green.
I = max(min(I, 1), 0); %Limit I to range [0, 1].
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Simple gamma correction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
gamma = 0.45;
I = I.^gamma;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Demosaic
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Convert to uint8 (range [0, 255]).
I = uint8(round(I*255));
RGB = demosaic(I, 'bggr');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
imshow(RGB);
</code></pre>
<p>Result:</p>
<p><a href="http://i.stack.imgur.com/u3n4A.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/u3n4A.jpg" alt="enter image description here"></a></p>
<p>Now the colors are normal... </p>
<hr>
<p><strong>Outdoor image processing :</strong></p>
<p>Applying "indoor" processing on the outdoor image, gets the following result: </p>
<p><a href="http://i.stack.imgur.com/wEqwt.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/wEqwt.jpg" alt="enter image description here"></a></p>
<p>White trees is a sign for Near-IR spectrum penetration to R, G and B pixels (not only to IR pixels).<br>
The chlorophyll of the vegetation has high reflection in the Near-IR spectrum. See: <a href="http://missionscience.nasa.gov/ems/08_nearinfraredwaves.html%E2%80%8C%E2%80%8B" rel="nofollow">http://missionscience.nasa.gov/ems/08_nearinfraredwaves.htmlââ</a>, and search it on Google.<br>
Subtracting IR from Red, Green and Blue color channels is required. </p>
<hr>
<p>I used the following image processing stages: </p>
<ul>
<li>Bayer mosaic color channel separation.</li>
<li><strong>Subtract IR "surplus" from Red, Green and Blue color channels.</strong></li>
<li>Linear stretching each color channel.</li>
<li>Simple white balance.</li>
<li>Restore Bayer mosaic.</li>
<li>Simple gamma correction.</li>
<li>Demosaic.</li>
<li>Resize RGB image to lower resolution.</li>
</ul>
<p>The following Matlab code process the outdoor image to RGB: </p>
<pre class="lang-matlab prettyprint-override"><code>srcN = 1280;
srcM = 720;
f = fopen('ir_6.raw', 'r');
%Read as transposed matrix dimensions, and transpose the matrix.
%The reason for that, is that Matlab memory oreder is column major, and
%raw image is stored in row major (like C arrays).
I = fread(f, [srcN, srcM], 'uint16');
fclose(f);
I = I';
%Convert from range [0, 1023] range [0, 1] (working in double image format).
I = I/(2^10-1);
%Bayer mosaic color channel separation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Assume input format is GBRG Bayer mosaic format.
%Separate to color components.
B = I(1:2:end, 1:2:end);
G = I(1:2:end, 2:2:end);
IR = I(2:2:end, 1:2:end);
R = I(2:2:end, 2:2:end);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Subtract IR "surplus" from R, G and B.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%The coefficients were tuned by trial and error...
ir_r = 1.3; % 130% of IR radiation is absorbed by red pixels???
ir_g = 0.35; % 35% of IR radiation is absorbed by green pixels.
ir_b = 0.3; % 30% of IR radiation is absorbed by blue pixels.
IR = imresize(IR, size(I)); %Resize IR to the size of I.
IR = max(min(IR, 1), 0); %Limit IR to range [0, 1] (because imresize values slightly outside the range of input).
R = R - IR(2:2:end, 2:2:end)*ir_r; %Subtract IR for R (IR scale coefficient is ir_r).
G = G - IR(1:2:end, 2:2:end)*ir_g; %Subtract IR for G (IR scale coefficient is ir_g).
B = B - IR(1:2:end, 1:2:end)*ir_b; %Subtract IR for B (IR scale coefficient is ir_b).
R = max(min(R, 1), 0); %Limit IR to range [0, 1]
G = max(min(G, 1), 0);
B = max(min(B, 1), 0);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Linear stretching each color channel.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Linear streatch blue color channel.
B = imadjust(B, stretchlim(B, [0.02 0.98]),[]);
%Linear streatch green channel.
G = imadjust(G, stretchlim(G, [0.02 0.98]),[]);
%Linear streatch red color channel.
R = imadjust(R, stretchlim(R, [0.02 0.98]),[]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Simple white balance
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Median or R, G and B.
rgb_med = [median(R(:)), median(G(:)), median(B(:))];
rgb_scale = max(rgb_med)./rgb_med;
%Scale each color channel, to have the same median.
R = R*rgb_scale(1);
G = G*rgb_scale(2);
B = B*rgb_scale(3);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Restore Bayer mosaic.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Insert streached color channnels back into I.
I(1:2:end, 1:2:end) = B;
I(1:2:end, 2:2:end) = G;
I(2:2:end, 2:2:end) = R;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Replace IR with green - resize green to full size of image first.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
T = imresize(G, [srcM, srcN]); %T - temporary green, size 1280x720
I(2:2:end, 1:2:end) = T(2:2:end, 1:2:end); %Replace IR with Green.
I = max(min(I, 1), 0); %Limit I to range [0, 1].
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Simple gamma correction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
gamma = 0.45;
I = I.^gamma;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Demosaic
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Convert to uint8 (range [0, 255]).
I = uint8(round(I*255));
RGB = demosaic(I, 'bggr');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
RGB = imresize(RGB, size(I)/2); %Shrink size of RGB image for reducing demosaic artifacts.
imshow(RGB);
</code></pre>
<p>Result is not so good, but it demonstrates the concept that IR channel can be subtracted from the Red Green and Blue channels.<br>
There is still work to be done...<br>
Result image: </p>
<p><a href="http://i.stack.imgur.com/G0FzH.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/G0FzH.jpg" alt="enter image description here"></a></p>
<p>Reason for the "false color" green patches:<br>
Saturated pixels in the Red color channel (saturated in the raw input), are not handled properly.<br>
Problem can by solved by reducing exposure (taking the shot with lower exposure time). </p>
| 5 |
2016-09-21T21:48:38Z
|
[
"python",
"matlab",
"numpy",
"image-processing"
] |
Skipping falsifying examples in Hypothesis
| 39,623,023 |
<p><strong>The Story:</strong></p>
<p>I'm currently in the process of unit-testing a function using <a href="http://hypothesis.readthedocs.io/en/latest/" rel="nofollow"><code>hypothesis</code></a> and a <a href="http://stackoverflow.com/q/39561310/771848">custom generation strategy</a> trying to find a specific input to "break" my current solution. Here is how my test looks like:</p>
<pre><code>from solution import answer
# skipping mystrategy definition - not relevant
@given(mystrategy)
def test(l):
assert answer(l) in {0, 1, 2}
</code></pre>
<p>Basically, I'm looking for possible inputs when <code>answer()</code> function does not return 0 or 1 or 2.</p>
<p>Here is how my <em>current workflow</em> looks like:</p>
<ul>
<li>run the test</li>
<li><p><code>hypothesis</code> finds an input that produces an <code>AssertionError</code>:</p>
<pre><code>$ pytest test.py
=========================================== test session starts ============================================
...
------------------------------------------------ Hypothesis ------------------------------------------------
Falsifying example: test(l=[[0], [1]])
</code></pre></li>
<li><p>debug the function with this particular input trying to understand if this input/output is a legitimate one and the function worked correctly</p></li>
</ul>
<p><strong>The Question:</strong></p>
<p>How can I skip this falsifying generated example (<code>[[0], [1]]</code> in this case) and ask <code>hypothesis</code> to generate me a different one?</p>
<hr>
<p>The Question can also be interpreted: Can I ask <code>hypothesis</code> to not terminate if a falsifying example found and generate more falsifying examples instead?</p>
| 1 |
2016-09-21T17:31:51Z
| 39,623,466 |
<p>There's at present no way to get Hypothesis to keep trying after it finds a failure (it might happen at some point, but it's not really clear what the right behaviour for this should be and it hasn't been a priority), but you can get it to ignore specific classes of failure using the <a href="https://hypothesis.readthedocs.io/en/latest/details.html#making-assumptions" rel="nofollow">assume</a> functionality.</p>
<p>e.g. you could skip this example with:</p>
<pre><code>@given(mystrategy)
def test(l):
assume(l != [[0], [1]])
assert answer(l) in {0, 1, 2}
</code></pre>
<p>Hypothesis will skip any examples where you call assume with a False argument and not count them towards your budget of examples it runs.</p>
<p>You'll probably find that this just results in trivial variations on the example, but you can pass more complex expressions to assume to ignore classes of examples.</p>
<p>What's your actual use case here? The normal intended usage pattern her would be to fix the bug that causes Hypothesis to fail and let it find new bugs that way. I know this isn't always practical, but I'm interested in why.</p>
| 1 |
2016-09-21T17:56:50Z
|
[
"python",
"unit-testing",
"testing",
"property-based-testing",
"python-hypothesis"
] |
Error Embedding Pyqtgraph into PyQt4 GraphicsView
| 39,623,076 |
<p>I am attempting to embed a pyqtgraph into a PyQt4 GraphicsView widget. I am getting an error with the following code:. What am I doing wrong?</p>
<pre><code>#imports
from PyQt4 import QtGui
from PyQt4 import QtCore
import ui_test #Gui File
import sys
import pyqtgraph as pg
class Gui(QtGui.QMainWindow, ui_test.Ui_MainWindow, pg):
vb = pg.ViewBox()
def __init__(self):
super(self.__class__, self).__init__()
self.setupUi(self) # This is defined in ui_pumptest.py file automatically
self.graphicsView.setCentralItem(self.vb) #set central item to be graph
def main():
app = QtGui.QApplication(sys.argv) # A new instance of QApplication
form = Gui() # We set the form to be our ExampleApp (design)
form.show() # Show the form
app.exec_() # and execute the. app
if __name__ == '__main__': # if we're running file directly and not importing it
main() # run the main function
</code></pre>
<p>The error is:</p>
<pre><code>QWidget: Must construct a QApplication before a QPaintDevice
</code></pre>
| 0 |
2016-09-21T17:35:41Z
| 40,061,003 |
<p>The two things that need to be fixed with this code:
(1)
Remove pg from base class list, you don't inherit from the whole pyqtgraph library:</p>
<pre><code>class Gui(QtGui.QMainWindow, ui_test.Ui_MainWindow, pg):
</code></pre>
<p>to</p>
<pre><code>class Gui(QtGui.QMainWindow, ui_test.Ui_MainWindow):
</code></pre>
<p>(2)
Construct the viewbox inside the <strong>init</strong>:</p>
<pre><code>class Gui(QtGui.QMainWindow, ui_test.Ui_MainWindow):
def __init__(self):
super(self.__class__, self).__init__()
self.setupUi(self) # This is defined in ui_pumptest.py file automatically
self.vb = pg.ViewBox()
self.graphicsView.setCentralItem(self.vb) #set central item to be graph
</code></pre>
| 1 |
2016-10-15T15:40:31Z
|
[
"python",
"pyqt4",
"qgraphicsview",
"pyqtgraph"
] |
Copying a file to multiple paths at the same time
| 39,623,222 |
<p>I am transferring a 150-200mb file to many locations (shared drives located across the world) daily. The issue is that each transfer (using shutil) takes probably 100-700 seconds and each one has to complete in order for the next one to begin. It now takes like a full hour to transfer some files if I do it that way. My temporary solution was to create a separate .py file to run for each location so they can be done simultaneously, but that is not ideal.</p>
<p>How can I dip into multi-thread programming? I'd like to run all of the transfers at once but I have zero experience with this.</p>
<p>A simple google search landed me with:</p>
<p><a href="https://docs.python.org/3/library/concurrent.futures.html" rel="nofollow">https://docs.python.org/3/library/concurrent.futures.html</a>.</p>
<pre><code>import shutil
with ThreadPoolExecutor(max_workers=4) as e:
e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
e.submit(shutil.copy, 'src4.txt', 'dest4.txt')
</code></pre>
<p>Can someone point me into the right direction? I have been meaning to learn how to do things in parallel for a while now but never got around to it.</p>
| 0 |
2016-09-21T17:43:04Z
| 39,624,270 |
<p>Here's a working example that does what you want. Note that it may not be any faster than one-at-a-time if the bottleneck is network bandwidth.</p>
<pre><code>from concurrent.futures import ThreadPoolExecutor
import os
import shutil
import time
from threading import Lock
src_dir = './test_src'
src_files = 'src1.txt', 'src2.txt', 'src3.txt', 'src4.txt'
dst_dir = './test_dst'
print_lock = Lock()
_print = print # save original
def print(*args, **kwargs):
"""Prevents concurrent printing."""
with print_lock:
_print(*args, **kwargs)
def copy_file(src_file):
src_file = os.path.join(src_dir, src_file)
print('starting transfer of "{}"'.format(src_file))
shutil.copy2(src_file, dst_dir)
print('transfer of "{}" completed'.format(src_file))
with ThreadPoolExecutor(max_workers=4) as e:
jobs = [e.submit(copy_file, src_file) for src_file in src_files]
while any(job.running() for job in jobs):
time.sleep(.1)
print('done')
</code></pre>
| 1 |
2016-09-21T18:43:44Z
|
[
"python",
"python-3.x",
"shutil"
] |
SECRET_KEY errors with enviroment variables
| 39,623,443 |
<p>I am working through <a href="http://www.marinamele.com/taskbuster-django-tutorial/create-home-page-with-tdd-staticfiles-templates-settings" rel="nofollow">the TaskBuster Django</a> tutorial whose goal is to help in the process of setting up a good development setup for a project.</p>
<p>When I run the command
echo $SECRET_KEY</p>
<p>In either my "Dev" environment or my "Test" environment I get the same output so I believe that my $ENVIROMENTS/bin/postactivate and predeativate variables are set up correctly. </p>
<p>my base.py folder contains </p>
<pre><code> # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# Get SECRET_KEY from the virtual environment
from django.core.exceptions import ImproperlyConfigured
def get_env_variable(var_name):
try:
return os.environ[var_name]
except KeyError:
error_msg = "Set the %s environment variable" % var_name
raise ImproperlyConfigured(error_msg)
SECRET_KEY = get_env_variable('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'bapsite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'bapsite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
</code></pre>
<p>However, when I try to run the tests I get this output.</p>
<pre><code>Traceback (most recent call last):
File "/home/devin/DjangoProjects/bap_project/bapsite/settings/base.py", line 28, in get_env_variable
return os.environ[var_name]
File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/os.py", line 725, in __getitem__
raise KeyError(key) from None
KeyError: 'SECRET_KEY'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv
super(Command, self).run_from_argv(argv)
File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/core/management/base.py", line 378, in run_from_argv
parser = self.create_parser(argv[0], argv[1])
File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/core/management/base.py", line 351, in create_parser
self.add_arguments(parser)
File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/core/management/commands/test.py", line 52, in add_arguments
test_runner_class = get_runner(settings, self.test_runner)
File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/test/utils.py", line 144, in get_runner
test_runner_class = settings.TEST_RUNNER
File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/conf/__init__.py", line 48, in __getattr__
self._setup(name)
File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/conf/__init__.py", line 44, in _setup
self._wrapped = Settings(settings_module)
File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/site-packages/django/conf/__init__.py", line 92, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/home/devin/.virtualenvs/bapsite_test/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/devin/DjangoProjects/bap_project/bapsite/settings/testing.py", line 2, in <module>
from .base import *
File "/home/devin/DjangoProjects/bap_project/bapsite/settings/base.py", line 33, in <module>
SECRET_KEY = get_env_variable('SECRET_KEY')
File "/home/devin/DjangoProjects/bap_project/bapsite/settings/base.py", line 31, in get_env_variable
raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable
</code></pre>
<p>This leads me to believe that there is some issue with the secret key but I"m unclear how to troubleshoot from here. </p>
<p>is the return os.environ[var_name] returning the wrong value? How do I see what that is returning so I can point it to what I'd prefer it to return? Am I on the correct path to figuring this out?</p>
<p>Here is the testing file I am using currently</p>
<pre><code>from selenium import webdriver
from django.core.urlresolvers import reverse
from django.contrib.staticfiles.testing import LiveServerTestCase
class HomeNewVisitorTest(LiveServerTestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
def get_full_url(self, namespace):
return self.live_server_url + reverse(namespace)
def test_home_title(self):
self.browser.get(self.get_full_url("home"))
self.assertIn("TaskBuster", self.browser.title)
def test_h1_css(self):
self.browser.get(self.get_full_url("home"))
h1 = self.browser.find_element_by_tag_name("h1")
self.assertEqual(h1.value_of_css_property("color"),
"rgba(200, 50, 255, 1)")
</code></pre>
| 1 |
2016-09-21T17:55:27Z
| 39,623,714 |
<p>You don't have an environment variable named SECRET_KEY. You need to set it before you run your program. </p>
<p>On Unix</p>
<pre><code>export SECRET_KEY="password"
</code></pre>
<p>On Windows </p>
<pre><code>set SECRET_KEY="password"
</code></pre>
<p>It's worth noting that the variable will disappear when you close the terminal. There are ways around that if you'd like to look for them.</p>
| 1 |
2016-09-21T18:12:25Z
|
[
"python",
"django",
"testing",
"virtualenv"
] |
What is IF-MIB: snimpy.mib.SMIException: unable to find b'IF-MIB' (check the path)?
| 39,623,454 |
<p>I followed <a href="https://snimpy.readthedocs.io/en/latest/usage.html#regular-python-module" rel="nofollow">the doc</a> but got the following error:</p>
<pre><code>>>> from snimpy.manager import Manager as M
from snimpy.manager import load
load("IF-MIB")
m = M("localhost")
print(m.ifDescr[0])
Traceback (most recent call last):
File "<input>", line 4, in <module>
File "/home/ed8/projects/coaxis-opt/env/lib/python3.5/site-packages/snimpy/manager.py", line 578, in load
m = mib.load(mibname)
File "/home/ed8/projects/coaxis-opt/env/lib/python3.5/site-packages/snimpy/mib.py", line 605, in load
raise SMIException("unable to find {0} (check the path)".format(mib))
snimpy.mib.SMIException: unable to find b'IF-MIB' (check the path)
</code></pre>
<h3>Question</h3>
<p>What is <code>IF-MIB</code>? Do I need to install some package on my system?</p>
<h3>Reference</h3>
<p><a href="https://github.com/vincentbernat/snimpy/issues/57" rel="nofollow">Doc example fails: snimpy.mib.SMIException: unable to find b'IF-MIB' (check the path)</a></p>
| 0 |
2016-09-21T17:55:57Z
| 39,624,108 |
<p>As provided by <a href="https://github.com/vincentbernat/snimpy/issues/57#issuecomment-248692852" rel="nofollow">snimpy developer</a>:</p>
<blockquote>
<p>If you are on Ubuntu, you need to </p>
<pre><code>apt-get install snmp-mibs-downloader
</code></pre>
</blockquote>
| 0 |
2016-09-21T18:34:29Z
|
[
"python",
"snmp",
"mib",
"snimpy"
] |
Using local Python modules from python -c '...'
| 39,623,499 |
<p>I'm having trouble getting the Python 3.5 CLI to run commands with the <code>-c</code> switch.</p>
<p>If I try <code>python3 -c "print(5 + 9)"</code> in the shell, the output is <code>14</code> as expected.</p>
<p>However, I have a file in the current working directory called <code>gcd.py</code> that looks like this:</p>
<pre><code>def gcd(m, n):
return m if n == 0 else gcd(n, m % n)
</code></pre>
<p>If I run <code>python3 -m gcd -c "print(gcd(48, 18))"</code> the shell just creates a new command prompt without outputting anything.</p>
<p>If I change the file to:</p>
<pre><code>print('test')
def gcd(m, n):
return m if n == 0 else gcd(n, m % n)
</code></pre>
<p>then the shell will output <code>test</code>, so the file is being loaded. Does anybody know what I'm doing wrong? Thanks.</p>
| 0 |
2016-09-21T17:58:47Z
| 39,623,531 |
<p>You can't use <code>-m</code> and <code>-c</code> together; either one or the other controls execution. Specifying them both makes Python ignore them.</p>
<p>Use an <code>import</code> statement in <code>-c</code> instead:</p>
<pre><code>python3 -c "from gcd import gcd; print(gcd(48, 18))"
</code></pre>
<p>Note that <code>-m</code> treats the module as a script, it is not a 'import this module first' switch for <code>-c</code>.</p>
| 4 |
2016-09-21T18:00:54Z
|
[
"python",
"shell"
] |
How do I find a value relative to where a list occurs within my list in Python?
| 39,623,506 |
<p>I have a list of numbers:</p>
<pre><code>Data = [0,2,0,1,2,1,0,2,0,2,0,1,2,0,2,1,1,...]
</code></pre>
<p>And I have a list of tuples of two, which is all possible combinations of the individual numbers above:</p>
<pre><code>Combinations = [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)]
</code></pre>
<p>I want to try to find where each item in Combinations appears in Data and add the value after each occurrence to another list.</p>
<p>For example, for (0,2) I want to make a list [0,0,0,1] because those are the the values that fall immediately after (0,2) occurs in Data.</p>
<p>So far, I have:</p>
<pre><code>any(Data[i:i+len(CurrentTuple)] == CurrentTuple for i in xrange(len(Data)-len(CurrentTuple)+1))
</code></pre>
<p>Where <code>CurrentTuple</code> is <code>Combinations.pop()</code>.
The problem is that this only gives me a Boolean of whether the <code>CurrentTuple</code> occurs in Data. What I really need is the value after each occurrence in Data.</p>
<p>Does anyone have any ideas as to how this can be solved? Thanks!</p>
| 2 |
2016-09-21T17:59:24Z
| 39,623,756 |
<pre><code>sum([all(x) for x in (Data[i:i+len(CurrentTuple)] == CurrentTuple for i in xrange
(len(Data)-len(CurrentTuple)+1))])
</code></pre>
<p>What you did return a generator that produce the following list:</p>
<pre><code>[array([False, True], dtype=bool),
array([ True, False], dtype=bool),
array([False, True], dtype=bool),
...
array([False, False], dtype=bool),
array([False, False], dtype=bool),
array([False, False], dtype=bool),
array([False, True], dtype=bool)]
</code></pre>
<p>One of the array that you have in this list match the <code>CurrentTuple</code> only if both the <code>bool</code> in the array are <code>True</code>. The <code>all</code> return <code>True</code> only if all the elements of the list are <code>True</code> so the list generated by the <code>[all(x) for x in ...]</code> will contains <code>True</code> only if the twin of numbers match the <code>CurrentTuple</code>. A <code>True</code> is conted as <code>1</code> when you use <code>sum</code>. I hope it is clear. </p>
<p>If you want to compare only non-overlapping pairs:</p>
<pre><code>[2,2,
0,2,
...]
</code></pre>
<p>and keep the algorithm as general as possible, you can use the following:</p>
<pre><code>sum([all(x) for x in (Data[i:i+len(CurrentTuple)] == CurrentTuple for i in xrange
(0,len(Data)-len(CurrentTuple)+1,len(CurrentTuple)))])
</code></pre>
<p>Despite much more cryptic, this code is much faster than any alternative that using <code>append</code> (look [<a href="http://stackoverflow.com/questions/39518899/3-array-generators-faster-than-1-for-loop/39519661#39519661]">3 array generators faster than 1 for loop</a> to understand why).</p>
| 0 |
2016-09-21T18:14:47Z
|
[
"python",
"list",
"tuples",
"markov-chains"
] |
How do I find a value relative to where a list occurs within my list in Python?
| 39,623,506 |
<p>I have a list of numbers:</p>
<pre><code>Data = [0,2,0,1,2,1,0,2,0,2,0,1,2,0,2,1,1,...]
</code></pre>
<p>And I have a list of tuples of two, which is all possible combinations of the individual numbers above:</p>
<pre><code>Combinations = [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)]
</code></pre>
<p>I want to try to find where each item in Combinations appears in Data and add the value after each occurrence to another list.</p>
<p>For example, for (0,2) I want to make a list [0,0,0,1] because those are the the values that fall immediately after (0,2) occurs in Data.</p>
<p>So far, I have:</p>
<pre><code>any(Data[i:i+len(CurrentTuple)] == CurrentTuple for i in xrange(len(Data)-len(CurrentTuple)+1))
</code></pre>
<p>Where <code>CurrentTuple</code> is <code>Combinations.pop()</code>.
The problem is that this only gives me a Boolean of whether the <code>CurrentTuple</code> occurs in Data. What I really need is the value after each occurrence in Data.</p>
<p>Does anyone have any ideas as to how this can be solved? Thanks!</p>
| 2 |
2016-09-21T17:59:24Z
| 39,623,911 |
<p>You can use a dict to group the data to see where/if any comb lands in the original list zipping up pairs:</p>
<pre><code>it1, it2 = iter(Data), iter(Data)
next(it2)
Combinations = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
d = {c: [] for c in Combinations}
ind = 2
for i, j in zip(it1, it2):
if (i, j) in d and ind < len(Data):
d[(i, j)].append(Data[ind])
ind += 1
print(d)
</code></pre>
<p>Which would give you:</p>
<pre><code>{(0, 1): [2, 2], (1, 2): [1, 0], (0, 0): [], (2, 1): [0, 1], (1, 1): [2], (2, 0): [1, 2, 1, 2], (2, 2): [], (1, 0): [2], (0, 2): [0, 0, 0, 1]}
</code></pre>
<p>You could also do it in reverse:</p>
<pre><code>from collections import defaultdict
it1, it2 = iter(Data), iter(Data)
next(it2)
next_ele_dict = defaultdict(list)
data_iter = iter(Data[2:])
for ind, (i, j) in enumerate(zip(it1, it2)):
if ind < len(Data) -2:
next_ele_dict[(i, j)].append(next(data_iter))
def next_ele():
for comb in set(Combinations):
if comb in next_ele_dict:
yield comb, next_ele_dict[comb]
print(list(next_ele()))
</code></pre>
<p>Which would give you:</p>
<pre><code> [((0, 1), [2, 2]), ((1, 2), [1, 0]), ((2, 1), [0, 1]), ((1, 1), [2]), ((2, 0), [1, 2, 1, 2]), ((1, 0), [2]), ((0, 2), [0, 0, 0, 1])]
</code></pre>
<p>Any approach is better than a pass over the Data list for every element in Combinations.</p>
<p>To work for arbitrary length tuples we just need to create the tuples based on the length:</p>
<pre><code>from collections import defaultdict
n = 2
next_ele_dict = defaultdict(list)
def chunks(iterable, n):
for i in range(len(iterable)-n):
yield tuple(iterable[i:i+n])
data_iter = iter(Data[n:])
for tup in chunks(Data, n):
next_ele_dict[tup].append(next(data_iter))
def next_ele():
for comb in set(Combinations):
if comb in next_ele_dict:
yield comb, next_ele_dict[comb]
print(list(next_ele()))
</code></pre>
<p>You can apply it to whatever implementation you prefer, the logic will be the same as far as making the tuples goes.</p>
| 0 |
2016-09-21T18:24:44Z
|
[
"python",
"list",
"tuples",
"markov-chains"
] |
need help pivoting pandas table
| 39,623,521 |
<pre><code>print df
output_time position
0 2016-01-01 08:00:01 start
1 2016-01-01 08:07:53 end
2 2016-01-01 08:07:54 start
3 2016-01-01 08:09:23 end
4 2016-01-01 08:09:24 start
5 2016-01-01 08:32:51 end
</code></pre>
<p>I need the output as such (with df remaining a dataframe type not series type:</p>
<pre><code>print df
start end
2016-01-01 08:00:01 2016-01-01 08:07:53
2016-01-01 08:07:54 2016-01-01 08:09:23
2016-01-01 08:09:24 2016-01-01 08:32:51
</code></pre>
<p><code>df = df.pivot_table(columns="output_time", values="position")</code> gives the following error:</p>
<blockquote>
<p>raise DataError('No numeric types to aggregate')
pandas.core.base.DataError: No numeric types to aggregate</p>
</blockquote>
| 0 |
2016-09-21T18:00:27Z
| 39,623,713 |
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>pivot</code></a> instead of <code>pivot_table</code>:</p>
<pre><code># Perform the pivot.
df = df.pivot(index=df.index//2, columns='position')
# Format the columns.
df.columns = df.columns.droplevel(0).rename(None)
</code></pre>
<p>The resulting output:</p>
<pre><code> end start
0 2016-01-01 08:07:53 2016-01-01 08:00:01
1 2016-01-01 08:09:23 2016-01-01 08:07:54
2 2016-01-01 08:32:51 2016-01-01 08:09:24
</code></pre>
| 2 |
2016-09-21T18:12:25Z
|
[
"python",
"pandas",
"numpy"
] |
need help pivoting pandas table
| 39,623,521 |
<pre><code>print df
output_time position
0 2016-01-01 08:00:01 start
1 2016-01-01 08:07:53 end
2 2016-01-01 08:07:54 start
3 2016-01-01 08:09:23 end
4 2016-01-01 08:09:24 start
5 2016-01-01 08:32:51 end
</code></pre>
<p>I need the output as such (with df remaining a dataframe type not series type:</p>
<pre><code>print df
start end
2016-01-01 08:00:01 2016-01-01 08:07:53
2016-01-01 08:07:54 2016-01-01 08:09:23
2016-01-01 08:09:24 2016-01-01 08:32:51
</code></pre>
<p><code>df = df.pivot_table(columns="output_time", values="position")</code> gives the following error:</p>
<blockquote>
<p>raise DataError('No numeric types to aggregate')
pandas.core.base.DataError: No numeric types to aggregate</p>
</blockquote>
| 0 |
2016-09-21T18:00:27Z
| 39,623,755 |
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>cumcount</code></a> for creating new <code>index</code> values with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unstack.html" rel="nofollow"><code>unstack</code></a>:</p>
<pre><code>df['g'] = df.groupby('position').cumcount()
df1 = df.set_index(['g','position']).unstack()
df1.columns = df1.columns.droplevel(0)
df1.columns.name = None
df1.index.name = None
print (df1)
end start
0 2016-01-01 08:07:53 2016-01-01 08:00:01
1 2016-01-01 08:09:23 2016-01-01 08:07:54
2 2016-01-01 08:32:51 2016-01-01 08:09:24
</code></pre>
| 0 |
2016-09-21T18:14:43Z
|
[
"python",
"pandas",
"numpy"
] |
need help pivoting pandas table
| 39,623,521 |
<pre><code>print df
output_time position
0 2016-01-01 08:00:01 start
1 2016-01-01 08:07:53 end
2 2016-01-01 08:07:54 start
3 2016-01-01 08:09:23 end
4 2016-01-01 08:09:24 start
5 2016-01-01 08:32:51 end
</code></pre>
<p>I need the output as such (with df remaining a dataframe type not series type:</p>
<pre><code>print df
start end
2016-01-01 08:00:01 2016-01-01 08:07:53
2016-01-01 08:07:54 2016-01-01 08:09:23
2016-01-01 08:09:24 2016-01-01 08:32:51
</code></pre>
<p><code>df = df.pivot_table(columns="output_time", values="position")</code> gives the following error:</p>
<blockquote>
<p>raise DataError('No numeric types to aggregate')
pandas.core.base.DataError: No numeric types to aggregate</p>
</blockquote>
| 0 |
2016-09-21T18:00:27Z
| 39,624,264 |
<p>This seems to be really quick though <code>pivot_table</code> was actually asked:</p>
<pre><code>data = df.T.unstack().ravel()
pd.DataFrame(data={data[1]:data[0::4], data[3]:data[2::4]})
</code></pre>
<p><a href="http://i.stack.imgur.com/yD8xc.png" rel="nofollow"><img src="http://i.stack.imgur.com/yD8xc.png" alt="Image"></a></p>
| 0 |
2016-09-21T18:43:30Z
|
[
"python",
"pandas",
"numpy"
] |
Solving an ordinary differential equation on a fixed grid (preferably in python)
| 39,623,613 |
<p>I have a differential equation of the form </p>
<p><code>dy(x)/dx = f(y,x)</code></p>
<p>that I would like to solve for <code>y</code>. </p>
<p>I have an array <code>xs</code> containing all of the values of <code>x</code> for which I need <code>ys</code>. </p>
<p>For only those values of <code>x</code>, I can evaluate <code>f(y,x)</code> for any <code>y</code>. </p>
<p>How can I solve for <code>ys</code>, preferably in python?</p>
<h2>MWE</h2>
<pre><code>import numpy as np
# these are the only x values that are legal
xs = np.array([0.15, 0.383, 0.99, 1.0001])
# some made up function --- I don't actually have an analytic form like this
def f(y, x):
if not np.any(np.isclose(x, xs)):
return np.nan
return np.sin(y + x**2)
# now I want to know which array of ys satisfies dy(x)/dx = f(y,x)
</code></pre>
| 2 |
2016-09-21T18:05:32Z
| 39,623,781 |
<p>Assuming you can use something simple like Forward Euler...</p>
<p>Numerical solutions will rely on approximate solutions at previous times. So if you want a solution at <code>t = 1</code> it is likely you will need the approximate solution at <code>t<1</code>.</p>
<p>My advice is to figure out what step size will allow you to hit the times you need, and then find the approximate solution on an interval containing those times.</p>
<pre><code>import numpy as np
#from your example, smallest step size required to hit all would be 0.0001.
a = 0 #start point
b = 1.5 #possible end point
h = 0.0001
N = float(b-a)/h
y = np.zeros(n)
t = np.linspace(a,b,n)
y[0] = 0.1 #initial condition here
for i in range(1,n):
y[i] = y[i-1] + h*f(t[i-1],y[i-1])
</code></pre>
<p>Alternatively, you could use an adaptive step method (which I am not prepared to explain right now) to take larger steps between the times you need.</p>
<p>Or, you could find an approximate solution over an interval using a coarser mesh and interpolate the solution.</p>
<p>Any of these should work. </p>
| 0 |
2016-09-21T18:16:10Z
|
[
"python",
"math",
"mathematical-optimization",
"numerical-methods",
"differential-equations"
] |
Solving an ordinary differential equation on a fixed grid (preferably in python)
| 39,623,613 |
<p>I have a differential equation of the form </p>
<p><code>dy(x)/dx = f(y,x)</code></p>
<p>that I would like to solve for <code>y</code>. </p>
<p>I have an array <code>xs</code> containing all of the values of <code>x</code> for which I need <code>ys</code>. </p>
<p>For only those values of <code>x</code>, I can evaluate <code>f(y,x)</code> for any <code>y</code>. </p>
<p>How can I solve for <code>ys</code>, preferably in python?</p>
<h2>MWE</h2>
<pre><code>import numpy as np
# these are the only x values that are legal
xs = np.array([0.15, 0.383, 0.99, 1.0001])
# some made up function --- I don't actually have an analytic form like this
def f(y, x):
if not np.any(np.isclose(x, xs)):
return np.nan
return np.sin(y + x**2)
# now I want to know which array of ys satisfies dy(x)/dx = f(y,x)
</code></pre>
| 2 |
2016-09-21T18:05:32Z
| 39,624,481 |
<p>I think you should first solve ODE on a regular grid, and then interpolate solution on your fixed grid. The approximate code for your problem</p>
<pre><code>import numpy as np
from scipy.integrate import odeint
from scipy import interpolate
xs = np.array([0.15, 0.383, 0.99, 1.0001])
# dy/dx = f(x,y)
def dy_dx(y, x):
return np.sin(y + x ** 2)
y0 = 0.0 # init condition
x = np.linspace(0, 10, 200)# here you can control an accuracy
sol = odeint(dy_dx, y0, x)
f = interpolate.interp1d(x, np.ravel(sol))
ys = f(xs)
</code></pre>
<p>But dy_dx(y, x) should always return something reasonable (not np.none).
Here is the drawing for this case
<a href="http://i.stack.imgur.com/j5RdJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/j5RdJ.png" alt="enter image description here"></a></p>
| 0 |
2016-09-21T18:58:23Z
|
[
"python",
"math",
"mathematical-optimization",
"numerical-methods",
"differential-equations"
] |
Prevent PyPI from publishing a new version until all wheels are uploaded?
| 39,623,682 |
<p>We have a Python package which we distribute via PyPI. We create wheels for Win x64, Win x86, and Mac.</p>
<p>We use AppVeyor for the Windows builds and Travis for the Mac build.</p>
<p>The problem we have is that all the wheels don't finish at the same time, but as soon as the first wheel is uploaded to PyPI, then our package page gets rev'ed to the latest version even though all the wheels aren't uploaded.</p>
<p>So we're running into the situation where a user randomly tries to install our package via pip when PyPI has been rev'ed to the new version but the wheel for their platform isn't up yet, and then they get a pip error.</p>
<p>Is there an elegant way to solve this? I haven't found anything so far.</p>
<p>Thanks!
Brian</p>
| 1 |
2016-09-21T18:10:20Z
| 39,624,118 |
<p>What I just did was I downloaded all wheels manually from CI after they're all built (OK, using <a href="https://github.com/MacPython/terryfy" rel="nofollow">https://github.com/MacPython/terryfy</a>, but that is a detail) and then uploaded them all in one go manually. Not exacty <em>elegant</em>, I know. But that does minimize the time the PyPI page is inconsistent to several minutes. </p>
| 1 |
2016-09-21T18:35:18Z
|
[
"python",
"pypi"
] |
How to export Bokeh view to Matplotlib?
| 39,623,694 |
<p><p>
I have a Flask web app that uses Bokeh to deliver interactive charts. My end goal is to export whatever the current Bokeh view is to Matplotlib (so that I can create a printable pdf file after that). This would include how the current axes look like after the user zooms and pans. Is there a way to export that data so that I can create those Matplotlib charts behind the scenes? (Printing the page directly or printing to pdf results in low-quality and blurred charts.)<p>
Thanks!</p>
| 0 |
2016-09-21T18:11:26Z
| 39,625,002 |
<p>No, currently there is no way to export bokeh to matplotlib. Actually you can do it otherway. You can create matplotlib plot, save, and after that you can <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/compat.html#bokeh.mpl.to_bokeh" rel="nofollow">export matplotlib to bokeh</a>. I think this is the best option. Eventually you can export bokeh plot as png but it still would not solve problem with quality </p>
| 0 |
2016-09-21T19:26:16Z
|
[
"python",
"matplotlib",
"flask",
"pdf-generation",
"bokeh"
] |
TensorFlow Multi-Layer Perceptron
| 39,623,747 |
<p>I am learning TensorFlow, and my goal is to implement MultiPerceptron for my needs. I checked the <a href="https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/multilayer_perceptron.py" rel="nofollow">MNIST tutorial with MultiPerceptron implementation</a> and everything was clear to me except this:</p>
<pre><code> _, c = sess.run([optimizer, cost], feed_dict={x: batch_x,
y: batch_y})
</code></pre>
<p>I guess, <code>x</code> is an image itself(28*28 pixels, so the input is 784 neurons) and <code>y</code> is a label which is an 1x10 array:</p>
<pre><code>x = tf.placeholder("float", [None, n_input])
y = tf.placeholder("float", [None, n_classes])
</code></pre>
<p>They feed whole batches (which are packs of data points and labels)! How does tensorflow interpret this "batch" input? And how does it update the weights: simultaneously after each element in a batch, or after running through the whole batch?</p>
<p>And, if I need to input one number (<code>input_shape = [1,1]</code>) and output four numbers (<code>output_shape = [1,4]</code>), how should I change the <code>tf.placeholders</code> and in which form should I feed them into session?</p>
<ol>
<li><p>When I ask, how does tensorflow interpret it, I want to know how tensorflow splits the batch into single elements. For example, batch is a 2-D array, right? In which direction does it split an array? Or it uses matrix operations and doesn't split anything?</p></li>
<li><p>When I ask, how should I feed my data, I want to know, should it be a 2-D array with samples at its rows and features at its columns, or, maybe, could it be a 2-D list. </p></li>
</ol>
<p>When I feed my float numpy array <code>X_train</code> to <code>x</code>, which is :</p>
<pre><code>x = tf.placeholder("float", [1, n_input])
</code></pre>
<p>I receive an error:</p>
<p><code>ValueError: Cannot feed value of shape (1, 18) for Tensor 'Placeholder_10:0', which has shape '(1, 1)'</code></p>
<p>It appears that I have to create my data as a Tensor too?</p>
<p>When I tried [18x1]:</p>
<p><code>Cannot feed value of shape (18, 1) for Tensor 'Placeholder_12:0', which has shape '(1, 1)'</code></p>
| 0 |
2016-09-21T18:14:22Z
| 39,623,857 |
<blockquote>
<p>They feed whole bathces(which are packs of data points and labels)!</p>
</blockquote>
<p>Yes, this is how neural networks are usually trained (due to some nice mathematical properties of having best of two worlds - better gradient approximation than in SGD on one hand and much faster convergence than full GD). </p>
<blockquote>
<p>How does tensorflow interpret this "batch" input?</p>
</blockquote>
<p>It "interprets" it according to operations in your graph. You probably have <strong>reduce mean</strong> somewhere in your graph, which calculates <strong>average</strong> over your batch, thus causing this to be the "interpretation". </p>
<blockquote>
<p>And how does it update the weights: 1.simultaniusly after each element in a batch? 2. After running threw the whole batch?.</p>
</blockquote>
<p>As in the previous answer - there is nothing "magical" about batch, it is just another dimension, and each internal operation of neural net is well defined for the batch of data, thus there is still <strong>a single</strong> update in the end. Since you use reduce mean operation (or maybe reduce sum?) you are updating according to mean of the "small" gradients (or sum if there is reduce sum instead). Again - you could control it (up to the agglomerative behaviour, you cannot force it to do per-sample update unless you introduce while loop into the graph).</p>
<blockquote>
<p>And, if i need to imput one number(input_shape = [1,1]) and ouput four nubmers (output_shape = [1,4]), how should i change the tf.placeholders and in which form should i feed them into session? THANKS!!</p>
</blockquote>
<p>just set the variables, <code>n_input=1</code> and <code>n_classes=4</code>, and you push your data as before, as [batch, n_input] and [batch, n_classes] arrays (in your case batch=1, if by "1x1" you mean "one sample of dimension 1", since your edit start to suggest that you actually do have a batch, and by 1x1 you meant a 1d input).</p>
<blockquote>
<p>EDIT: 1.when i ask, how does tensorflow interpret it, i want to know, how tensorflow split the batch into single elements. For example, batch is a 2-D array, right? In which direction it splits an array. Or it uses matrix operations and doesnt split anything? 2. When i ask, how should i feed my data, i want to know, should it be a 2-D array with samples at its rows and features at its colums, or, maybe, could it be a 2-D list.</p>
</blockquote>
<p>It <strong>does not</strong> split anything. It is just a matrix, and each operation is perfectly well defined for matrices as well. <strong>Usually</strong> you put examples in rows, thus in <strong>first dimension</strong>, and this is exactly what [batch, n_inputs] says - that you have <code>batch</code> rows each with <code>n_inputs</code> columns. But again - there is nothing special about it, and you could also create a graph which accepts column-wise batches if you would really need to. </p>
| 1 |
2016-09-21T18:20:57Z
|
[
"python",
"machine-learning",
"tensorflow"
] |
How to authenticate in Jenkins while remotely accessing its JSON API?
| 39,623,786 |
<p>I need to access the Jenkins JSON API from a Python script. The problem is that our Jenkins installation is secured so to log in users have to select a certificate. Sadly, in Jenkins <a href="https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API" rel="nofollow">Remote Access Documentation</a> they don't mention a thing about certificates and I tried using the API Token without success.</p>
<p>How can I get to authenticate from a Python script to use their JSON API?</p>
<p>Thanks in advance!</p>
| 1 |
2016-09-21T18:16:30Z
| 39,625,595 |
<p>I finally found out how to authenticate to Jenkins using certs and wget. I had to convert my pfx certificates into pem ones with cert and keys in separate files <a href="http://stackoverflow.com/questions/15144046/need-help-converting-p12-certificate-into-pem-using-openssl">For more info about that come here</a>. In the end this is the command I used.</p>
<pre><code>wget --certificate=/home/B/cert.pem --private-key=/home/B/key.pem --no-check-certificate --output-document=jenkins.json https:<URL>
</code></pre>
| 0 |
2016-09-21T20:03:11Z
|
[
"python",
"authentication",
"jenkins"
] |
How to authenticate in Jenkins while remotely accessing its JSON API?
| 39,623,786 |
<p>I need to access the Jenkins JSON API from a Python script. The problem is that our Jenkins installation is secured so to log in users have to select a certificate. Sadly, in Jenkins <a href="https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API" rel="nofollow">Remote Access Documentation</a> they don't mention a thing about certificates and I tried using the API Token without success.</p>
<p>How can I get to authenticate from a Python script to use their JSON API?</p>
<p>Thanks in advance!</p>
| 1 |
2016-09-21T18:16:30Z
| 39,626,190 |
<p>You have to authenticate to the JSON API using HTTP Basic Auth. </p>
<blockquote>
<p>To make scripted clients (such as wget) invoke operations that require authorization (such as scheduling a build), use HTTP BASIC authentication to specify the user name and the API token. This is often more convenient than emulating the form-based authentication</p>
</blockquote>
<p><a href="https://wiki.jenkins-ci.org/display/JENKINS/Authenticating+scripted+clients" rel="nofollow">https://wiki.jenkins-ci.org/display/JENKINS/Authenticating+scripted+clients</a></p>
<p>Here is a sample of using Basic Auth with Python. </p>
<p><a href="http://docs.python-requests.org/en/master/user/authentication/" rel="nofollow">http://docs.python-requests.org/en/master/user/authentication/</a></p>
<p>Keep in mind if you are using a Self Signed certificate on an internal Jenkin Server you'll need to turn off certificate validation <strong>OR</strong> get the certificate from the server and add it to the HTTP request</p>
<p><a href="http://docs.python-requests.org/en/master/user/advanced/" rel="nofollow">http://docs.python-requests.org/en/master/user/advanced/</a></p>
| 1 |
2016-09-21T20:39:34Z
|
[
"python",
"authentication",
"jenkins"
] |
Search XML Tags for Name Attribute: Python elementTree module
| 39,623,852 |
<p>I'm trying to parse an XML doc in Python using the <code>ElementTree</code> module. I'm trying to look for <code>Elements</code> that have an xml tag of <code>entry</code> and a <code>name</code> attribute within that tag that equals a certain <code>ipAddress</code>. Below is my code so far:</p>
<pre><code>tree = ET.parse(fi2)
root = tree.getroot()
for child in root.iter('entry'): #looks through child elements for tag=entry
#look for elements that have an attribute(name)='string'
</code></pre>
<p>For reference, when I use the code <code>print child.tag, child.attrib</code> within the <code>for</code> loop, I get the following output:</p>
<pre><code>entry {'name': 'ipAddress'}
</code></pre>
<p>I need assistance searching for <code>entry</code> tags with a <code>name attribute</code> of <code>ipAddress</code></p>
| 0 |
2016-09-21T18:20:40Z
| 39,623,925 |
<pre><code>import xml.etree.ElementTree as ET
tree = ET.parse(your_xml)
root = tree.getroot()
for child in root:
if child.tag=='entry':
for node in child:
if node.attrib["name"]=='certain_ip':
print("found")
</code></pre>
| 0 |
2016-09-21T18:25:29Z
|
[
"python",
"xml",
"elementtree"
] |
Search XML Tags for Name Attribute: Python elementTree module
| 39,623,852 |
<p>I'm trying to parse an XML doc in Python using the <code>ElementTree</code> module. I'm trying to look for <code>Elements</code> that have an xml tag of <code>entry</code> and a <code>name</code> attribute within that tag that equals a certain <code>ipAddress</code>. Below is my code so far:</p>
<pre><code>tree = ET.parse(fi2)
root = tree.getroot()
for child in root.iter('entry'): #looks through child elements for tag=entry
#look for elements that have an attribute(name)='string'
</code></pre>
<p>For reference, when I use the code <code>print child.tag, child.attrib</code> within the <code>for</code> loop, I get the following output:</p>
<pre><code>entry {'name': 'ipAddress'}
</code></pre>
<p>I need assistance searching for <code>entry</code> tags with a <code>name attribute</code> of <code>ipAddress</code></p>
| 0 |
2016-09-21T18:20:40Z
| 39,626,880 |
<pre><code>tree = ET.parse(fi2)
root = tree.getroot()
for child in root.iter('entry'): #looks through child elements for tag=entry
#look for elements that have an attribute(name)='string'
if ipAddress in child.get('name'):
#condition is met. Execute some code. Do your thang
</code></pre>
| 0 |
2016-09-21T21:30:14Z
|
[
"python",
"xml",
"elementtree"
] |
Creating a Pandas DataFrame with HDFS file in .csv format
| 39,623,858 |
<p>Im trying to create a Spark workflow from fetching .csv data from a hadoop cluster and putting it into Pandas DataFrame. I'm able to pull the Data from HDFS and put it in an RDD, but unable to process it into the Pandas Dataframe.
The following is my code:</p>
<pre><code>import pandas as pd
import numpy as nm
A=sc.textFile("hdfs://localhost:9000/sales_ord_univ.csv") # this creates the RDD
B=pd.DataFrame(A) # this gives me the following error:pandas.core.common.PandasError: DataFrame constructor not properly called!
</code></pre>
<p>I'm pretty sure this error is as such due to the RDD being a big single <strong>list</strong>,
Hence I tried splitting the data by ';'( i.e each new row is a different string)
But that didn't seem to help either. </p>
<p>My overall goal is to use Pandas to change CSV into JSON and output into MongoDB. I have done this project using DictReader, PysparkSQL, but wanted to check if it is possible using Pandas.</p>
<p>Any help would be appreciated
Thanks!</p>
| 0 |
2016-09-21T18:21:00Z
| 39,625,656 |
<p>I would recommend to load the csv into a Spark DataFrame and convert it to a Pandas DataFrame.</p>
<pre><code>csvDf = sqlContext.read.format("csv").option("header", "true").option("inferschema", "true").option("mode", "DROPMALFORMED").load("hdfs://localhost:9000/sales_ord_univ.csv")
B = csvDf.toPandas()
</code></pre>
<p>If you are still using a Spark version < 2.0, you have to use <code>read.format("com.databricks.spark.csv")</code> and include the com.databricks.spark.csv package (e.g. with the <code>--packages</code> parameter when using the pyspark shell).</p>
| 0 |
2016-09-21T20:06:32Z
|
[
"python",
"csv",
"hadoop",
"pandas",
"pyspark"
] |
Adjusting matplotlib colormap to show simulation
| 39,623,883 |
<p>I'm building a little simulation based on this experiment:
<a href="https://www.youtube.com/watch?v=plVk4NVIUh8" rel="nofollow">https://www.youtube.com/watch?v=plVk4NVIUh8</a> , which shows the evolution of a bacteria over time.</p>
<p>I have initialized some bacteria with random resistance at the edge of a petri dish:</p>
<p><a href="http://i.stack.imgur.com/VSiDA.png" rel="nofollow"><img src="http://i.stack.imgur.com/VSiDA.png" alt="enter image description here"></a></p>
<p>As the bacteria spreads, the contrast from the non occupied space is less and less, after a 100 generation it becomes like this:
<a href="http://i.stack.imgur.com/kZvuc.png" rel="nofollow"><img src="http://i.stack.imgur.com/kZvuc.png" alt="enter image description here"></a> </p>
<p>I use plt.matshow(Map) to make the pictures, where Map is a 2D numpy array, with bacteria resistance values (always bigger than 0), the non occupied space is represented as 0. I tried different colormaps, but it did not help. My aim is to make the non occupied space some constant dark color,
the infected space some light color, with conrtast to notice the different resistance values.</p>
<p>Can you help me with that?</p>
| 0 |
2016-09-21T18:22:34Z
| 39,624,288 |
<p>You could get a <a href="http://matplotlib.org/users/colormaps.html" rel="nofollow">colormap</a> with a dark color for low values, such as 'magma' and define, as Andreas suggested a 'vmin' value. e.g.</p>
<pre><code>import matplotlib.pyplot as plt
from scipy import rand
a = rand(10, 20) + 0.5
a[0, 0] = 0
cmap = plt.get_cmap('magma')
img = plt.pcolormesh(a, cmap=cmap, vmin=0,)
img.figure.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/ZXBPt.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZXBPt.png" alt="enter image description here"></a></p>
<p>Cheers!
S</p>
| 1 |
2016-09-21T18:45:10Z
|
[
"python",
"numpy",
"matplotlib",
"simulation"
] |
Adjusting matplotlib colormap to show simulation
| 39,623,883 |
<p>I'm building a little simulation based on this experiment:
<a href="https://www.youtube.com/watch?v=plVk4NVIUh8" rel="nofollow">https://www.youtube.com/watch?v=plVk4NVIUh8</a> , which shows the evolution of a bacteria over time.</p>
<p>I have initialized some bacteria with random resistance at the edge of a petri dish:</p>
<p><a href="http://i.stack.imgur.com/VSiDA.png" rel="nofollow"><img src="http://i.stack.imgur.com/VSiDA.png" alt="enter image description here"></a></p>
<p>As the bacteria spreads, the contrast from the non occupied space is less and less, after a 100 generation it becomes like this:
<a href="http://i.stack.imgur.com/kZvuc.png" rel="nofollow"><img src="http://i.stack.imgur.com/kZvuc.png" alt="enter image description here"></a> </p>
<p>I use plt.matshow(Map) to make the pictures, where Map is a 2D numpy array, with bacteria resistance values (always bigger than 0), the non occupied space is represented as 0. I tried different colormaps, but it did not help. My aim is to make the non occupied space some constant dark color,
the infected space some light color, with conrtast to notice the different resistance values.</p>
<p>Can you help me with that?</p>
| 0 |
2016-09-21T18:22:34Z
| 39,677,557 |
<p>I was able to make the visulaization better, using logaritmic normalization: Let's say my bacteriaMap has really different resistancevalues:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
size=10
a = rand(size, size) * 0.2
b = rand(size, size) * 2
c = rand(size, size) * 20
sumMap = np.concatenate((a,b,c), axis=1)
</code></pre>
<p>sumMap is the numpy array to plot, with small, medium and big numbers.
Building up colormap and normalizer:</p>
<pre><code>maxval=np.max(sumh)
minval=np.min(sumh)
colormap = plt.get_cmap('magma')
norm = mpl.colors.LogNorm(vmax=maxval, vmin=minval)
</code></pre>
<p>If I use the normalization the map loks like this:</p>
<pre><code>img = plt.pcolormesh(sumh, cmap=colormap, norm=norm)
img.figure.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/XoLNN.png" rel="nofollow"><img src="http://i.stack.imgur.com/XoLNN.png" alt="enter image description here"></a></p>
<p>If I don't:</p>
<pre><code>img = plt.pcolormesh(sumh, cmap=cmap, )
img.figure.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/aNT1b.png" rel="nofollow"><img src="http://i.stack.imgur.com/aNT1b.png" alt="enter image description here"></a></p>
| 0 |
2016-09-24T14:39:45Z
|
[
"python",
"numpy",
"matplotlib",
"simulation"
] |
Is there any way to print **kwargs in Python
| 39,623,889 |
<p>I am just curious about <code>**kwargs</code>. I am just started learning it, So while going through all the question on stackoverflow and video tutorials I notice we can do like this </p>
<pre><code>def print_dict(**kwargs):
print(kwargs)
print_dict(x=1,y=2,z=3)
</code></pre>
<p>Which gives output as :<code>{'y': 2, 'x': 1, 'z': 3}</code>
So I figures why not do the reverse and print the like <code>x=1,y=2,z=3</code></p>
<p>So I tried this:</p>
<pre><code>mydict = {'x':1,'y':2,'z':3}
print(**mydict)
</code></pre>
<p>But I got an error like : <code>TypeError: 'z' is an invalid keyword argument for this function</code>(sometimes it shows 'y' is an invalid keyword).</p>
<p>I also tried like assign it to the variable and then print it but again i got an error (<code>SyntaxError: invalid syntax</code>):</p>
<pre><code>mydict = {'x':1,'y':2,'z':3}
var = **mydict
print(var)
</code></pre>
<p>See this is working:</p>
<pre><code>def print_dict(**this):
print(this)
mydict = {'x':1,'y':2,'z':3}
print_dict(**mydict)
</code></pre>
<p>But instead of <code>print(this)</code> if i do <code>print(**this)</code> it gives the error.</p>
<p>As we can print <code>*arg</code> as I try this code:</p>
<pre><code>def num(*tuple_num):
print(tuple_num)
print(*tuple_num)
num(1,2,3,4)
</code></pre>
<p>It run perfectly and gives output as:</p>
<pre><code>(1, 2, 3, 4)
1 2 3 4
</code></pre>
<p>So I want to know is there any possible solution/way to print <code>**kwargs</code> ?</p>
| 2 |
2016-09-21T18:23:04Z
| 39,623,935 |
<p>You have to build your own formatting for dictionaries (nothing else are <code>**kwargs</code>):</p>
<pre><code>print(','.join('{0}={1!r}'.format(k,v) for k,v in this.items()))
</code></pre>
| 4 |
2016-09-21T18:26:07Z
|
[
"python"
] |
Is there any way to print **kwargs in Python
| 39,623,889 |
<p>I am just curious about <code>**kwargs</code>. I am just started learning it, So while going through all the question on stackoverflow and video tutorials I notice we can do like this </p>
<pre><code>def print_dict(**kwargs):
print(kwargs)
print_dict(x=1,y=2,z=3)
</code></pre>
<p>Which gives output as :<code>{'y': 2, 'x': 1, 'z': 3}</code>
So I figures why not do the reverse and print the like <code>x=1,y=2,z=3</code></p>
<p>So I tried this:</p>
<pre><code>mydict = {'x':1,'y':2,'z':3}
print(**mydict)
</code></pre>
<p>But I got an error like : <code>TypeError: 'z' is an invalid keyword argument for this function</code>(sometimes it shows 'y' is an invalid keyword).</p>
<p>I also tried like assign it to the variable and then print it but again i got an error (<code>SyntaxError: invalid syntax</code>):</p>
<pre><code>mydict = {'x':1,'y':2,'z':3}
var = **mydict
print(var)
</code></pre>
<p>See this is working:</p>
<pre><code>def print_dict(**this):
print(this)
mydict = {'x':1,'y':2,'z':3}
print_dict(**mydict)
</code></pre>
<p>But instead of <code>print(this)</code> if i do <code>print(**this)</code> it gives the error.</p>
<p>As we can print <code>*arg</code> as I try this code:</p>
<pre><code>def num(*tuple_num):
print(tuple_num)
print(*tuple_num)
num(1,2,3,4)
</code></pre>
<p>It run perfectly and gives output as:</p>
<pre><code>(1, 2, 3, 4)
1 2 3 4
</code></pre>
<p>So I want to know is there any possible solution/way to print <code>**kwargs</code> ?</p>
| 2 |
2016-09-21T18:23:04Z
| 39,623,954 |
<p>The syntax <code>callable(**dictionary)</code> <em>applies</em> the dictionary as if you used separate keyword arguments.</p>
<p>So your example:</p>
<pre><code>mydict = {'x':1,'y':2,'z':3}
print(**mydict)
</code></pre>
<p>Is internally translated to:</p>
<pre><code>print(x=1, y=2, z=3)
</code></pre>
<p>where the exact ordering depends on the current random hash seed. Since <code>print()</code> doesn't support those keyword arguments the call fails.</p>
<p>The other <code>print()</code> call succeeds, because you passed in the values as separate <em>positional</em> arguments:</p>
<pre><code>tuple_num = (1, 2, 3, 4)
print(*tuple_num)
</code></pre>
<p>is effectively the same as:</p>
<pre><code>print(1, 2, 3, 4)
</code></pre>
<p>and the <code>print()</code> function supports separate arguments by writing them out one by one with the <code>sep</code> value in between (which is a space by default).</p>
<p>The <code>**dictionary</code> is not valid syntax outside of a call. Since <code>callable(**dictionary)</code> is part of the call syntax, and not an object, there is <em>nothing to print</em>.</p>
<p>At most, you can <em>format</em> the dictionary to look like the call:</p>
<pre><code>print(', '.join(['{}={!r}'.format(k, v) for k, v in mydict.items()]))
</code></pre>
| 7 |
2016-09-21T18:26:44Z
|
[
"python"
] |
cycle "for" in Python
| 39,623,953 |
<p>I have to create a three new lists of items using two different lists.</p>
<pre><code>list_one = ['one', 'two','three', 'four','five']
list_two = ['blue', 'green', 'white']
</code></pre>
<p>So, <code>len(list_one) != len(list_two)</code></p>
<p>Now I should create an algorithm(a cycle) which can do this:
<code>[oneblue, twoblue, threeblue, fourblue, fiveblue]</code>. Same for 'green' and 'white'.</p>
<p>I undestand that I should create three cycles but I don't know how.
I've tried to make a function like this but it doesn't works.</p>
<pre><code>def mix():
i = 0
for i in range(len(list_one)):
new_list = list_one[i]+list_two[0]
i = i+1
return new_list
</code></pre>
<p>What am I doing wrong?</p>
| -2 |
2016-09-21T18:26:43Z
| 39,624,005 |
<p>I think you might be looking for <a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow">itertools.product</a>:</p>
<pre><code>>>> [b + a for a,b in itertools.product(list_two, list_one)]
['oneblue',
'twoblue',
'threeblue',
'fourblue',
'fiveblue',
'onegreen',
'twogreen',
'threegreen',
'fourgreen',
'fivegreen',
'onewhite',
'twowhite',
'threewhite',
'fourwhite',
'fivewhite']
</code></pre>
| 2 |
2016-09-21T18:29:04Z
|
[
"python"
] |
cycle "for" in Python
| 39,623,953 |
<p>I have to create a three new lists of items using two different lists.</p>
<pre><code>list_one = ['one', 'two','three', 'four','five']
list_two = ['blue', 'green', 'white']
</code></pre>
<p>So, <code>len(list_one) != len(list_two)</code></p>
<p>Now I should create an algorithm(a cycle) which can do this:
<code>[oneblue, twoblue, threeblue, fourblue, fiveblue]</code>. Same for 'green' and 'white'.</p>
<p>I undestand that I should create three cycles but I don't know how.
I've tried to make a function like this but it doesn't works.</p>
<pre><code>def mix():
i = 0
for i in range(len(list_one)):
new_list = list_one[i]+list_two[0]
i = i+1
return new_list
</code></pre>
<p>What am I doing wrong?</p>
| -2 |
2016-09-21T18:26:43Z
| 39,624,047 |
<ul>
<li>return should be out of for loop.</li>
<li>No need to initialize <code>i</code> and increment it, since you are using range.</li>
<li>Also, since both list can be of variable length, don't use range. Iterate over the list elements directly.</li>
<li><code>def mix():</code> should be like <code>def mix(l_one,l_two):</code></li>
</ul>
<p>All above in below code:</p>
<pre><code>def mix(l_one,l_two):
new_list = []
for x in l_one:
for y in l_two:
new_list.append(x+y)
return new_list
list_one = ['one', 'two','three', 'four','five']
list_two = ['blue', 'green', 'white']
n_list = mix(list_one,list_two)
print n_list
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>C:\Users\dinesh_pundkar\Desktop>python c.py
['oneblue', 'onegreen', 'onewhite', 'twoblue', 'twogreen', 'twowhite', 'threeblu
e', 'threegreen', 'threewhite', 'fourblue', 'fourgreen', 'fourwhite', 'fiveblue'
, 'fivegreen', 'fivewhite']
C:\Users\dinesh_pundkar\Desktop>
</code></pre>
<p>Using List Comprehension, <code>mix()</code> function will look like below:</p>
<pre><code> def mix(l_one,l_two):
new_list =[x+y for x in l_one for y in l_two]
return new_list
</code></pre>
| 0 |
2016-09-21T18:31:09Z
|
[
"python"
] |
cycle "for" in Python
| 39,623,953 |
<p>I have to create a three new lists of items using two different lists.</p>
<pre><code>list_one = ['one', 'two','three', 'four','five']
list_two = ['blue', 'green', 'white']
</code></pre>
<p>So, <code>len(list_one) != len(list_two)</code></p>
<p>Now I should create an algorithm(a cycle) which can do this:
<code>[oneblue, twoblue, threeblue, fourblue, fiveblue]</code>. Same for 'green' and 'white'.</p>
<p>I undestand that I should create three cycles but I don't know how.
I've tried to make a function like this but it doesn't works.</p>
<pre><code>def mix():
i = 0
for i in range(len(list_one)):
new_list = list_one[i]+list_two[0]
i = i+1
return new_list
</code></pre>
<p>What am I doing wrong?</p>
| -2 |
2016-09-21T18:26:43Z
| 39,624,084 |
<p>You should do this</p>
<pre><code>def cycle(list_one,list_two):
newList = []
for el1 in list_two:
for el2 in list_one:
newList.append(el2+el1)
return newList
</code></pre>
| 0 |
2016-09-21T18:33:20Z
|
[
"python"
] |
cycle "for" in Python
| 39,623,953 |
<p>I have to create a three new lists of items using two different lists.</p>
<pre><code>list_one = ['one', 'two','three', 'four','five']
list_two = ['blue', 'green', 'white']
</code></pre>
<p>So, <code>len(list_one) != len(list_two)</code></p>
<p>Now I should create an algorithm(a cycle) which can do this:
<code>[oneblue, twoblue, threeblue, fourblue, fiveblue]</code>. Same for 'green' and 'white'.</p>
<p>I undestand that I should create three cycles but I don't know how.
I've tried to make a function like this but it doesn't works.</p>
<pre><code>def mix():
i = 0
for i in range(len(list_one)):
new_list = list_one[i]+list_two[0]
i = i+1
return new_list
</code></pre>
<p>What am I doing wrong?</p>
| -2 |
2016-09-21T18:26:43Z
| 39,624,148 |
<p>There are a few problems with your code:</p>
<ol>
<li><p>When you do a for loop <code>for i in ...:</code>, you do not need to initialize <code>i</code> (<code>i = 0</code>) and you should not increment it (<code>i = i + 1</code>) since Python knows that <code>i</code> will take all values specified in the for loop definition.</p></li>
<li><p>If your code indentation (indentation is very important in Python) is truly the one written above, your <code>return</code> statement is inside the for loop. As soon as your function encounters your return statement, your function will exit and return what you specified: in this case, a string.</p></li>
<li><p><code>new_list</code> is not a list but a string.</p></li>
<li><p>In Python, you can loop directly over the list items as opposed to their index (<code>for item in list_one:</code> as opposed to <code>for i in range(len(list_one)):</code></p></li>
</ol>
<p>Here is your code cleaned up:</p>
<pre><code>def mix():
new_list = []
for i in list_one:
new_list.append(list_one[i]+list_two[0])
return new_list
</code></pre>
<p>This can be rewritten using a list comprehension:</p>
<pre><code>def mix(list_one, list_two):
return [item+list_two[0] for item in list_one]
</code></pre>
<p>And because <code>list_two</code> has more than one item, you would need to iterate over <code>list_two</code> as well:</p>
<pre><code>def mix(list_one, list_two):
return [item+item2 for item in list_one for item2 in list_two]
</code></pre>
| 0 |
2016-09-21T18:36:58Z
|
[
"python"
] |
cycle "for" in Python
| 39,623,953 |
<p>I have to create a three new lists of items using two different lists.</p>
<pre><code>list_one = ['one', 'two','three', 'four','five']
list_two = ['blue', 'green', 'white']
</code></pre>
<p>So, <code>len(list_one) != len(list_two)</code></p>
<p>Now I should create an algorithm(a cycle) which can do this:
<code>[oneblue, twoblue, threeblue, fourblue, fiveblue]</code>. Same for 'green' and 'white'.</p>
<p>I undestand that I should create three cycles but I don't know how.
I've tried to make a function like this but it doesn't works.</p>
<pre><code>def mix():
i = 0
for i in range(len(list_one)):
new_list = list_one[i]+list_two[0]
i = i+1
return new_list
</code></pre>
<p>What am I doing wrong?</p>
| -2 |
2016-09-21T18:26:43Z
| 39,624,394 |
<p>Another way to achieve this using <code>map()</code>. Just mentioning as the option:</p>
<pre><code>>>> from itertools import product
>>> map(lambda x: ''.join(x), product(list_one, list_two))
['oneblue', 'onegreen', 'onewhite', 'twoblue', 'twogreen', 'twowhite', 'threeblue', 'threegreen', 'threewhite', 'fourblue', 'fourgreen', 'fourwhite', 'fiveblue', 'fivegreen', 'fivewhite']
</code></pre>
| 0 |
2016-09-21T18:52:23Z
|
[
"python"
] |
In pandas dataframe, generate third column data based on results in two other columns
| 39,623,977 |
<p>I'm a newbie to dataframes. I have columns <code>A</code>, <code>B</code> and <code>C</code> and want to use the data in A and B to create a value in C. For example, if <code>A = 1</code> and/or <code>B = 1</code>, then I want to place a <code>1</code> in column <code>C</code> and do this logic for all rows in the dataframe.</p>
<p>e.g. starting array:</p>
<pre><code> A B C
0 1 0
1 0 1
2 1 1
3 0 0
</code></pre>
<p>etc </p>
<p>resulting array:</p>
<pre><code> A B C
0 1 0 1
1 0 1 1
2 1 1 1
3 0 0 0
</code></pre>
<p>etc</p>
| 2 |
2016-09-21T18:27:45Z
| 39,624,056 |
<pre><code>def f(x):
if (x.B==1) and (x.A !=1): #Or whatever logic you like
return 1
else:
return 0
df['C'] = df.apply(lambda x: f(x), axis = 1)
</code></pre>
| 0 |
2016-09-21T18:31:34Z
|
[
"python",
"pandas",
"dataframe",
"boolean",
"condition"
] |
In pandas dataframe, generate third column data based on results in two other columns
| 39,623,977 |
<p>I'm a newbie to dataframes. I have columns <code>A</code>, <code>B</code> and <code>C</code> and want to use the data in A and B to create a value in C. For example, if <code>A = 1</code> and/or <code>B = 1</code>, then I want to place a <code>1</code> in column <code>C</code> and do this logic for all rows in the dataframe.</p>
<p>e.g. starting array:</p>
<pre><code> A B C
0 1 0
1 0 1
2 1 1
3 0 0
</code></pre>
<p>etc </p>
<p>resulting array:</p>
<pre><code> A B C
0 1 0 1
1 0 1 1
2 1 1 1
3 0 0 0
</code></pre>
<p>etc</p>
| 2 |
2016-09-21T18:27:45Z
| 39,624,075 |
<p>Given a starting DF of:</p>
<pre><code>df = pd.DataFrame({'A': [1, 0, 1, 0], 'B': [0, 1, 1, 0]})
</code></pre>
<p>Then you can create column <code>C</code> as such:</p>
<pre><code>df['C'] = (df == 1).any(axis=1).astype(int)
</code></pre>
<p>Then leaves <code>df</code> as:</p>
<pre><code> A B C
0 1 0 1
1 0 1 1
2 1 1 1
3 0 0 0
</code></pre>
| 2 |
2016-09-21T18:32:44Z
|
[
"python",
"pandas",
"dataframe",
"boolean",
"condition"
] |
In pandas dataframe, generate third column data based on results in two other columns
| 39,623,977 |
<p>I'm a newbie to dataframes. I have columns <code>A</code>, <code>B</code> and <code>C</code> and want to use the data in A and B to create a value in C. For example, if <code>A = 1</code> and/or <code>B = 1</code>, then I want to place a <code>1</code> in column <code>C</code> and do this logic for all rows in the dataframe.</p>
<p>e.g. starting array:</p>
<pre><code> A B C
0 1 0
1 0 1
2 1 1
3 0 0
</code></pre>
<p>etc </p>
<p>resulting array:</p>
<pre><code> A B C
0 1 0 1
1 0 1 1
2 1 1 1
3 0 0 0
</code></pre>
<p>etc</p>
| 2 |
2016-09-21T18:27:45Z
| 39,624,091 |
<p>Use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>:</p>
<pre><code>df['C'] = np.where(df.A | df.B, 1, 0)
print (df)
A B C
0 0 0 0
1 0 1 1
2 1 0 1
3 1 1 1
df['C'] = np.where((df.A == 0) & (df.B == 0), 0, 1)
print (df)
A B C
0 0 0 0
1 0 1 1
2 1 0 1
3 1 1 1
</code></pre>
<p>Or simplier convert boolean <code>Series</code> to <code>int</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>astype</code></a>:</p>
<pre><code>df['C'] = (df.A | df.B).astype(int)
print (df)
A B C
0 0 0 0
1 0 1 1
2 1 0 1
3 1 1 1
df['C'] = (~((df.A == 0) & (df.B == 0))).astype(int)
print (df)
A B C
0 0 0 0
1 0 1 1
2 1 0 1
3 1 1 1
</code></pre>
| 2 |
2016-09-21T18:33:36Z
|
[
"python",
"pandas",
"dataframe",
"boolean",
"condition"
] |
In pandas dataframe, generate third column data based on results in two other columns
| 39,623,977 |
<p>I'm a newbie to dataframes. I have columns <code>A</code>, <code>B</code> and <code>C</code> and want to use the data in A and B to create a value in C. For example, if <code>A = 1</code> and/or <code>B = 1</code>, then I want to place a <code>1</code> in column <code>C</code> and do this logic for all rows in the dataframe.</p>
<p>e.g. starting array:</p>
<pre><code> A B C
0 1 0
1 0 1
2 1 1
3 0 0
</code></pre>
<p>etc </p>
<p>resulting array:</p>
<pre><code> A B C
0 1 0 1
1 0 1 1
2 1 1 1
3 0 0 0
</code></pre>
<p>etc</p>
| 2 |
2016-09-21T18:27:45Z
| 39,624,158 |
<p>You can use the logical functions of numpy <code>logical_and</code> and <code>logical_or</code></p>
<pre><code>import numpy as np
df['C'] = np.logical_and(df['A'], df['B']).astype(int)
</code></pre>
| 0 |
2016-09-21T18:37:34Z
|
[
"python",
"pandas",
"dataframe",
"boolean",
"condition"
] |
In pandas dataframe, generate third column data based on results in two other columns
| 39,623,977 |
<p>I'm a newbie to dataframes. I have columns <code>A</code>, <code>B</code> and <code>C</code> and want to use the data in A and B to create a value in C. For example, if <code>A = 1</code> and/or <code>B = 1</code>, then I want to place a <code>1</code> in column <code>C</code> and do this logic for all rows in the dataframe.</p>
<p>e.g. starting array:</p>
<pre><code> A B C
0 1 0
1 0 1
2 1 1
3 0 0
</code></pre>
<p>etc </p>
<p>resulting array:</p>
<pre><code> A B C
0 1 0 1
1 0 1 1
2 1 1 1
3 0 0 0
</code></pre>
<p>etc</p>
| 2 |
2016-09-21T18:27:45Z
| 39,624,164 |
<p>Other solution using a <code>list comprehesion</code> and <code>zip</code></p>
<pre><code>df['C'] = [(1 if i or j == 1 else 0) for i,j in zip(df['A'], df['B'])]
</code></pre>
<p>it returns:</p>
<pre><code> A B C
0 1 0 1
1 0 1 1
2 1 1 1
3 0 0 0
</code></pre>
<p>Change the condition if <code>'A'</code> and <code>'B'</code> <code>==</code> <strong><em>1</em></strong> use <code>&</code>:</p>
<p>Example:</p>
<pre><code>df['C'] = [(1 if i & j == 1 else 0) for i,j in zip(df['A'], df['B'])]
</code></pre>
<p>This will return:</p>
<pre><code> A B C
0 1 0 0
1 0 1 0
2 1 1 1
3 0 0 0
</code></pre>
| 0 |
2016-09-21T18:37:50Z
|
[
"python",
"pandas",
"dataframe",
"boolean",
"condition"
] |
WEIRD Django AuthenticationForm Behaviour
| 39,623,998 |
<p>I have, all day, tried to figure this out but I can't really see where the problem is coming from.</p>
<p>I have a <strong>Django</strong> <code>AuthenticationForm</code> that seems to be submitting data somehow but not getting validated.</p>
<p><strong>forms.py</strong>:</p>
<pre><code>class LoginForm(AuthenticationForm):
username = forms.CharField(widget=forms.TextInput(attrs={'name': 'username'}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'name': 'password'}))
</code></pre>
<p><strong>views.py</strong>:</p>
<pre><code>def index(request):
template = 'myapp/login.html'
if request.method == "POST":
print request.POST #prints QueryDict with its data
reg = LoginForm(request.POST or None)
if reg.is_valid():
return HttpResponse('Success: Form is valid!')
else:
return HttpResponse('Error: Form not valid')
loginform = LoginForm()
context = {'loginform':loginform}
return render(request, template, context)
</code></pre>
<p><strong>HTML</strong>:</p>
<pre><code> <form method="post" action=".">
{% csrf_token %}
<h2>Sign in</h2>
<p class="text-danger">{{loginform.errors}}</p>
{{ loginform.as_p }}
<button name = "signin" type="submit" value="0">Sign in</button>
</form>
</code></pre>
<p>The <code>print request.POST</code> in my views.py prints <em>QueryDict: {u'username': [u'yax'], u'csrfmiddlewaretoken': [u'r8y1PaVNjxNWypdzP
MaFe1ZL7IkE1O7Hw0yRPQTSipW36z1g7X3vPS5qMMX56byj'], u'password': [u'sdfdsfsddfs']
, u'signin': [u'0']}</em> but the <code>reg.is_valid()</code> keeps returning <code>false</code>.</p>
<p><strong>EDIT</strong>:</p>
<p>I have also tried printing out <code>reg.errors</code> but it doesn't print out anything.</p>
| 1 |
2016-09-21T18:28:59Z
| 39,624,185 |
<p>Try making the following change:</p>
<pre><code>reg = LoginForm(data=request.POST)
</code></pre>
<p><code>AuthenticationForm</code> is slightly different in that it needs the <code>data</code> argument.</p>
<p>Also note that you should test it with actually valid username and password combinations (that correspond to an existing user), since <code>AuthenticationForm</code> checks for that as well.</p>
| 1 |
2016-09-21T18:39:18Z
|
[
"python",
"django",
"python-2.7",
"django-forms"
] |
Is it possible to cast dtype of scipy CSR matrix to NPY_FLOAT?
| 39,624,043 |
<p>I have a scipy CSR matrix that was constructed from a COO matrix as follows:</p>
<pre><code>coord_mat = coo_matrix((data, (row, col)), dtype=np.float64)
</code></pre>
<p>It is being used as an input to a library with an underlying C implementation, and I believe that the dtype of my matrix is <code>double(np.float64)</code>. However, I'm encountering the following error:</p>
<pre><code>ValueError: Buffer dtype mismatch, expected 'flt' but got 'double'
</code></pre>
<p>I went to do some research and found the <a href="http://docs.scipy.org/doc/numpy/reference/c-api.dtype.html#c.NPY_FLOAT" rel="nofollow">scipy C-api</a>, which informed me that the <code>NPY_FLOAT</code> data type is converted to a 32-bit float in C, while the current data type I have corresponds to a 64-bit double. Am I on the right track here? If so, how do I cast the type of the array? I'm not entirely sure how I can call on the <code>NPY_FLOAT</code> object in order to cast it.</p>
<p>Any help on this matter would be deeply appreciated!</p>
| 0 |
2016-09-21T18:30:56Z
| 39,625,960 |
<p>I'm not sure about the <code>C</code> interface, I'll try to explain the <code>coo_matrix</code> part.</p>
<p>Since you are using the tuple input it splits that into 3 variables</p>
<pre><code>obj, (row, col) = arg1
</code></pre>
<p>then it assigns those to attributes</p>
<pre><code>self.row = np.array(row, copy=copy, dtype=idx_dtype)
self.col = np.array(col, copy=copy, dtype=idx_dtype)
self.data = np.array(obj, copy=copy)
</code></pre>
<p>and since you specified a dtype</p>
<pre><code>if dtype is not None:
self.data = self.data.astype(dtype)
</code></pre>
<p>If <code>data</code>, <code>row</code> and <code>col</code> are already arrays, any you didn't specify the dtype, the sparse matrix can use those inputs as attributes without copying. Your dtype parameter will produce a copy.</p>
<p>The sparse matrix is not a <code>numpy</code> array, but rather an object that has 3 arrays as attribute. The matrix accepts the <code>astype</code> method, which probably does that same <code>self.data.astype</code> action. So I think you case comes down to: can you cast any array to that type.</p>
| 0 |
2016-09-21T20:24:27Z
|
[
"python",
"numpy",
"scipy",
"python-c-api"
] |
Extract data from "e under title tag using BeautifulSoup?
| 39,624,126 |
<p>I want to extract title of a link after getting its HTML via <code>BeautifulSoup</code> library in python.
Basically, the whole title tag is </p>
<pre><code> <title>Imaan Z Hazir on Twitter: &quot;Guantanamo and Abu Ghraib, financial and military support to dictators in Latin America during the cold war. REALLY, AMERICA? (3)&quot;</title>
</code></pre>
<p>I want to extract data that is in &quot tags that is only this <code>Guantanamo and Abu Ghraib, financial and military support to dictators in Latin America during the cold war. REALLY, AMERICA? (3)</code>
I tried as </p>
<pre><code>import urllib
import urllib.request
from bs4 import BeautifulSoup
link = "https://twitter.com/ImaanZHazir/status/778560899061780481"
try:
List=list()
r = urllib.request.Request(link, headers={'User-Agent': 'Chrome/51.0.2704.103'})
h = urllib.request.urlopen(r).read()
data = BeautifulSoup(h,"html.parser")
for i in data.find_all("title"):
List.append(i.text)
print(List[0])
except urllib.error.HTTPError as err:
pass
</code></pre>
<p>I also tried as </p>
<pre><code>for i in data.find_all("title.&quot"):
for i in data.find_all("title>&quot"):
for i in data.find_all("&quot"):
</code></pre>
<p>and </p>
<pre><code>for i in data.find_all("quot"):
</code></pre>
<p>But no one is working.</p>
| 1 |
2016-09-21T18:36:01Z
| 39,624,609 |
<p>Once you have parsed the html:</p>
<pre><code>data = BeautifulSoup(h,"html.parser")
</code></pre>
<p>Find the title this way:</p>
<pre><code>title = data.find("title").string # this is without <title> tag
</code></pre>
<p>Now find two quotes (<code>"</code>) in the string. There are many ways to do that. I would use regex:</p>
<pre><code>import re
match = re.search(r'".*"', title)
if match:
print match.group(0)
</code></pre>
<p>You never search for <code>&quot;</code> or any other <code>&NAME;</code> sequences because BeautifulSoup converts them to the actual characters they represent.</p>
<p><strong>EDIT:</strong></p>
<p>Regex which does not capture the quotes would be:</p>
<pre><code>re.search(r'(?<=").*(?=")', title)
</code></pre>
| 0 |
2016-09-21T19:05:06Z
|
[
"python",
"css-selectors",
"beautifulsoup",
"html-parser"
] |
Extract data from "e under title tag using BeautifulSoup?
| 39,624,126 |
<p>I want to extract title of a link after getting its HTML via <code>BeautifulSoup</code> library in python.
Basically, the whole title tag is </p>
<pre><code> <title>Imaan Z Hazir on Twitter: &quot;Guantanamo and Abu Ghraib, financial and military support to dictators in Latin America during the cold war. REALLY, AMERICA? (3)&quot;</title>
</code></pre>
<p>I want to extract data that is in &quot tags that is only this <code>Guantanamo and Abu Ghraib, financial and military support to dictators in Latin America during the cold war. REALLY, AMERICA? (3)</code>
I tried as </p>
<pre><code>import urllib
import urllib.request
from bs4 import BeautifulSoup
link = "https://twitter.com/ImaanZHazir/status/778560899061780481"
try:
List=list()
r = urllib.request.Request(link, headers={'User-Agent': 'Chrome/51.0.2704.103'})
h = urllib.request.urlopen(r).read()
data = BeautifulSoup(h,"html.parser")
for i in data.find_all("title"):
List.append(i.text)
print(List[0])
except urllib.error.HTTPError as err:
pass
</code></pre>
<p>I also tried as </p>
<pre><code>for i in data.find_all("title.&quot"):
for i in data.find_all("title>&quot"):
for i in data.find_all("&quot"):
</code></pre>
<p>and </p>
<pre><code>for i in data.find_all("quot"):
</code></pre>
<p>But no one is working.</p>
| 1 |
2016-09-21T18:36:01Z
| 39,626,388 |
<p>Here is a simple complete example using regex to extract the text within quotes:</p>
<pre><code>import urllib
import re
from bs4 import BeautifulSoup
link = "https://twitter.com/ImaanZHazir/status/778560899061780481"
r = urllib.request.urlopen(link)
soup = BeautifulSoup(r, "html.parser")
title = soup.title.string
quote = re.match(r'^.*\"(.*)\"', title)
print(quote.group(1))
</code></pre>
<p>What happen's here is that after getting pages's source and finding the <code>title</code> we use a regular expression against the title to extract the text within the quotes.</p>
<p>We tell the regular expression to look for an arbitrary number of symbols at the beginning of the string (<code>^.*</code>) before the opening quote (<code>\"</code>), then capture the text between it and the closing quote (second <code>\"</code>).</p>
<p>Then we print the captured text by telling Python to print the first captured group (the part between parenthesis in regex).</p>
<p>Here's more on matching with regex in python - <a href="https://docs.python.org/3/library/re.html#match-objects" rel="nofollow">https://docs.python.org/3/library/re.html#match-objects</a></p>
| 0 |
2016-09-21T20:52:21Z
|
[
"python",
"css-selectors",
"beautifulsoup",
"html-parser"
] |
Extract data from "e under title tag using BeautifulSoup?
| 39,624,126 |
<p>I want to extract title of a link after getting its HTML via <code>BeautifulSoup</code> library in python.
Basically, the whole title tag is </p>
<pre><code> <title>Imaan Z Hazir on Twitter: &quot;Guantanamo and Abu Ghraib, financial and military support to dictators in Latin America during the cold war. REALLY, AMERICA? (3)&quot;</title>
</code></pre>
<p>I want to extract data that is in &quot tags that is only this <code>Guantanamo and Abu Ghraib, financial and military support to dictators in Latin America during the cold war. REALLY, AMERICA? (3)</code>
I tried as </p>
<pre><code>import urllib
import urllib.request
from bs4 import BeautifulSoup
link = "https://twitter.com/ImaanZHazir/status/778560899061780481"
try:
List=list()
r = urllib.request.Request(link, headers={'User-Agent': 'Chrome/51.0.2704.103'})
h = urllib.request.urlopen(r).read()
data = BeautifulSoup(h,"html.parser")
for i in data.find_all("title"):
List.append(i.text)
print(List[0])
except urllib.error.HTTPError as err:
pass
</code></pre>
<p>I also tried as </p>
<pre><code>for i in data.find_all("title.&quot"):
for i in data.find_all("title>&quot"):
for i in data.find_all("&quot"):
</code></pre>
<p>and </p>
<pre><code>for i in data.find_all("quot"):
</code></pre>
<p>But no one is working.</p>
| 1 |
2016-09-21T18:36:01Z
| 39,627,577 |
<p>Just split the text on the colon:</p>
<pre><code>In [1]: h = """<title>Imaan Z Hazir on Twitter: &quot;Guantanamo and Abu Ghraib, financial and military support to dictators in Latin America during the cold war. REALLY, AMERICA? (3)&quot;</title>"""
In [2]: from bs4 import BeautifulSoup
In [3]: soup = BeautifulSoup(h, "lxml")
In [4]: print(soup.title.text.split(": ", 1)[1])
"Guantanamo and Abu Ghraib, financial and military support to dictators in Latin America during the cold war. REALLY, AMERICA? (3)"
</code></pre>
<p>Actually looking at the page you don't need to split at all, the text is in the <em>p</em> tag inside the <em>div.js-tweet-text-container</em>, th:</p>
<pre><code>In [8]: import requests
In [9]: from bs4 import BeautifulSoup
In [10]: soup = BeautifulSoup(requests.get("https://twitter.com/ImaanZHazir/status/778560899061780481").content, "lxml")
In [11]: print(soup.select_one("div.js-tweet-text-container p").text)
Guantanamo and Abu Ghraib, financial and military support to dictators in Latin America during the cold war. REALLY, AMERICA? (3)
In [12]: print(soup.title.text.split(": ", 1)[1])
"Guantanamo and Abu Ghraib, financial and military support to dictators in Latin America during the cold war. REALLY, AMERICA? (3)"
</code></pre>
<p>So you can do it either way for the same result.</p>
| 0 |
2016-09-21T22:37:16Z
|
[
"python",
"css-selectors",
"beautifulsoup",
"html-parser"
] |
Clojure equivalent of python int.from_bytes(byteorder='big')
| 39,624,132 |
<p>The Python built in method <code>int.from_bytes()</code> returns the integer represented by the given array of bytes. I wanted know the Clojure equivalent of such method or similar methods in Clojure.</p>
| 0 |
2016-09-21T18:36:16Z
| 39,624,791 |
<p>You could use java's <a href="https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#BigInteger(byte[])" rel="nofollow">java's BigInteger</a> directly:</p>
<pre><code>(BigInteger. (byte-array [1 2 3]))
=> 66051
</code></pre>
<p>Since clojure natively supports big numbers, you could use it seamlessly with clojure's arithmetics:</p>
<pre><code>(def b (BigInteger. (byte-array [1 2 3])))
(+ b 23)
=> 66074N
</code></pre>
| 2 |
2016-09-21T19:14:29Z
|
[
"python",
"clojure"
] |
Python Unit Test subtle bug
| 39,624,159 |
<p>I'm new to Python and I've read the unit test documentation for python and I'm doing something different from the examples provided. I'm comparing sets. I don't know why my code keeps getting a failure. It seems like the code is written correctly. Can someone take a gander and see if they can resolve the problem? I will be eternally greatful!!</p>
<p>I'm trying to get better at unit testing so that's why I'm working this code out. </p>
<pre><code>import unittest
def determineIntersections(listingData, carList):
listingDataKeys = []
for key in listingData:
listingDataKeys.append(key)
carListKeys = []
for car in carList:
carListKeys.append(car[0])
intersection = set(carListKeys).intersection(set(listingDataKeys))
difference = set(carListKeys).symmetric_difference(set(listingDataKeys))
resultList = {'intersection' : intersection,
'difference' : difference}
return resultList
class TestHarness(unittest.TestCase):
def test_determineIntersections(self):
listingData = {"a": "", "b": "", "c": "", "d": ""}
carList = {"a": "", "e": "", "f": ""}
results = determineIntersections(listingData, carList)
print results['intersection']
print results['difference']
self.assertEqual(len(results['intersection']), 1)
self.assertSetEqual(results['intersection'], set(["a"]) # offending code piece
self.assertEqual(results['difference'], set(["b", "c", "d", "e", "f"])) # offending code piece
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>When I disable the "offending code piece" that is the asserts for the set comparison, the code behaves correctly but when I enable the code I get the following output: </p>
<pre><code>python UnitTester.py
File "UnitTester.py", line 39
if __name__ == '__main__':
^
SyntaxError: invalid syntax
</code></pre>
<p>Any ideas greatly appreciated! Thanks. </p>
| 1 |
2016-09-21T18:37:35Z
| 39,624,213 |
<p>You're simply missing a parentheses at the end of </p>
<pre><code>self.assertSetEqual(results['intersection'], set(["a"])
</code></pre>
<p>This confuses the interpreter. Change it to</p>
<pre><code>self.assertSetEqual(results['intersection'], set(["a"]))
</code></pre>
<p>In general, you might try to find an editor (or editor settings) that match parentheses, or warn about unmatched parentheses.</p>
| 2 |
2016-09-21T18:40:44Z
|
[
"python",
"unit-testing"
] |
Linked List Type Error
| 39,624,170 |
<p>I am a beginner and I started learning python programming and I am stuck with an error. I get a type error</p>
<pre><code>class Node:
def __init__(self):
self.data = None
self.next = Node
def setData(self,data)
self.data = data
def getData(self):
return self.data
def setNext(self,next):
self.next = next
def getNext(self):
return self.next
def hasNext(self):
return self.next!=None
class LinkedList(object):
def __init__(self):
self.length = 0
self.head = None
def listLength(self):
currentNode = self.head
length = 0
while currentNode.hasNext:
length = length + 1
currentNode = currentNode.getNext()
return length
"""
Methods to Insert nodes in a Linked List:
# insertNode: Use this method to simply insert a node to the Linked List
# insertHead: Use this method to insert a node at the head of the Linked List
# insertTail: Use this method to insert a node at the tail of the Linked List
# insertAtPosition: Use this method to insert a node at a particular position of the Linked List
"""
def insertNode(self,node):
if self.length == 0:
self.insertHead(node)
else:
self.insertTail(node)
def insertHead(self, data):
nodeToBeInserted = Node()
nodeToBeInserted.setData(data)
if self.length == 0:
self.head = nodeToBeInserted
else:
nodeToBeInserted.setNext(self.head)
self.head = nodeToBeInserted
self.length = self.length + 1
def insertTail(self,data):
nodeToBeInserted = Node()
nodeToBeInserted.setData(data)
currentNode = self.head
while currentNode.getNext() != None:
currentNode = currentNode.getNext()
currentNode.setNext(nodeToBeInserted)
self.length = self.length + 1
def insertAtPosition(self,data, position):
if position > self.length or position < 0:
print("Invalid position!, The size of the Linked List is:%s"%self.length)
else:
if position ==0:
self.insertHead(data)
else:
nodeToBeInserted = Node()
nodeToBeInserted.setData(data)
currentNode = self.head
count = 0
while count < position - 1:
currentNode = currentNode.getNext()
count = count + 1
nodeToBeInserted.setNext(currentNode.getNext())
currentNode.setNext(nodeToBeInserted)
self.length = self.length+1
ll = LinkedList()
ll.insertNode(1)
ll.insertNode(2)
ll.insertNode(3)
</code></pre>
<p>The error I am seeing is:</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/XPS 13/PycharmProjects/DataStructures/LinkedList/Implementation/SinglyLinkedList.py", line 154, in <module>
ll.insertNode(2)
File "C:/Users/XPS 13/PycharmProjects/DataStructures/LinkedList/Implementation/SinglyLinkedList.py", line 92, in insertNode
self.insertTail(node)
File "C:/Users/XPS 13/PycharmProjects/DataStructures/LinkedList/Implementation/SinglyLinkedList.py", line 121, in insertTail
while currentNode.getNext() != None:
TypeError: getNext() missing 1 required positional argument: 'self'
Process finished with exit code 1
</code></pre>
<p>If someone can please explain me the reason for this error it will be appreciated.</p>
<p>Thank you.</p>
| 0 |
2016-09-21T18:38:20Z
| 39,624,269 |
<p>Looks like you've got a typo right here:</p>
<pre><code>class Node:
def __init__(self):
self.data = None
self.next = Node
</code></pre>
<p>That should be <code>self.next = None</code>.</p>
<p>The reason you're getting <code>getNext() missing 1 required positional argument</code> is because eventually <code>insertTail</code> reaches the end of the linked list, and the <code>Node</code> type is assigned to <code>currentNode</code>. So the next time you call <code>currentNode.getNext()</code>, you're actually calling <code>Node.getNext()</code>, which raises the error because there's no Node instance to implicitly assign to <code>self</code>.</p>
| 0 |
2016-09-21T18:43:43Z
|
[
"python",
"linked-list",
"typeerror"
] |
Linked List Type Error
| 39,624,170 |
<p>I am a beginner and I started learning python programming and I am stuck with an error. I get a type error</p>
<pre><code>class Node:
def __init__(self):
self.data = None
self.next = Node
def setData(self,data)
self.data = data
def getData(self):
return self.data
def setNext(self,next):
self.next = next
def getNext(self):
return self.next
def hasNext(self):
return self.next!=None
class LinkedList(object):
def __init__(self):
self.length = 0
self.head = None
def listLength(self):
currentNode = self.head
length = 0
while currentNode.hasNext:
length = length + 1
currentNode = currentNode.getNext()
return length
"""
Methods to Insert nodes in a Linked List:
# insertNode: Use this method to simply insert a node to the Linked List
# insertHead: Use this method to insert a node at the head of the Linked List
# insertTail: Use this method to insert a node at the tail of the Linked List
# insertAtPosition: Use this method to insert a node at a particular position of the Linked List
"""
def insertNode(self,node):
if self.length == 0:
self.insertHead(node)
else:
self.insertTail(node)
def insertHead(self, data):
nodeToBeInserted = Node()
nodeToBeInserted.setData(data)
if self.length == 0:
self.head = nodeToBeInserted
else:
nodeToBeInserted.setNext(self.head)
self.head = nodeToBeInserted
self.length = self.length + 1
def insertTail(self,data):
nodeToBeInserted = Node()
nodeToBeInserted.setData(data)
currentNode = self.head
while currentNode.getNext() != None:
currentNode = currentNode.getNext()
currentNode.setNext(nodeToBeInserted)
self.length = self.length + 1
def insertAtPosition(self,data, position):
if position > self.length or position < 0:
print("Invalid position!, The size of the Linked List is:%s"%self.length)
else:
if position ==0:
self.insertHead(data)
else:
nodeToBeInserted = Node()
nodeToBeInserted.setData(data)
currentNode = self.head
count = 0
while count < position - 1:
currentNode = currentNode.getNext()
count = count + 1
nodeToBeInserted.setNext(currentNode.getNext())
currentNode.setNext(nodeToBeInserted)
self.length = self.length+1
ll = LinkedList()
ll.insertNode(1)
ll.insertNode(2)
ll.insertNode(3)
</code></pre>
<p>The error I am seeing is:</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/XPS 13/PycharmProjects/DataStructures/LinkedList/Implementation/SinglyLinkedList.py", line 154, in <module>
ll.insertNode(2)
File "C:/Users/XPS 13/PycharmProjects/DataStructures/LinkedList/Implementation/SinglyLinkedList.py", line 92, in insertNode
self.insertTail(node)
File "C:/Users/XPS 13/PycharmProjects/DataStructures/LinkedList/Implementation/SinglyLinkedList.py", line 121, in insertTail
while currentNode.getNext() != None:
TypeError: getNext() missing 1 required positional argument: 'self'
Process finished with exit code 1
</code></pre>
<p>If someone can please explain me the reason for this error it will be appreciated.</p>
<p>Thank you.</p>
| 0 |
2016-09-21T18:38:20Z
| 39,624,291 |
<p><code>while currentNode.hasNext</code> is always true, because it is a method.</p>
<p>On the other hand, <code>while currentNode.hasNext()</code> might be false at some point.</p>
<hr>
<p><code>self.next = Node</code> means the class is next.</p>
<p>On the other hand, <code>self.next = Node()</code> would make a new instance.</p>
<p>But I guess you don't want that, because it would try to create an endless linked list, so <code>self.next = None</code> might be better.</p>
<p>This causes <code>currentNode = currentNode.getNext()</code> to assign the class to <code>currentNode</code> and then later, the next call to <code>currentNode.getNext()</code> is actually calling <code>Node.getNext()</code> which causes this error.</p>
| 0 |
2016-09-21T18:45:32Z
|
[
"python",
"linked-list",
"typeerror"
] |
Linked List Type Error
| 39,624,170 |
<p>I am a beginner and I started learning python programming and I am stuck with an error. I get a type error</p>
<pre><code>class Node:
def __init__(self):
self.data = None
self.next = Node
def setData(self,data)
self.data = data
def getData(self):
return self.data
def setNext(self,next):
self.next = next
def getNext(self):
return self.next
def hasNext(self):
return self.next!=None
class LinkedList(object):
def __init__(self):
self.length = 0
self.head = None
def listLength(self):
currentNode = self.head
length = 0
while currentNode.hasNext:
length = length + 1
currentNode = currentNode.getNext()
return length
"""
Methods to Insert nodes in a Linked List:
# insertNode: Use this method to simply insert a node to the Linked List
# insertHead: Use this method to insert a node at the head of the Linked List
# insertTail: Use this method to insert a node at the tail of the Linked List
# insertAtPosition: Use this method to insert a node at a particular position of the Linked List
"""
def insertNode(self,node):
if self.length == 0:
self.insertHead(node)
else:
self.insertTail(node)
def insertHead(self, data):
nodeToBeInserted = Node()
nodeToBeInserted.setData(data)
if self.length == 0:
self.head = nodeToBeInserted
else:
nodeToBeInserted.setNext(self.head)
self.head = nodeToBeInserted
self.length = self.length + 1
def insertTail(self,data):
nodeToBeInserted = Node()
nodeToBeInserted.setData(data)
currentNode = self.head
while currentNode.getNext() != None:
currentNode = currentNode.getNext()
currentNode.setNext(nodeToBeInserted)
self.length = self.length + 1
def insertAtPosition(self,data, position):
if position > self.length or position < 0:
print("Invalid position!, The size of the Linked List is:%s"%self.length)
else:
if position ==0:
self.insertHead(data)
else:
nodeToBeInserted = Node()
nodeToBeInserted.setData(data)
currentNode = self.head
count = 0
while count < position - 1:
currentNode = currentNode.getNext()
count = count + 1
nodeToBeInserted.setNext(currentNode.getNext())
currentNode.setNext(nodeToBeInserted)
self.length = self.length+1
ll = LinkedList()
ll.insertNode(1)
ll.insertNode(2)
ll.insertNode(3)
</code></pre>
<p>The error I am seeing is:</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/XPS 13/PycharmProjects/DataStructures/LinkedList/Implementation/SinglyLinkedList.py", line 154, in <module>
ll.insertNode(2)
File "C:/Users/XPS 13/PycharmProjects/DataStructures/LinkedList/Implementation/SinglyLinkedList.py", line 92, in insertNode
self.insertTail(node)
File "C:/Users/XPS 13/PycharmProjects/DataStructures/LinkedList/Implementation/SinglyLinkedList.py", line 121, in insertTail
while currentNode.getNext() != None:
TypeError: getNext() missing 1 required positional argument: 'self'
Process finished with exit code 1
</code></pre>
<p>If someone can please explain me the reason for this error it will be appreciated.</p>
<p>Thank you.</p>
| 0 |
2016-09-21T18:38:20Z
| 39,624,553 |
<p>You have made mistakes in your code:</p>
<p>In <code>Node</code> class:</p>
<pre><code>self.next = Node
</code></pre>
<p>Why do you make this statement? Assign class itself to next is unreasonable. it should be:</p>
<pre><code>self.next = None
</code></pre>
<p>Another thing, I would like to suggest is you'd better design a good <code>__init__</code> function for each class. Think the <code>__init__</code> function in a class as a constructor for the class.</p>
<p>In your <code>__init__</code> function, no arguments are provided, which means when you instantiate the class, you cannot pass any data to it. In practice, we always need to provide some data to instantiate a class. Let's take the <code>Node</code> class for example, when we use it, we often already know the data this node should store, and the <code>next</code> node information, may or may not be known. So the better way to define its <code>__init__</code> function is:</p>
<pre><code>def Node():
def __init__(self, data, next=None):
self.data = data
self.next = next
</code></pre>
<p>Next time, you make new instance with <code>data</code> property known:</p>
<pre><code>node = Node(data=1)
</code></pre>
<p>If you also know the <code>next</code> property:</p>
<pre><code>node = Node(data=1, next=next)
</code></pre>
<p>This make you more convenient, without need to call <code>setX</code> function.</p>
| 0 |
2016-09-21T19:02:15Z
|
[
"python",
"linked-list",
"typeerror"
] |
How to kill celery worker process for process restart
| 39,624,223 |
<p>I have a celery worker process that creates one socket to an external server in <code>celery.signals.worker_process_init</code>. If the connection can't be established and an exception is raised the celery worker fails to start, which is the intended behaviour.</p>
<p>That socket class also sends occasional heartbeat packets using a <code>threading.Timer</code>. Unfortunately, because the Timer thread has no special exception handling, my worker doesn't quit if something happens to the connection.</p>
<p>I started catching exceptions from my socket read and write operations and have tried a bunch of things to gracefully stop the current worker process:</p>
<pre><code>sys.exit(1) # Doesn't kill the worker process (because it's running in a thread?)
</code></pre>
<p>next attempt, I saw it mentioned somewhere in <code>celery/billiard</code> issues: </p>
<pre><code>raise SystemExit("Socket error") # Same, I guess
</code></pre>
<p>this works:</p>
<pre><code>os.kill(os.getpid(), signal.SIGHUP)
</code></pre>
<p>BUT the celery worker supervisor process goes into a fast spin creating celery worker processes that exit immediately, instead of giving up and dying after a few attempts.</p>
<p>Is there a nicer way to signal the death of a celery worker process from outside a celery task?</p>
| 3 |
2016-09-21T18:41:20Z
| 39,688,990 |
<p>I had similar problem. I ended up creating a separate script to manage workers. </p>
<p>Create an infinite while loop, sleep for required time and then create/kill worker process.</p>
<pre><code>while True:
time.sleep(5)
# create workers if possible
# kill stale workers if not required.
</code></pre>
| 0 |
2016-09-25T16:08:30Z
|
[
"python",
"multithreading",
"sockets",
"celery",
"python-multiprocessing"
] |
Authentication Popup using Selenium Webdriver Python
| 39,624,225 |
<p>I'm able to send keys to handle the authentication popup of a site using Selenium and win32com.client. It is working fine when I run the code manually (running a Jupyter Notebook).</p>
<p>The error occurs when I convert .ipynb to .py and schedule it to run automatically using Windows Task Scheduler. It get stuck into the authentication popup window.</p>
<p>I have tried the options below:</p>
<p>1.) This works fine in notebook</p>
<pre><code>shell = comclt.Dispatch("WScript.Shell")
driver = webdriver.Chrome(chrome_path)
driver.maximize_window()
driver.get(url)
shell.SendKeys("username", + "{TAB}" + "password" + "{TAB}" + "{ENTER}")
</code></pre>
<p>2.) Just trying some alternatives and its working in notebook </p>
<pre><code>shell = comclt.Dispatch("WScript.Shell")
driver = webdriver.Chrome(chrome_path)
driver.maximize_window()
driver.get(url)
try:
alert = driver.switch_to_alert().accept()
shell.SendKeys("username", + "{TAB}" + "password" + "{TAB}" + "{ENTER}")
except NoAlertPresentException:
shell.SendKeys("username", + "{TAB}" + "password" + "{TAB}" + "{ENTER}")
</code></pre>
<p>Is there a better approach on how to run this code (.py) automatically using Task Scheduler? </p>
| 0 |
2016-09-21T18:41:25Z
| 39,667,751 |
<p>Works well with .ipynb and py while in active desktop session
updates:
added codes to minimize the Console Window Class</p>
<pre><code>app = Application().Connect(title ='path' + 'python.exe', class_name = 'ConsoleWindowClass')
cwc = app.ConsoleWindowClass
cwc.Minimize()
app = Application().Connect(title ='page', class_name = 'Chrome_WidgetWin_1')
widget = app.Chrome_WidgetWin_1
widget.Minimize()
time.sleep(2) # will allow the some time before executing other task
widget.Maximize()
widget.SetFocus()
time.sleep(3)
shell.SendKeys("username", + "{TAB}" + "password" + "{TAB}" + "{ENTER}")
</code></pre>
<p>It won't work when the computer is locked. Work around is to send a pyautogui for mouse events.</p>
<p>Again, it might not be the best solution but this is my temporary solution until your best approach :)</p>
| 0 |
2016-09-23T18:55:43Z
|
[
"python",
"selenium-webdriver",
"scheduled-tasks",
"win32com",
"pywinauto"
] |
Python: Json Data into Class Instance varaibles
| 39,624,240 |
<p>I am trying to create a class called Movie. I have declared the instance variables. I am calling the OMDB API and I would like to store assign the variables to that. But that doesn't seem to be working. Even when I print json_Data, it doesn't print anything. Can anyone point me in the right direction. I know I can store the data into a dictionary. But how would it be stored in a class. I am a newbiew that is still learning python. </p>
<pre><code>class Movie(object):
""" Class provides a structure to store Movie information """
def __init__(self, imdb_id, title = None, release_year = None, rating = None, run_time = None, genre = None, director = None, actors = None, plot = None, awards = None, poster_image = None, imdb_votes = None, youtube_trailer = None):
self.imdb_id = imdb_id
self.title = title
self.release_year = release_year
self.rating = rating
self.run_time = run_time
self.genre = genre
self.director = director
self.actors = actors
self.plot = plot
self.awards = awards
self.poster_image = poster_image
self.imdb_votes = imdb_votes
self.youtube_trailer = youtube_trailer
def get_api_data(self):
"""
Method retreves and parses information for each movie based on imdb_id
"""
#URL for OMDBI
url = "http://www.omdbapi.com/?i="+self.imdb_id+"&plot=full&r=json&v=1"
try:
response = urllib.urlopen(url)
except URLERROR as e:
if hasattr(e, 'reason'):
print ("Unable to reach a server.")
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print "Server is unable to fulfill the request."
print 'Error Code: ', e.code
else:
json_data = json.loads(response.read())
self.imdb_id = json_data["imdbID"].encode("utf8","ignore")
self.title = json_data["Title"].encode("utf8","ignore")
self.release_year = int(json_data["Released"].split("")[-1])
self.rating = json_data["imdbRating"].encode("utf8", "ignore")
self.run_time = json_data["Runtime"].encode("utf8", "ignore")
self.genre = json_data["Rated"].encode("utf8", "ignore")
self.director = json_data["Director"].encode("utf8", "ignore")
self.actors = json_data["Actors"].encode("utf8", "ignore")
self.plot = json_data["Plot"].encode("utf8", "ignore")
self.awards = json_data["Awards"].encode("utf8", "ignore")
self.poster_image = json_data["Poster"].encode("utf8", "ignore")
self.imdb_votes = json_data["imdbVotes"].encode("utf8", "ignore")
</code></pre>
<p>Is it recommended to store the data returned as a dictionary as opposed to creating a class for each movie type? </p>
| 0 |
2016-09-21T18:42:04Z
| 39,624,320 |
<pre><code>class Movie(object):
""" Class provides a structure to store Movie information """
def __init__(self, imdb_id, title = None, release_year = None, rating = None, run_time = None, genre = None, director = None, actors = None, plot = None, awards = None, poster_image = None, imdb_votes = None, youtube_trailer = None):
self.imdb_id = imdb_id
self.title = title
self.release_year = release_year
self.rating = rating
self.run_time = run_time
self.genre = genre
self.director = director
self.actors = actors
self.plot = plot
self.awards = awards
self.poster_image = poster_image
self.imdb_votes = imdb_votes
self.youtube_trailer = youtube_trailer
def get_api_data(self):
"""
Method retreves and parses information for each movie based on imdb_id
"""
#URL for OMDBI
url = "http://www.omdbapi.com/?i="+self.imdb_id+"&plot=full&r=json&v=1"
try:
response = urllib.urlopen(url)
except URLERROR as e:
if hasattr(e, 'reason'):
print ("Unable to reach a server.")
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print "Server is unable to fulfill the request."
print 'Error Code: ', e.code
# if urllib.urlopen() succeeds, the code jumps to here
json_data = json.loads(response.read())
self.imdb_id = json_data["imdbID"].encode("utf8","ignore")
self.title = json_data["Title"].encode("utf8","ignore")
self.release_year = int(json_data["Released"].split("")[-1])
self.rating = json_data["imdbRating"].encode("utf8", "ignore")
self.run_time = json_data["Runtime"].encode("utf8", "ignore")
self.genre = json_data["Rated"].encode("utf8", "ignore")
self.director = json_data["Director"].encode("utf8", "ignore")
self.actors = json_data["Actors"].encode("utf8", "ignore")
self.plot = json_data["Plot"].encode("utf8", "ignore")
self.awards = json_data["Awards"].encode("utf8", "ignore")
self.poster_image = json_data["Poster"].encode("utf8", "ignore")
self.imdb_votes = json_data["imdbVotes"].encode("utf8", "ignore")
</code></pre>
| 1 |
2016-09-21T18:47:15Z
|
[
"python",
"python-2.7"
] |
Loop over Colums in Pandas Dataframe to create multiple plots with one x variable and mulitple y (colum values)
| 39,624,252 |
<p>I have a single pandas dataframe and want to plot colums 2 though n against colum 1. I would like to create a for loop to do this. I am using matplotlib.</p>
| -2 |
2016-09-21T18:42:55Z
| 39,625,783 |
<p>The <a href="https://stanford.edu/~mwaskom/software/seaborn/index.html" rel="nofollow">Seaborn</a> visualization library is based on matplotlib and provides out of the box plot for statistical analysis. I think the <code>pairplot</code> function is what your are looking for. See the documentation <a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.pairplot.html#seaborn.pairplot" rel="nofollow">here</a>. </p>
| 0 |
2016-09-21T20:13:41Z
|
[
"python",
"pandas",
"matplotlib"
] |
Passing bash variable to python command within a shell script
| 39,624,434 |
<p>Needing to extract two variables per line from a JSON file and use each of these 2 variables in separate follow up commands.</p>
<p>My script is so far:</p>
<pre><code>#!/bin/bash
VCTRL_OUT='/tmp/workingfile.json'
old_IFS=$IFS # save the field separator
IFS=$'\n' # new field separator, the end of line
for line in $(cat $VCTRL_OUT)
do
python -c 'import json,sys;obj=json.load($line);print obj["ip_range"]'
done
</code></pre>
<p>The second to last line is wrong and need to know how to do this.</p>
<p>The following works:</p>
<pre><code>cat /tmp/workingfile.json | head -n +1 | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["ip_range"]';
</code></pre>
<p>But not sure how to do the same in the bash script for loop.</p>
| 0 |
2016-09-21T18:54:58Z
| 39,626,537 |
<p>Python wouldn't be my first choice for this kind of one-liner, but you might try</p>
<pre><code>#!/bin/bash
VCTRL_OUT='/tmp/workingfile.json'
parse_json () {
python -c $'import json,fileinput,operator\nfor line in fileinput.input(): print "%s %s"%operator.itemgetter("ip_range","description")(json.loads(line))' "$1"
}
while IFS= read -r ip_range description; do
# do your thing with ip_range
done < <(parse_json "$VCTRL_OUT")
</code></pre>
<p>One alternative is to replace the Python bit with <code>jq</code>:</p>
<pre><code>while IFS= read -r ip_range description; do
# ...
done < <( jq -rRc 'fromjson | .ip_range+" "+.description' "$VCTRL_OUT")
</code></pre>
<p>Another alternative is to replace the entire <code>bash</code> script with Python, although that may be easier said than done, depending on what the <code>bash</code> script is actually doing.</p>
| 3 |
2016-09-21T21:02:04Z
|
[
"python",
"json",
"bash"
] |
How to do power curve fitting in Python?
| 39,624,462 |
<p>There is a question about exponential curve fitting, but I didn't find any materials on how to create a power curve fitting, like this:</p>
<pre><code>y = a*x^b
</code></pre>
<p>There is a way to do this in Excel, but is it possible in Python?</p>
| 0 |
2016-09-21T18:57:17Z
| 39,624,517 |
<p>If you do an easy transformation you can apply the usual least squares regression.</p>
<p>Instead of this equation: </p>
<pre><code>y = a*x^b
</code></pre>
<p>Take the natural log of both sides:</p>
<pre><code>ln(y) = ln(a*x^b) = ln(a) + ln(x^b) = ln(a) + b*ln(x)
</code></pre>
<p>This is a linear equation in <code>[ln(x), ln(y)]</code> with slope <code>b</code> and intercept <code>ln(a)</code>.</p>
<p>You can use out of the box least squares fitting on the transformed data.</p>
| 1 |
2016-09-21T19:00:15Z
|
[
"python",
"scikit-learn",
"regression"
] |
How to do power curve fitting in Python?
| 39,624,462 |
<p>There is a question about exponential curve fitting, but I didn't find any materials on how to create a power curve fitting, like this:</p>
<pre><code>y = a*x^b
</code></pre>
<p>There is a way to do this in Excel, but is it possible in Python?</p>
| 0 |
2016-09-21T18:57:17Z
| 39,624,545 |
<p>Just take logarithms:</p>
<pre><code>y = ax^b
log(y) = log(a) + b*log(x)
</code></pre>
<p>and use a linear fit for the pair <code>log(x)</code> and <code>log(y)</code>. It will result on a line with slope <code>b</code> and intercept <code>log(a)</code>, just take exponential to obtain the parameter <code>a</code>.</p>
| 1 |
2016-09-21T19:01:50Z
|
[
"python",
"scikit-learn",
"regression"
] |
Python Selenium webdriver working with iframes
| 39,624,736 |
<p>Good day. Im trying to learn how to use the Selenium IDE on firefox together with Python by exporting whatever test i did to Python 2.7.</p>
<p>During my test i ran into a few problems, one of them is that it isn't recognizing 2 text fields, which are inside iframes. Ive found some other answers right here on stack overflow but Im not really sure on how to apply them on my code. This is what i got from exporting directly from the Selenium IDE on firefox. I`m also completely new to python and programming in general, so any suggestion would also be welcome.</p>
<p>This is what i have right now:</p>
<pre><code># -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re
class StiMPythonWebdriver(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "https://webpage.com/"
self.verificationErrors = []
self.accept_next_alert = True
def test_sti_m_python_webdriver(self):
driver = self.driver
driver.find_element_by_id("SEARCHS").clear()
driver.find_element_by_id("SEARCHS").send_keys("403627") **It inserts a code of a form**
driver.find_element_by_id("splitbutton1-button").click()
# ERROR: Caught exception [ERROR: Unsupported command [waitForPopUp | details403627 | 100000]]
# ERROR: Caught exception [ERROR: Unsupported command [selectWindow | name=details403627 | ]] **It waits a little for the pop up window to open so it can continue the test**
driver.find_element_by_id("editButton_textSpan").click()
Select(driver.find_element_by_id("status")).select_by_visible_text("Option 1")
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | id=descrpt_ifr | ]]
# ERROR: Caught exception [ERROR: Unsupported command [selectFrame | id=tinymce | ]] **Right here at this part it is supposed to select the <p> inside the Iframe and type the following sentence "Canceled"**
driver.find_element_by_id("descrpt_ifr").clear()
driver.find_element_by_id("descrpt_ifr").send_keys("Canceled")
# ERROR: Caught exception [ERROR: Unsupported command [selectWindow | name=details403627 | ]]
driver.find_element_by_id("goButton_textSpan").click()**then it selects a button that exits the pop up**
</code></pre>
| 0 |
2016-09-21T19:11:34Z
| 39,630,177 |
<p>If you want to switch to iframe</p>
<pre><code>driver.switch_to_frame(driver.find_element_by_xpath("//iframe[@id='tinymce ']"))
</code></pre>
<p>If you want to switch to window -1 seems default active window</p>
<pre><code>driver.switch_to_window(driver.window_handles[-1])
</code></pre>
<p>Don't forgot to switch back when you complete .</p>
| 0 |
2016-09-22T04:17:37Z
|
[
"python",
"selenium",
"iframe"
] |
Iterate only one dict list from multi list dict
| 39,624,778 |
<p>I have a dict of lists like so:</p>
<pre><code>edu_options = { 'Completed Graduate School' : ['medical','litigation','specialist'...],
'Completed College' : ['linguistic','lpn','liberal','chicano'... ],
'Attended College' : ['general','inprogress','courseworktowards','continu'...],
</code></pre>
<p>My original code without an attempt at hierarchical matching:</p>
<pre><code>for edu_level in edu_options:
for option in edu_options[edu_level]
if option in cleaned_string:
user = edu_level
return user
else: continue
</code></pre>
<p>I'm comparing a string to these lists and returning the key. I want to do it in a hierarchical way.</p>
<pre><code> for edu_level in edu_options:
for option in edu_options[edu_level]:
if cleaned_string in edu_options["Completed Graduate School"]:
user = "Completed Graduate School"
return user
elif cleaned_string in edu_options["Completed College"]:
user = "Completed College"
return user
elif option in cleaned_string:
user = edu_level
return user
</code></pre>
<p>These if statements work for the majority of comparison str but don't pick up a few cases. For the first and second if statement, I only want to compare it to the respective list such as "Completed Graduate School". Is there a way to iterate through only that list without using another for loop? Something like </p>
<pre><code>Ex: string = Bachelor of Arts: Communication and Civil Service
cleaned_string = bachelorofartscommunicationandcivilservice
option = iterating through each item(str) of lists in edu_option
</code></pre>
<p>I want the graduate and college lists to be run through first because they are smaller and more specific. The error I'm trying to correct is another larger list in edu_options contains sub str that matches to cleaned_string incorrectly.</p>
| 0 |
2016-09-21T19:13:58Z
| 39,624,873 |
<p>How about this:</p>
<pre><code>for key, val_list in edu_options.items():
if key == "Completed Graduate School":
if cleaned_string in val_list:
#do something
#Similarly for remaining key types
</code></pre>
<p>This way, you are restricting the checks specifically to the key types. </p>
| 1 |
2016-09-21T19:18:55Z
|
[
"python",
"list",
"dictionary"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.