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 |
---|---|---|---|---|---|---|---|---|---|
Pandas DataFrame plotting - Tick labels | 39,697,683 | <p>this is a follow-up question on a piece of code I have <a href="http://stackoverflow.com/questions/39561248/python-plotting-pandas-pivot-table-from-long-data">posted previously here</a>. </p>
<p>I am plotting a Dataframe object using <code>data_CO2_PBPROD.T.plot(marker='o', color='k', alpha=0.3, lw=2)</code> but I get on the x-axis double labels, as you can see in this picture
<a href="http://i.stack.imgur.com/eKVAx.png" rel="nofollow"><img src="http://i.stack.imgur.com/eKVAx.png" alt="enter image description here"></a></p>
<p>I tried to work on the set_major_formatter property of matplotlib.pyplot.axes() but then I get a separate graph with the correct tick labels - but no data displayed - along with the previous graph, unchanged.</p>
| 0 | 2016-09-26T08:08:55Z | 39,697,870 | <p>You can use the argument <strong>xticks</strong> to set the values of your axis as explained in the documentation <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html" rel="nofollow">here</a>:</p>
<pre><code>xticks = [date for _ ,date in data_CO2_PBPROD.Column1]
</code></pre>
<p>Where <strong>Column1</strong> is the column of your DataFrame containing the tuples (Values, Year)</p>
<p>Then put the <strong>xticks</strong> as a parameter to your plot function :</p>
<pre><code>data_CO2_PBPROD.T.plot(marker='o', xticks=xticks, color='k', alpha=0.3, lw=2)
</code></pre>
| 0 | 2016-09-26T08:22:20Z | [
"python",
"pandas",
"matplotlib",
"plot"
]
|
django admin list_display - returning multiple column values with single callable (django 1.9, python=2.7.x) | 39,697,892 | <p>So my Django code for <code>admin.py</code> looks something like this:</p>
<pre><code>class MyUserAdmin(UserAdmin):
form = MyUseChangeForm
list_display = ('email', 'is_admin', 'is_superuser',
'total_tasks', 'total_tests')
list_filter = ('is_admin', 'is_superuser')
ordering = ('email',)
def total_tests(self, obj):
others = OtherObject.objects.filter(user=obj)
total = 0
correct = 0
for other in others:
# ... etc
return # ...
total_tests.short_description = "Tests Taken"
def total_tasks(self, obj):
return OtherObject.objects.filter(user=obj).count()
total_tasks.short_description = "Tasks Done"
</code></pre>
<p>However, realizing that every callable I make (<code>total_tasks</code>, <code>total_tests</code>) will make this page load suuuuuuper slow when I have more database entries - is there a way to share computation? Maybe cache so that every callable doesn't have to query ALL the items from different tables over and over again?</p>
| 0 | 2016-09-26T08:24:14Z | 39,698,010 | <p>First of all tune tune your code.</p>
<ol>
<li><code>total_tasks</code> - should be <code>OtherObject.objects.filter(user_id=obj.pk).count()</code> - it will boost you a bit.</li>
<li>You've hidden the body of for loop in <code>total_tests</code>. I am afraid that you refer to some objects connected with <code>OtherObject</code> model. Without <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#select-related" rel="nofollow">select_related</a> you can almost DDOS your database and make the view extremaly slow.</li>
</ol>
| 1 | 2016-09-26T08:30:43Z | [
"python",
"django"
]
|
django admin list_display - returning multiple column values with single callable (django 1.9, python=2.7.x) | 39,697,892 | <p>So my Django code for <code>admin.py</code> looks something like this:</p>
<pre><code>class MyUserAdmin(UserAdmin):
form = MyUseChangeForm
list_display = ('email', 'is_admin', 'is_superuser',
'total_tasks', 'total_tests')
list_filter = ('is_admin', 'is_superuser')
ordering = ('email',)
def total_tests(self, obj):
others = OtherObject.objects.filter(user=obj)
total = 0
correct = 0
for other in others:
# ... etc
return # ...
total_tests.short_description = "Tests Taken"
def total_tasks(self, obj):
return OtherObject.objects.filter(user=obj).count()
total_tasks.short_description = "Tasks Done"
</code></pre>
<p>However, realizing that every callable I make (<code>total_tasks</code>, <code>total_tests</code>) will make this page load suuuuuuper slow when I have more database entries - is there a way to share computation? Maybe cache so that every callable doesn't have to query ALL the items from different tables over and over again?</p>
| 0 | 2016-09-26T08:24:14Z | 39,698,396 | <p>Override the <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_queryset" rel="nofollow"><code>get_queryset</code></a> method for your <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#prefetch-related" rel="nofollow"><code>prefetch_related</code></a> to fetch the related objects. You can then modify your methods to use the prefetched <code>self.otherobject_set.all()</code> instead of querying <code>OtherObject.objects.filter(user=obj)</code> once for each method for each row in the queryset.</p>
<pre><code>class MyUserAdmin(UserAdmin):
def get_queryset(self, request):
qs = super(MyUserAdmin, self).get_queryset(request)
qs = qs.prefetch_related('otherobject')
return qs
def total_tests(self, obj):
others = self.otherobject_set.all()
...
def total_tasks(self, obj):
return len(self.otherobject_set.all())
</code></pre>
| 1 | 2016-09-26T08:51:07Z | [
"python",
"django"
]
|
python matplotlib bars don't change when running script multiple times | 39,697,937 | <p>I've been writing a post-processing script for a model we have at work, which worked fine. Recently I re-structured the script for clarity and re-usability.</p>
<p>General background: we have pickle-stored arrays as output from a model, for each "main parameter" <code>(N:nitrogen, P:phosporus)</code>. There are a bunch of pickled arrays per <code>subparameter/year/month</code> in a folder structure. Eg: <code>N/RNO3_2010_03</code>, is the result for March 2010 of the subparameter <code>RNO3</code> of the main parameter N.</p>
<p>What I do in the script below is give some parameters to a <code>def()</code> to run over the folder with the arrays, gather the information and plot a chart (optional write a survey of the data to CSV or make some PNG saves for visual purposes).</p>
<p>When I run this script for one main parameter (only <code>N</code> set to True, or only <code>P</code> set to True, all goes well). When I run this for both parameters at once (<code>N</code> and <code>P</code> both <code>True</code>), the plot for the second parameters seems to be the same as the plot for the first parameter. I looked up what could cause it, but can't find a similar problem.</p>
<p>The last thing I did was deleting the <code>p0</code>, <code>p1..</code>. parameters since they seem to be the ones that don't update (or keep the last input stored when starting a new loop).</p>
<p>Thanks for your advice!</p>
<p>Example of a correct output for N (sorry I can only upload 1 image).</p>
<pre><code>import numpy as np
import csv
import pickle
import matplotlib.pyplot as plt
import matplotlib
# Fill in settings below ! --------------------------------------------------------------------
path = "Z:/Modellering/2_ArcNemo/OutputArcNEMO/Rob/Nete20002012_20160802145344/"
bekken = "Nete"
N = True #set this True if you want to proces data for N, else False
P = True #set this True if you want to proces data for P, else False
RES = True #set this True if you want to proces data for residue, else False
data = False #set this True if you want to write processed data to a file (csv), else False
figure = True #set this True if you want to visualise processed data in a figure (png)
save_png= False #set this True if you want to save a png of every array of RES, else False
years = ["2010","2011","2012"] #copy-paste the wanted years from below into this list
#"2000","2001","2002","2003","2004","2005","2006","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016","2017","2018","2019","2020","2021"
#Fill in the above settings ! ------------------------------------------------------------------
parametersN = [N,"N",["DrNO3","RNO3","RNorg"],500000]
parametersP = [P,"P",["DroP","RoP","RPorg","RPsor"],5000]
#parametersRES = ["NS30","NS60","NS90"]
months = ["01","02","03","04","05","06","07","08","09","10","11","12"]
save = "overzicht.csv"
def process(parameters):
dates = []
max_par = 0
S = 0
par0_dat = []
par1_dat = []
par2_dat = []
par3_dat = []
result = []
if parameters[0]:
saved = path + str(parameters[1]) + save
parameters_list = parameters[2]
j=0
for par in parameters_list:
for y in years:
for m in months:
to_load = path+str(parameters[1])+"/"+par+"_"+y+"_"+m
array = pickle.load(open(str(to_load),"rb"))
sum_par = np.sum(pickle.load(open(str(to_load),"rb")))/1000
if save_png:
save_img = path+par+"_"+y+"_"+m+".png"
matplotlib.image.imsave(save_img, array)
if figure==True:
dates.append(str(m)+"/"+str(y))
if j==0:
par0_dat.append(sum_par)
if j==1:
par1_dat.append(sum_par)
if j==2:
par2_dat.append(sum_par)
if j==3:
par3_dat.append(sum_par)
if data==True:
result.append(str(par))
d = str(m) + "_" + str(y)
result.append(d)
result.append(str(sum_par))
with open(saved, 'ab') as f:
w = csv.writer(f, delimiter = ",")
w.writerow(result)
result = []
j+=1
if figure==True:
S = len(dates)/len(parameters[2])
if parameters[1]!="P":
par3_dat = [0]*S
for i in range(0, S):
if (par0_dat[i] + par1_dat[i] + par2_dat[i] + par3_dat[i]) > max_par:
max_par = par0_dat[i] + par1_dat[i] + par2_dat[i] + par3_dat[i]
ind = np.arange(S)
width = 0.6
p1 = plt.bar(ind, par0_dat, width, color='r')
p2 = plt.bar(ind, par1_dat, width, color='y',bottom=par0_dat)
p3 = plt.bar(ind, par2_dat, width, color='b',bottom=[par0_dat[k]+par1_dat[k] for k in range(len(par0_dat))])
p4 = plt.bar(ind, par3_dat, width, color='k',bottom=[par0_dat[l]+par1_dat[l]+par2_dat[l] for l in range(len(par0_dat))])
if parameters[1]!="P":
plt.legend((p1[0], p2[0], p3[0]), (parameters[2][0], parameters[2][1] , parameters[2][2]))
else:
plt.legend((p1[0], p2[0], p3[0], p4[0]), (parameters[2][0], parameters[2][1] , parameters[2][2], parameters[2][3]))
title = parameters[1] + "t netto-emissies " + bekken + " " + str(years[0]) +" - " + str(years[len(years)-1])
plt.title(title)
plt.ylabel("kg " + parameters[1] + "/mnd")
plt.xticks(ind + width/2., dates)
plt.xticks(rotation=90, fontsize=7)
plt.yticks(np.arange(0, max_par, parameters[3]))
plt.tight_layout()
plt.savefig(path+ str(parameters[1]) +".png")
print str(p1)
print p1
del p1
del p2
del p3
del p4
parameters = []
process(parametersN)
process(parametersP)
print "Done"
</code></pre>
| -1 | 2016-09-26T08:26:37Z | 39,698,730 | <p>I guess the only thing you need is a new figure... so try to place <code>plt.figure()</code> right after <code>if figure == True:</code> like this:</p>
<pre><code> ...
j+=1
if figure==True:
plt.figure()
S = len(dates)/len(parameters[2])
...
</code></pre>
<p>and see if it works.<br>
Or do you want to have both P and N results in one figure? Then you need to work with subplots but you'll have to change a little more.</p>
| 0 | 2016-09-26T09:06:52Z | [
"python",
"matplotlib"
]
|
How to split comma delimited values into multiple rows using Python | 39,697,974 | <p>I'm using Python and SQLite to manipulate a database. </p>
<p>I have an SQLite Table <code>Movies</code> that looks like this:</p>
<pre><code>| ID | Country
+----------------+-------------
| 1 | USA, Germany, Mexico
| 2 | Brazil, Canada
| 3 | Peru
</code></pre>
<p>I would like to split the comma delimited values in <code>Country</code> and insert them into <strong>another table</strong> <code>Countries</code> so that <code>Countries</code> table looks like this </p>
<pre><code>| ID | Country
+----------------+-------------
| 1 | USA
| 1 | Germany
| 1 | Mexico
| 2 | Brazil
| 2 | Canada
| 3 | Peru
</code></pre>
<p>How do I do split the values from <code>Country</code> column in <code>Movies</code> table and insert them into <code>Country</code> column in <code>Countries</code> table?</p>
<p>According to <a href="http://stackoverflow.com/questions/12744155/sqlite-create-new-columns-from-column-containing">this post</a>, I can't accomplish this task using pure SQLite. How would I go about it using Python?</p>
| 0 | 2016-09-26T08:28:42Z | 39,698,740 | <p>Using Python,</p>
<pre><code>cursor.execute("""Select * from Movies""")
all_data = cursor.fetchall()
cursor.execute("""CREATE TABLE IF NOT EXISTS Countries
(ID TEXT,
Country TEXT)""")
for single_data in all_data:
countries = single_data[1].split()
for single_country in countries:
cursor.execute("""INSERT INTO Countries VALUES(%s,"%s")"""%(single_data[0],single_country))
conn.commit()
</code></pre>
| 0 | 2016-09-26T09:07:24Z | [
"python",
"sqlite"
]
|
Decorators on bound methods with access to class and his ancestors | 39,698,045 | <p>When I decorated the bound method in Python class, I need get some info in this decorator from outer class. Is that possible?</p>
<p>For example:</p>
<pre><code>def modifier(func):
import sys
cls_namespace = sys._getframe(1).f_locals
cls_namespace['data'] # dictonary has no key 'data'
...
return func
class Parent:
data = "Hi!"
class Child(Parent):
@modifier
def method(self):
pass
</code></pre>
<p>the <code>cls_namespace</code> is just incomplete namespace of current class without <code>data</code> field that I need to get.</p>
<p>Is there ways to get it in decorator?</p>
| 2 | 2016-09-26T08:32:15Z | 39,698,115 | <p>Function decoration takes place when the class body is being executed, nothing is known about the class itself or its base classes at this time. This means that <code>modifier</code> decorates the <em>unbound function object</em> and only when <code>func</code> is actually called on an instance will it be bound.</p>
<p>You could return a wrapper function to replace the decorated function, it'll be bound instead and you'll have access to <code>self</code>:</p>
<pre><code>from functools import wraps
def modifier(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
# self is an instance of the class
self.data
return func(self, *args, **kwargs)
return wrapper
</code></pre>
<p>The wrapper will then be called each time <code>method</code> is called on an instance.</p>
<p>If you must have access to the <em>base classes</em> at class creation time, you'll have to wait until the <code>class Child</code> statement has <em>completed execution</em>. Until Python 3.6, that's only possible from a class decorator or metaclass; each is called after the class body is created and you'll have access to (at the least) the base classes.</p>
<p>Using a class decorator, for example:</p>
<pre><code>def modifier(cls):
# cls is the newly created class object, including class attributes
cls.data
return cls
@modifier
class Child(Parent):
def method(self):
pass
</code></pre>
<p>Note the location of the decorator now.</p>
<p>Python 3.6 adds an <a href="https://docs.python.org/3.6/whatsnew/3.6.html#pep-487-simpler-customization-of-class-creation" rel="nofollow"><code>__init_subclass__</code> method</a> that could also give you that access; the (class) method is called each time a subclass is created of the current class:</p>
<pre><code>class Parent:
def __init_subclass__(cls, **kwargs):
# cls is a subclass of Parent
super().__init_subclass__(**kwargs)
cls.data
data = "Hi!"
class Child(Parent):
def method(self):
pass
</code></pre>
| 3 | 2016-09-26T08:35:10Z | [
"python",
"class",
"reflection",
"decorator",
"python-decorators"
]
|
Decorators on bound methods with access to class and his ancestors | 39,698,045 | <p>When I decorated the bound method in Python class, I need get some info in this decorator from outer class. Is that possible?</p>
<p>For example:</p>
<pre><code>def modifier(func):
import sys
cls_namespace = sys._getframe(1).f_locals
cls_namespace['data'] # dictonary has no key 'data'
...
return func
class Parent:
data = "Hi!"
class Child(Parent):
@modifier
def method(self):
pass
</code></pre>
<p>the <code>cls_namespace</code> is just incomplete namespace of current class without <code>data</code> field that I need to get.</p>
<p>Is there ways to get it in decorator?</p>
| 2 | 2016-09-26T08:32:15Z | 39,698,136 | <p>Not that the very first arg passed to your decorator's wrapper will be an objects instance (<code>self</code>). Thanks to it you can access w=everything you need. </p>
<p>See Raphaels response:
<a href="http://stackoverflow.com/questions/11731136/python-class-method-decorator-w-self-arguments">Related issue</a></p>
<pre><code>def wrapped(self, *f_args, **f_kwargs):
</code></pre>
<p>self is the very first argument</p>
| -1 | 2016-09-26T08:36:07Z | [
"python",
"class",
"reflection",
"decorator",
"python-decorators"
]
|
How to mock self in python? | 39,698,094 | <p>Consider the following code. I want to mock <code>self.get_value</code>, which is invoked in <code>foo.verify_client()</code></p>
<pre><code>import unittest
import mock
def mock_get_value(self, value):
return 'client'
class Foo:
def __init__(self):
pass
def get_value(self, value):
return value
def verify_client(self):
client = self.get_value('client')
return client == 'client'
class testFoo(unittest.TestCase):
@mock.patch('self.get_value', side_effect = mock_get_value, autospec = True)
def test_verify_client(self):
foo = Foo()
result = foo.verify_client()
self.assertTrue(result)
if __name__ == "__main__":
unittest.main()
</code></pre>
<p>But I failed, the errors are as follows.</p>
<pre><code>E
======================================================================
ERROR: test_verify_client (__main__.testFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/apps/Python/lib/python2.7/site-packages/mock/mock.py", line 1297, in patched
arg = patching.__enter__()
File "/apps/Python/lib/python2.7/site-packages/mock/mock.py", line 1353, in __enter__
self.target = self.getter()
File "/apps/Python/lib/python2.7/site-packages/mock/mock.py", line 1523, in <lambda>
getter = lambda: _importer(target)
File "/apps/Python/lib/python2.7/site-packages/mock/mock.py", line 1206, in _importer
thing = __import__(import_path)
ImportError: No module named self
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
</code></pre>
<p>How can I do it?</p>
| 1 | 2016-09-26T08:34:15Z | 39,698,604 | <p>I figured it out. Changing this line</p>
<pre><code>@mock.patch('self.get_value', side_effect = mock_get_value, autospec = True)
</code></pre>
<p>to</p>
<pre><code>@mock.patch('test.Foo.get_value', mock_get_value)
</code></pre>
<p>worked.</p>
<p>Especially, the format of the patched function should be <code>module_name + class_name + method_name</code></p>
| 1 | 2016-09-26T09:00:28Z | [
"python",
"unit-testing",
"mocking"
]
|
Python Pandas convert column data type | 39,698,097 | <p>I know a question like this has been asked zillion types, but so far I have not been able to find an answer to this question.</p>
<p>I have joined two .csv files together with Pandas and now I would like to add some more columns to the new joined .csv file and the values calculate based on the already available data.</p>
<p>However, I keep getting this error:</p>
<pre><code>"The truth value of a is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()."
</code></pre>
<p>Now that obviously seems to be a problem with the data type of my column (which is all integers), but I have not found a (working) way to set that column as integers.</p>
<p>Here is my code:</p>
<pre><code>import pandas
def nscap(ns):
if ns <= 13:
x = ns
elif ns > 13:
x = 13
return x
df_1 = pandas.read_csv("a.csv", sep=';', names=["DWD_ID", "NS"], header=0)
df_2 = pandas.read_csv("b.csv", sep=';', names=["VEG", "DWD_ID"], header=0)
df_joined = pandas.merge(df_1, df_2, on="DWD_ID")
df_joined["NS_Cap"] = nscap(df_joined["NS"])
</code></pre>
<p>If i set</p>
<pre><code>df_joined["NS_Cap"] = nscap(20)
</code></pre>
<p>the code works fine</p>
<p>I have tried functions like .astype(int) or .to_numeric() but unless I had the syntax wrong, it didn't work for me.</p>
<p>Thanks in advance!</p>
| 1 | 2016-09-26T08:34:17Z | 39,698,318 | <p>As with @EdChum's comment, you need to use <code>clip(upper=13)</code> or <code>clip_upper(13)</code>. One other option which can help you in the long run with instances like this is to use <code>apply</code> with a lambda function. This is a really nifty all-around method.</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(5,18,size=(5, 4)), columns=list('ABCD'))
nscap = lambda x: min(x, 13)
print df.head()
print '-' * 20
df['NSCAP'] = df['D'].apply(nscap)
print df.head()
</code></pre>
<p>Result:</p>
<p><a href="http://i.stack.imgur.com/HEZAF.png" rel="nofollow"><img src="http://i.stack.imgur.com/HEZAF.png" alt="enter image description here"></a></p>
<p>Take note of the last 2 lines of the second dataframe.</p>
<p>Hope this helps.</p>
| 1 | 2016-09-26T08:46:20Z | [
"python",
"python-2.7",
"csv",
"pandas"
]
|
Python Pandas convert column data type | 39,698,097 | <p>I know a question like this has been asked zillion types, but so far I have not been able to find an answer to this question.</p>
<p>I have joined two .csv files together with Pandas and now I would like to add some more columns to the new joined .csv file and the values calculate based on the already available data.</p>
<p>However, I keep getting this error:</p>
<pre><code>"The truth value of a is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()."
</code></pre>
<p>Now that obviously seems to be a problem with the data type of my column (which is all integers), but I have not found a (working) way to set that column as integers.</p>
<p>Here is my code:</p>
<pre><code>import pandas
def nscap(ns):
if ns <= 13:
x = ns
elif ns > 13:
x = 13
return x
df_1 = pandas.read_csv("a.csv", sep=';', names=["DWD_ID", "NS"], header=0)
df_2 = pandas.read_csv("b.csv", sep=';', names=["VEG", "DWD_ID"], header=0)
df_joined = pandas.merge(df_1, df_2, on="DWD_ID")
df_joined["NS_Cap"] = nscap(df_joined["NS"])
</code></pre>
<p>If i set</p>
<pre><code>df_joined["NS_Cap"] = nscap(20)
</code></pre>
<p>the code works fine</p>
<p>I have tried functions like .astype(int) or .to_numeric() but unless I had the syntax wrong, it didn't work for me.</p>
<p>Thanks in advance!</p>
| 1 | 2016-09-26T08:34:17Z | 39,698,394 | <p>(Your code is missing a parenthesis at the end of <code>nscap(df_joined["NS"]</code>.)</p>
<p>As @EdChum and @TheLaughingMan write, <code>clip_upper</code> is what you want here. This answer just addresses the direct reason for the error you're getting. </p>
<p>In the function</p>
<pre><code>def nscap(ns):
if ns <= 13:
x = ns
elif ns > 13:
x = 13
return x
</code></pre>
<p>effectively, <code>ns <= 13</code> operations on a <code>numpy.ndarray</code>. When you compare such an array to a scalar, broadcasting takes place, and the result is an array where each element indicates whether it was true for it or not. </p>
<p>So</p>
<pre><code>if ns <= 13:
</code></pre>
<p>translates to something like</p>
<pre><code>if numpy.array([True, False, True, True]):
</code></pre>
<p>and it's impossible to understand whether this is true or not. That's the error you're getting: you need to specify whether you mean if <em>all</em> entries are true, if <em>some</em> entry is true, and so on.</p>
| 1 | 2016-09-26T08:50:51Z | [
"python",
"python-2.7",
"csv",
"pandas"
]
|
Python - "Undo" text-wrap | 39,698,100 | <p>I need to take a text and remove the \n character, which I believe I've done. The next task is to remove the hyphen from words where it should not appear but to leave the hyphen in compound words where it should appear. For example, 'encyclo-\npedia to 'encyclopedia' and 'long-\nterm' to 'long-term'. The suggestion is to compare it with an original text.</p>
<pre><code>with open('C:\Users\Paul\Desktop\Comp_Ling_Research_1\BROWN_A1_hypenated.txt', 'rU') as myfile:
data=myfile.read().replace('\n', '')
</code></pre>
<p>I have a general idea of what to do but NLP is quite new to me.</p>
| 1 | 2016-09-26T08:34:29Z | 39,698,262 | <p>A first pass would be to keep a set of valid words around and de-hyphenate if your de-hyphenated word is in the set of valid words. Ubuntu has a list of valid words at /usr/share/dict/american-english. An overly simple version might look like:</p>
<pre><code>valid_words = set(line.strip() for line in open(valid_words_file))
output = []
for word in open(new_file).read().replace('-\n', '').replace('\n', ' ').split():
if '-' in word and word.replace('-', '') in valid_words:
output.append(word.replace('-', ''))
else:
output.append(word)
</code></pre>
<p>You would have to deal with punctuation, capitalization, etc., but that's the idea.</p>
| 0 | 2016-09-26T08:43:30Z | [
"python",
"nlp",
"nltk"
]
|
Python - "Undo" text-wrap | 39,698,100 | <p>I need to take a text and remove the \n character, which I believe I've done. The next task is to remove the hyphen from words where it should not appear but to leave the hyphen in compound words where it should appear. For example, 'encyclo-\npedia to 'encyclopedia' and 'long-\nterm' to 'long-term'. The suggestion is to compare it with an original text.</p>
<pre><code>with open('C:\Users\Paul\Desktop\Comp_Ling_Research_1\BROWN_A1_hypenated.txt', 'rU') as myfile:
data=myfile.read().replace('\n', '')
</code></pre>
<p>I have a general idea of what to do but NLP is quite new to me.</p>
| 1 | 2016-09-26T08:34:29Z | 39,701,733 | <pre><code>import re
with open('C:\Users\Paul\BROWN_A1.txt', 'rU') as truefile:
true_corpus = truefile.read()
true_tokens = true_corpus.split(' ')
with open('C:\Users\Paul\Desktop\Comp_Ling_Research_1\BROWN_A1_hypenated.txt', 'rU') as myfile:
my_corpus = myfile.read()
my_tokens = my_corpus.split(' ')
</code></pre>
| -1 | 2016-09-26T11:33:43Z | [
"python",
"nlp",
"nltk"
]
|
How to create an array of linearly spaced points using numpy? | 39,698,121 | <p>I am trying to create an array of equally spaced points using numpy, as below:</p>
<pre><code>array([ 0. , 0.05263158, 0.10526316, 0.15789474, 0.21052632,
0.26315789, 0.31578947, 0.36842105, 0.42105263, 0.47368421,
0.52631579, 0.57894737, 0.63157895, 0.68421053, 0.73684211,
0.78947368, 0.84210526, 0.89473684, 0.94736842, 1. ])
</code></pre>
<p>This array is 20 points between 0 and 1, all with the same amount of space between them. </p>
<p>Looking at the documentation for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html" rel="nofollow"><code>numpy.array</code></a>, however, I don't see a way to do this by passing in an extra parameter. Is this possible to do as a quick-and-easy one-liner?</p>
| -3 | 2016-09-26T08:35:30Z | 39,698,173 | <p>Use linspace.</p>
<pre><code>np.linspace(0, 1, 20)
</code></pre>
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html</a></p>
| 2 | 2016-09-26T08:37:54Z | [
"python",
"arrays",
"numpy"
]
|
DRF does not work with wagtail | 39,698,187 | <p>I have used DRF for rest api and puput for blog which is built on top of the wagtail. Before using puput, my rest api used to work but not now. For example when i try to open the url <strong><a href="http://localhost:8000/rest-api/ui/tab/" rel="nofollow">http://localhost:8000/rest-api/ui/tab/</a></strong> i get following error </p>
<blockquote>
<p>Page not Found 404 error Raised by: wagtail.wagtailcore.views.serve</p>
</blockquote>
<p><strong>settings.py</strong></p>
<pre><code>DJANGO_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
]
THIRD_PARTY_APPS = [
# rest framework
'rest_framework',
# third party apps
'allauth',
'allauth.account',
'allauth.socialaccount',
'ckeditor',
]
MACHINA_APPS = [
'mptt',
'haystack',
'widget_tweaks',
'django_markdown',
]
LOCAL_APPS = [
'ui_mgmt', # UI manager - tabs, cards etc
'faq', # faq
]
PUPUT_APPS = [
'wagtail.wagtailcore',
'wagtail.wagtailadmin',
'wagtail.wagtaildocs',
'wagtail.wagtailsnippets',
'wagtail.wagtailusers',
'wagtail.wagtailimages',
'wagtail.wagtailembeds',
'wagtail.wagtailsearch',
'wagtail.wagtailsites',
'wagtail.wagtailredirects',
'wagtail.wagtailforms',
'wagtail.contrib.wagtailsitemaps',
'wagtail.contrib.wagtailroutablepage',
'compressor',
'taggit',
'modelcluster',
'puput',
]
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + MACHINA_APPS + LOCAL_APPS + get_machina_apps() + PUPUT_APPS
</code></pre>
<p><strong>urls.py</strong></p>
<pre><code>from ui_mgmt import urls as ui_mgmt_urls
urlpatterns = [
url(r'^accounts/', include(allauth_urls)),
url(r'^admin/', admin.site.urls),
url(r'^forum/', include(board.urls)),
url(r'', include('puput.urls')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^rest-api/', include(ui_mgmt_urls)),
]
</code></pre>
<p><strong>ui_mgmt/urls.py</strong></p>
<pre><code>url(r'^ui/tabs/$', tab_list, name='tab_list'),
</code></pre>
<p><strong>ui_mgmt/views.py</strong></p>
<pre><code>@api_view(['GET','POST'])
def tab_list(request, format=None):
if not request.user.is_authenticated():
return Response(status=status.HTTP_401_UNAUTHORIZED)
user = request.user
if request.method == 'GET':
tabs = Tab.objects.filter(belongsTo=user)
serialized_data = ExtendedTabSerializer(tabs, many=True)
return Response(serialized_data.data)
elif request.method == 'POST':
serialized_data = TabSerializer(data=request.data)
if serialized_data.is_valid():
serialized_data.save(belongsTo=user)
newTab = ExtendedTabSerializer(Tab.objects.get(id=serialized_data.data['id']))
return Response(newTab.data,status=status.HTTP_201_CREATED)
return Response(serialized_data.errors,status=status.HTTP_400_BAD_REQUEST)
</code></pre>
<p>Why my DRF is not working? I get the same error for every rest api call.</p>
| 1 | 2016-09-26T08:38:31Z | 39,698,389 | <p>change the order of your url patterns.. puput should (probablly) the last element</p>
<pre><code>urlpatterns = [
url(r'^accounts/', include(allauth_urls)),
url(r'^admin/', admin.site.urls),
url(r'^forum/', include(board.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^rest-api/', include(ui_mgmt_urls)),
url(r'', include('puput.urls')), # it will match the rest of patterns
]
</code></pre>
<p>Hope this helps</p>
| 3 | 2016-09-26T08:50:27Z | [
"python",
"django",
"python-3.x",
"django-rest-framework",
"wagtail"
]
|
Accessing all function argmuments | 39,698,190 | <p>I have a function with 4 arguments and want to check those 4 arguments for something.
Currently I do it like this:</p>
<pre><code>def function1(arg1, arg2, arg3, arg4):
arg1 = function2(arg1)
arg2 = function2(arg2)
arg3 = function2(arg3)
arg4 = function2(arg4)
def function2(arg):
arg = dosomething(arg)
return arg
</code></pre>
<p>I think this is not really a nice way to do it, so my idea is to do something like this:</p>
<pre><code>def function1(arg1, arg2, arg3, arg4):
for arg in listOfArguments:
arg = function2(arg)
def function2(arg):
arg = checkSomething(arg)
return arg
</code></pre>
<p>Is there a way in Python to get a list of all the arguments passed to <code>function1</code>?</p>
<p>Thanks for your help and ideas.</p>
| 2 | 2016-09-26T08:38:42Z | 39,698,226 | <p>Yes, use <code>*args</code>:</p>
<pre><code>In [1]: def func(*args):
...: print(len(args), args)
...:
In [2]: func(1, 2, 3, 4)
4 (1, 2, 3, 4)
</code></pre>
<p>More information can be found <a href="https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/" rel="nofollow">here.</a></p>
| 3 | 2016-09-26T08:41:11Z | [
"python",
"function",
"python-3.x"
]
|
Accessing all function argmuments | 39,698,190 | <p>I have a function with 4 arguments and want to check those 4 arguments for something.
Currently I do it like this:</p>
<pre><code>def function1(arg1, arg2, arg3, arg4):
arg1 = function2(arg1)
arg2 = function2(arg2)
arg3 = function2(arg3)
arg4 = function2(arg4)
def function2(arg):
arg = dosomething(arg)
return arg
</code></pre>
<p>I think this is not really a nice way to do it, so my idea is to do something like this:</p>
<pre><code>def function1(arg1, arg2, arg3, arg4):
for arg in listOfArguments:
arg = function2(arg)
def function2(arg):
arg = checkSomething(arg)
return arg
</code></pre>
<p>Is there a way in Python to get a list of all the arguments passed to <code>function1</code>?</p>
<p>Thanks for your help and ideas.</p>
| 2 | 2016-09-26T08:38:42Z | 39,698,236 | <p>Since you have a <em>set</em> number of arguments <em>just create an iterable out of them</em>, for example, wrap the argument names in a tuple literal:</p>
<pre><code>for arg in (arg1, arg2, arg3, arg4):
# do stuff
</code></pre>
<p>If you don't mind your function being capable of being called with more args just use <a href="https://docs.python.org/3/reference/compound_stmts.html#function-definitions" rel="nofollow"><code>*args</code> syntax</a>:</p>
<pre><code>def function1(*args):
for arg in args:
arg = function2(arg)
</code></pre>
<p>which then exposes the arguments with which the function was invoked as a tuple which can be iterated over.</p>
<p>If you need to store the results for every invocation, it is better to change the <code>for-loop</code> in a <a href="https://docs.python.org/3.6/tutorial/datastructures.html#list-comprehensions" rel="nofollow"><em>list comprehension</em></a> creating a list of the returned values. For example, given a function that takes a value and simply adds <code>2</code> to it:</p>
<pre><code>def add2(arg):
return arg + 2
def function1(arg1, arg2, arg3, arg4):
a1, a2, a3, a4 = [add2(arg) for arg in (arg1, arg2, arg3, arg4)]
print(a1, a2, a3, a4)
</code></pre>
<p>We create a list comprehension that takes every <code>arg</code> and supplies it to <code>add2</code> and then stores it as an entry in a list, then we unpack to <code>a1,..,aN</code>. The values now contain the results of the function calls:</p>
<pre><code>function1(1, 2, 3, 4)
3, 4, 5, 6
</code></pre>
<p>In the previous examples <code>(arg1, arg2, arg3, arg4)</code> can always be replaced with <code>args</code> if you use the <code>*args</code> syntax when defining the function, the results will be similar.</p>
<hr>
<p>As an addendum, if you're more a fan of functional programming, you could always <strong><a href="https://docs.python.org/3/library/functions.html#map" rel="nofollow"><code>map</code></a></strong> the arguments to the function and save a few characters :-). I'll add a <code>*args</code> definition of <code>function1</code> this time:</p>
<pre><code>def function1(*args):
a1, a2, a3, a4 = map(add2, args)
print(a1, a2, a3, a4)
</code></pre>
<p>Same result.</p>
| 6 | 2016-09-26T08:41:48Z | [
"python",
"function",
"python-3.x"
]
|
python 3.x what is -> annotation | 39,698,290 | <p>In the following snippet what is <code>-></code> operator ,does it indicate the return type of the function also is it mandatory to use it in python 3.x ? Please point me to few docs for the same</p>
<pre><code> def g() -> str :
...
return 'hello world'
</code></pre>
| -5 | 2016-09-26T08:45:22Z | 39,698,327 | <p>This is type of return value: <a href="https://docs.python.org/3/library/typing.html" rel="nofollow">https://docs.python.org/3/library/typing.html</a> :) It's not mandatory, but might be usefull.</p>
| 1 | 2016-09-26T08:46:44Z | [
"python"
]
|
python 3.x what is -> annotation | 39,698,290 | <p>In the following snippet what is <code>-></code> operator ,does it indicate the return type of the function also is it mandatory to use it in python 3.x ? Please point me to few docs for the same</p>
<pre><code> def g() -> str :
...
return 'hello world'
</code></pre>
| -5 | 2016-09-26T08:45:22Z | 39,698,353 | <p><code>-></code> is an <a href="https://www.python.org/dev/peps/pep-3107/" rel="nofollow"><em>annotation</em></a>, attached to the function <em>return value</em>. Annotations are optional, but you can use the syntax to attach arbitrary objects to a function. You can attach more annotations by using <code>name : annotation</code> on the parameters too.</p>
<p>In the sample you gave, it is being used to create a <em>type hint</em>. Type hinting is a new Python 3 extension. It is <em>not</em> mandatory, but using type hints can make development in an IDE like PyCharm easier, as well as enable static typechecking by tools like <a href="http://mypy-lang.org/" rel="nofollow">mypy</a>.</p>
<p>See the <a href="https://docs.python.org/3/library/typing.html" rel="nofollow"><code>typing</code> module</a> for a set of objects to help create type hints, and the <a href="https://www.python.org/dev/peps/pep-0484/" rel="nofollow">PEP 484 <em>Type Hints</em></a> proposal.</p>
| 4 | 2016-09-26T08:48:06Z | [
"python"
]
|
Extracting Keywords using TF-IDF | 39,698,538 | <p>I'm tackling the problem of Keyword Extraction using TF-IDF in an article .
The pipeline that I follow goes as follows :</p>
<ol>
<li>Input Text</li>
<li>Tokenize into sentences to build vocabulary</li>
<li>Apply CountVectorizer to build a count vector for each sentence .</li>
<li>Apply TfidfTransformer to assign weights for the same .</li>
</ol>
<p>However , the problem I'm facing with this is that the scores I'm receiving for each token is in context with the sentence and what I want is the score of the token in context to the whole article . So how do I go about achieving that ?</p>
<p>For eg :
This is my toy text .</p>
<blockquote>
<p>"Rashid Siddiqui kept hearing those words from his fellow Muslim pilgrims lying mangled on the ground in 118-degree heat, under a searing Saudi sun. Barefoot, topless and dazed, Mr. Siddiqui had somehow escaped being crushed by the surging crowd.It was Sept. 24, 2015, the third morning of the hajj, the annual five-day pilgrimage to Mecca by millions of Muslims from around the world. By some estimates, it was the deadliest day in hajj history and one of the worst accidents in the world in decades. An American from Atlanta, Mr. Siddiqui, 42, had been walking through a sprawling valley of tens of thousands of pilgrim tents. His destination: Jamarat Bridge, where pilgrims throw pebbles at three large pillars in a ritual symbolizing the stoning of the devil. He was less than a mile from the bridge when the crush began."</p>
</blockquote>
<p>And this is my weight matrix .</p>
<pre><code>[[ 0.24922681 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0.24922681 0. 0.
0. 0. 0.24922681 0.24922681 0. 0.24922681
0.24922681 0. 0. 0.24922681 0. 0.24922681
0.24922681 0. 0. 0. 0. 0.
0.24922681 0. 0. 0. 0. 0.20107462
0. 0.24922681 0. 0.24922681 0.24922681 0.
0.1669101 0. 0. 0.24922681 0. 0. 0.
0. 0. 0. 0. 0. 0.
0.24922681 0. 0. ]
[ 0. 0.22910137 0.22910137 0. 0. 0.
0.22910137 0. 0.22910137 0. 0. 0.22910137
0. 0.22910137 0.18483754 0.22910137 0. 0. 0.
0. 0. 0.22910137 0. 0. 0.
0.18483754 0. 0. 0. 0. 0. 0.
0. 0. 0.22910137 0. 0.22910137 0.22910137
0.18483754 0. 0.22910137 0. 0. 0.22910137
0. 0. 0. 0. 0. 0.
0.22910137 0.15343186 0. 0. 0. 0.22910137
0. 0. 0. 0. 0. 0.22910137
0. 0. 0. 0.18483754 0. ]
[ 0. 0. 0. 0.22910137 0.22910137 0.22910137
0. 0.22910137 0. 0. 0. 0. 0.
0. 0.18483754 0. 0.22910137 0.22910137 0. 0.
0. 0. 0.22910137 0. 0. 0.18483754
0. 0. 0.22910137 0. 0. 0. 0.
0. 0. 0. 0. 0. 0.18483754
0. 0. 0. 0.22910137 0. 0. 0.
0. 0. 0. 0. 0. 0.15343186
0.22910137 0. 0. 0. 0. 0.22910137
0.22910137 0.22910137 0. 0. 0.22910137 0.22910137
0. 0.18483754 0.22910137]
</code></pre>
<p>Now what my question is that are these weights for the token with respect to the sentence or with respect to the whole article ? If it's with respect to the sentence , then how do i make it with respect to the whole article? </p>
<p>What I'm trying to achieve is a kind of unsupervised technique using tfidf for extracting keywords for a single article!! </p>
| 0 | 2016-09-26T08:57:11Z | 39,785,761 | <p>TfidfVectorizer is equivalent to Applying a CountVectorizer and then TfidfTransformer as given <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html" rel="nofollow">here</a>. If i understood you correctly, you passed an article and it returned a matrix of weight vectors but it would only happen if you divided the article into sentences or so. If it just one article you passed, it would return a sparse row. <a href="https://github.com/HimaVarsha94/Tfidf-test/blob/master/tfidf.ipynb" rel="nofollow">Here</a> is a sample python notebook which I made should help you.</p>
| 0 | 2016-09-30T07:14:05Z | [
"python",
"scikit-learn",
"nlp",
"tf-idf"
]
|
string reversal function using reversed indexing | 39,698,619 | <p>Could someone please help me understand why the following function does not print out the reverse of the string? What am I doing wrong?</p>
<pre><code>def myReverse(data):
for index in range( len(data)-1, -1, -1 ):
return data[index]
print( data[index] )
myReverse('blahblah')
</code></pre>
| -5 | 2016-09-26T09:01:19Z | 39,698,707 | <p>When you make a <code>return</code> call within the function, the control comes back to parent (which executed the function) ignoring the code within the scope of function after <code>return</code>. In your case, that is why <code>print</code> is not getting executed by your code.</p>
<p>Move the line containing <code>print</code> before <code>return</code> and move <code>return</code> to outside of the <code>for</code> loop. Your code should work then.</p>
<p><strong>Suggestion:</strong>
There is simpler way to reverse the string using <code>::-1</code>. For example:</p>
<pre><code>>>> my_string = 'HELLO'
>>> my_string[::-1]
'OLLEH'
</code></pre>
| 2 | 2016-09-26T09:05:35Z | [
"python"
]
|
string reversal function using reversed indexing | 39,698,619 | <p>Could someone please help me understand why the following function does not print out the reverse of the string? What am I doing wrong?</p>
<pre><code>def myReverse(data):
for index in range( len(data)-1, -1, -1 ):
return data[index]
print( data[index] )
myReverse('blahblah')
</code></pre>
| -5 | 2016-09-26T09:01:19Z | 39,698,712 | <p>You are returning before print. So the line <code>print( data[index] )</code> is never get executed. </p>
<p>Below code wil work just fine. </p>
<pre><code>def myReverse(data):
for index in range( len(data)-1, -1, -1 ):
print( data[index] , end = '')
</code></pre>
<p>Notice that this is a python3 solution. <code>print</code> in Python2 doesn't work like that. </p>
<p>So, get the same effect in python2 , first import the <code>print</code> from <code>__future__</code>.</p>
<pre><code>from __future__ import print_function
</code></pre>
<p>And then, same as above. </p>
| 1 | 2016-09-26T09:05:52Z | [
"python"
]
|
string reversal function using reversed indexing | 39,698,619 | <p>Could someone please help me understand why the following function does not print out the reverse of the string? What am I doing wrong?</p>
<pre><code>def myReverse(data):
for index in range( len(data)-1, -1, -1 ):
return data[index]
print( data[index] )
myReverse('blahblah')
</code></pre>
| -5 | 2016-09-26T09:01:19Z | 39,698,759 | <p><em>Intro:</em> the execution of a <code>for</code> loop will stop once a <code>return</code> statement or <code>break</code> statement is encountered or there is an exception.</p>
<p>You have a <code>return</code> statement which makes the <code>for</code> loop stop (<em>returning</em> control to the caller) as soon as the statement is encountered in the first iteration.</p>
<p>Move the <code>return</code> statement outside the <code>for</code> loop</p>
| 1 | 2016-09-26T09:08:29Z | [
"python"
]
|
TypeError: can only concatenate tuple (not "str") to tuple line 6 | 39,698,773 | <pre><code>import os
import time
source = [r'C:\\Documents','/home/swaroop/byte', '/home/swaroop/bin']
target_dir =r'C:\\Documents','/mnt/e/backup/'
today = target_dir + time.strftime("%Y%m%d")
now = time.strftime('%H%M%S')
os.path.exists(today)
os.mkdir(today)
print 'Successful created directory', today
target = today + os.sep + now + '.zip'
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'
today = target_dir + time.strftime("%Y%m%d")
</code></pre>
<p>Plees help</p>
<p>TypeError: can only concatenate tuple (not "str") to tuple</p>
| -6 | 2016-09-26T09:09:24Z | 39,699,216 | <p>Check the comma as @MosesKoledoye said, the <a href="http://files.swaroopch.com/python/byte_of_python.pdf" rel="nofollow">book</a> has:</p>
<pre><code># 1. The files and directories to be backed up are
# specified in a list.
# Example on Windows:
# source = ['"C:\\My Documents"', 'C:\\Code'] # Example on Mac OS X and Linux:
source = ['/Users/swa/notes']
# Notice we had to use double quotes inside the string # for names with spaces in it.
# 2. The backup must be stored in a
# main backup directory
# Example on Windows:
# target_dir = 'E:\\Backup'
# Example on Mac OS X and Linux:
target_dir = '/Users/swa/backup'
# Remember to change this to which folder you will be using
</code></pre>
<p>your code has:</p>
<pre><code>source = [r'C:\\Documents','/home/swaroop/byte', '/home/swaroop/bin']
target_dir =r'C:\\Documents','/mnt/e/backup/'
</code></pre>
<p>In the <code>target_dir</code> assignment the comma makes the right-side of the assignment a <em>tuple</em>. To join two strings together use a <code>+</code>, not a comma:</p>
<pre><code> target_dir =r'C:\\Documents' + '/mnt/e/backup/'
</code></pre>
<p>better yet, use a single string. <strong>However</strong>, <code>/mnt</code> is a Linux directory name, not a Windows one. I suspect you actually need:</p>
<pre><code> target_dir = '/mnt/e/backup/'
</code></pre>
<p>You have also made the Windows path a raw string, which means the two back-slashes will be retained. Either do this:</p>
<pre><code>'C:\\Documents'
</code></pre>
<p>or this:</p>
<pre><code>r'C:\Documents'
</code></pre>
<p>(unless or course you actually do want <code>\\</code>)</p>
<p>Edit: I just noticed you also have an indentation problem:</p>
<pre><code>if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
</code></pre>
<p>should be:</p>
<pre><code>if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
</code></pre>
<p>Finally, when you say "I copy all the code" and it fails, look to see where yours differs from what it says in the book.</p>
| 0 | 2016-09-26T09:30:16Z | [
"python"
]
|
python: Google Street View url request cannot load as json() | 39,698,881 | <p>I want to use python to grab Google Street View image.
For example:</p>
<pre><code>'url=https://maps.googleapis.com/maps/api/streetview?location=48.15763817939112,11.533002555370581&size=512x512&key=
</code></pre>
<p>I run the following code:</p>
<pre><code>import requests
result = requests.get(url)
result.json()
</code></pre>
<p>But it comes out an error:</p>
<pre><code>Traceback (most recent call last):
File "<ipython-input-69-180c2a4b335d>", line 1, in <module>
result.json()
File "/home/kang/.local/lib/python3.4/site-packages/requests/models.py", line 826, in json
return complexjson.loads(self.text, **kwargs)
File "/home/kang/.local/lib/python3.4/site-packages/simplejson/__init__.py", line 516, in loads
return _default_decoder.decode(s)
File "/home/kang/.local/lib/python3.4/site-packages/simplejson/decoder.py", line 370, in decode
obj, end = self.raw_decode(s)
File "/home/kang/.local/lib/python3.4/site-packages/simplejson/decoder.py", line 400, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
JSONDecodeError: Expecting value
</code></pre>
<p>The response of this url is:</p>
<p><a href="http://i.stack.imgur.com/i9uKk.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/i9uKk.jpg" alt="enter image description here"></a> </p>
<p>How to fix that?
Thank you very much.</p>
| -1 | 2016-09-26T09:14:32Z | 39,718,856 | <p>There is no JSON in the response that is coming back to you, which is why it is giving the error. </p>
| 0 | 2016-09-27T07:40:16Z | [
"python",
"json",
"api",
"google-maps-api-3",
"google-street-view"
]
|
HttpIO - Consuming external resources in a Dataflow transform | 39,698,886 | <p>I'm trying to write a custom <code>Source</code> using the Python Dataflow SDK to read JSON data in parallel from a REST endpoint.</p>
<p>E.g. for a given set of IDs, I need to retrieve the data from:
<code>
https://foo.com/api/results/1
https://foo.com/api/results/2
...
https://foo.com/api/results/{maxID}
</code></p>
<p>The key features I need are monitoring & rate limiting : even though I need parallelism (either thread/process-based or using async/coroutines), I also need to make sure my job stays "polite" towards the API endpoint - effectively avoiding involuntary DDoS.</p>
<p>Using <a href="https://github.com/GoogleCloudPlatform/psq" rel="nofollow">psq</a>, I should be able to implement some kind of rate-limit mechanism, but then I'd lose the ability to monitor progress & ETA using the <a href="https://cloud.google.com/dataflow/pipelines/dataflow-monitoring-intf" rel="nofollow">Dataflow Service Monitoring</a></p>
<p>It seems that, although they work well together, monitoring isn't unified between Google Cloud Dataflow and Google Cloud Pub/Sub (which uses Google Stackdriver Monitoring)</p>
<p><strong>How should I go about building a massively-parallel HTTP consumer workflow which implements rate limiting and has web-based monitoring ?</strong> </p>
| 0 | 2016-09-26T09:14:41Z | 39,776,506 | <p>Dataflow does not currently have a built-in way of doing global rate-limiting, but you can use the Source API to do this. The key concept is that each split of a Source will be processed by a single thread at most, so you can implement local rate limiting separately for each split.</p>
<p>This solution does not use Pub/Sub at all, so you can exclusively use the Dataflow Monitoring UI. If you want to set up alerts based on particular events in your pipeline, you could do something like <a href="http://stackoverflow.com/questions/35068351/how-do-i-set-alerts-based-on-events-in-my-dataflow-pipelines">this</a></p>
| 1 | 2016-09-29T17:26:13Z | [
"python",
"google-cloud-dataflow",
"google-cloud-pubsub",
"airflow"
]
|
how to properly use a unicode string in python regex | 39,698,935 | <p>I am getting an input regular expression from a user which is saved as a unicode string. Do I have to turn the input string into a raw string before compliling it as a regex object? Or is it unnecessary? Am I converting it to raw string properly?</p>
<pre><code>import re
input_regex_as_unicode = u"^(.){1,36}$"
string_to_check = "342342dedsfs"
# leave as unicode
compiled_regex = re.compile(input_regex_as_unicode)
match_string = re.match(compiled_regex, string_to_check)
# convert to raw
compiled_regex = re.compile(r'' + input_regex_as_unicode)
match_string = re.match(compiled_regex, string_to_check)
</code></pre>
<p>@Ahsanul Haque, my question is more regular expression specific, whether the regex handles the unicode string properly when converting it into a regex object</p>
| -1 | 2016-09-26T09:16:46Z | 39,700,258 | <p>The <code>re</code> module handles both unicode strings and normal strings properly, you do not need to convert them to anything (but you should be consistent in your use of strings).</p>
<p>There is no such a thing like "raw strings". You can use raw string notation in your code if it helps you with strings containing backslashes. For instance to match a newline character you could use <code>'\\n'</code>, <code>u'\\n'</code>, <code>r'\n'</code> or <code>ur'\n'</code>.</p>
<p>Your use of the raw string notation in your example does nothing since <code>r''</code> and <code>''</code> evaluate to the same string.</p>
| 1 | 2016-09-26T10:20:02Z | [
"python",
"regex",
"python-2.7"
]
|
How to store output of a python program in command prompt? | 39,699,061 | <p>I'm passing run time variable from command prompt to python to execute there (im=n python). Now I want to store the result of python program and use those results back into command prompt. Sample is as follows</p>
<pre><code>set input=
set /P input=Enter Layer Name:%=%
C:\Python27\python.exe F:\xampp\htdocs\flood_publish\projection_raster.py %input%
</code></pre>
<p>I'm passing user input string to python program from command prompt as above.
How use the result of python program back into command prompt</p>
| 0 | 2016-09-26T09:23:10Z | 39,699,140 | <p>Assuming its a bash script from where you are calling the python function, it should be done like:</p>
<pre><code>function callPython()
{
local pythonResult=<code for calling python>
echo $pythonResult
}
local pythonReturnOutput = $(callPython)
</code></pre>
<p>and you can now use pythonReturnOutput.</p>
<p>This answer may be incorrect, if you are not using bash, shell script. However, I would highly recommend to have a script in place, if its not already.</p>
| -1 | 2016-09-26T09:26:37Z | [
"python",
"shell",
"cmd",
"runtime",
"parameter-passing"
]
|
How to store output of a python program in command prompt? | 39,699,061 | <p>I'm passing run time variable from command prompt to python to execute there (im=n python). Now I want to store the result of python program and use those results back into command prompt. Sample is as follows</p>
<pre><code>set input=
set /P input=Enter Layer Name:%=%
C:\Python27\python.exe F:\xampp\htdocs\flood_publish\projection_raster.py %input%
</code></pre>
<p>I'm passing user input string to python program from command prompt as above.
How use the result of python program back into command prompt</p>
| 0 | 2016-09-26T09:23:10Z | 39,699,297 | <p>Let me know if this helps.</p>
<p><strong>Code of python file (c.py):</strong></p>
<pre><code>import sys
print('You passed ',sys.argv[1])
</code></pre>
<p><strong>Windows Batch Code (a.bat) :</strong></p>
<pre><code>@echo off
set input=
set /P input=Enter Layer Name:%=%
(python c.py %input%) > tmp.txt
set /P output=<tmp.txt
echo %output%
</code></pre>
<p>
<strong>Output of batch code:</strong></p>
<pre><code>C:\Users\dinesh_pundkar\Desktop>a.bat
Enter Layer Name:Dinesh
You passed Dinesh
C:\Users\dinesh_pundkar\Desktop>
</code></pre>
| 1 | 2016-09-26T09:34:26Z | [
"python",
"shell",
"cmd",
"runtime",
"parameter-passing"
]
|
How to store output of a python program in command prompt? | 39,699,061 | <p>I'm passing run time variable from command prompt to python to execute there (im=n python). Now I want to store the result of python program and use those results back into command prompt. Sample is as follows</p>
<pre><code>set input=
set /P input=Enter Layer Name:%=%
C:\Python27\python.exe F:\xampp\htdocs\flood_publish\projection_raster.py %input%
</code></pre>
<p>I'm passing user input string to python program from command prompt as above.
How use the result of python program back into command prompt</p>
| 0 | 2016-09-26T09:23:10Z | 39,699,455 | <p>It is depending on the case. If your Python code is exiting a value (with <code>exit(<returncode>)</code>), you can retrieve it from the <code>%ERRORLEVEL%</code> environment variable.</p>
<pre><code><yourpythoncommand>
echo Return code: %ERRORLEVEL%
</code></pre>
<p>If you are willing to capture and process the standard output, you need to use a <code>FOR</code> loop:</p>
<pre><code>FOR /F "delims=" %%I IN ('<yourpythoncall>') DO CALL :processit %%I
GOTO :EOF
:processit
echo Do something with %1
GOTO :EOF
</code></pre>
<p>Now, if you don't want to process the output line by line, the easiest is to redirect the output to a temporary file.</p>
<pre><code><yourpythoncommand> >%TEMP%\mytempfile.txt
<do something with %TEMP%\mytempfile.txt>
del %TEMP%\mytempfile.txt
</code></pre>
| 0 | 2016-09-26T09:41:56Z | [
"python",
"shell",
"cmd",
"runtime",
"parameter-passing"
]
|
Spark RDD to DataFrame python | 39,699,107 | <p>I am trying to convert the Spark RDD to a DataFrame. I have seen the documentation and example where the scheme is passed to
<code>sqlContext.CreateDataFrame(rdd,schema)</code> function. </p>
<p>But I have 38 columns or fields and this will increase further. If I manually give the schema specifying each field information, that it going to be so tedious job.</p>
<p>Is there any other way to specify the schema without knowing the information of the columns prior.</p>
| 0 | 2016-09-26T09:24:49Z | 39,705,464 | <p>See,</p>
<p>There is two ways of convert an RDD to DF in spark.</p>
<p><code>toDF()</code> and <code>createDataFrame(rdd, schema)</code></p>
<p>I will show you how you can do that dynamically.</p>
<h2>toDF()</h2>
<p>The <code>toDF()</code> command gives you the way to convert an <code>RDD[Row]</code> to a Dataframe. The point is, the object <code>Row()</code> can receive a <code>**kwargs</code> argument. So, there is an easy way to do that.</p>
<pre><code>from pyspark.sql.types import Row
#here you are going to create a function
def f(x):
d = {}
for i in range(len(x)):
d[str(i)] = x[i]
return d
#Now populate that
df = rdd.map(lambda x: Row(**f(x))).toDF()
</code></pre>
<p>This way you are going to be able to create a dataframe dynamically.</p>
<h1>createDataFrame(rdd, schema)</h1>
<p>Other way to do that is creating a dynamic schema. How?</p>
<p>This way:</p>
<pre><code>from pyspark.sql.types import StructType
from pyspark.sql.types import StructField
from pyspark.sql.types import StringType
schema = StructType([StructField(str(i), StringType(), True) for i in range(32)])
df = sqlContext.createDataFrame(rdd, schema)
</code></pre>
<p>This seccond way is cleanner to do that...</p>
<p>So this is how you can create dataframes dynamically.</p>
| 0 | 2016-09-26T14:25:32Z | [
"python",
"apache-spark",
"pyspark",
"spark-dataframe"
]
|
Create a function that sorts customers of the bank by amount of money | 39,699,257 | <p>I'm learning how to use Classes, so far I have achieved the following:</p>
<pre><code>class customer:
def __init__ (self, name, ID, money):
self.name = name
self.ID = ID
self.money = money
def deposit(self, amount):
self.money = self.money+amount
def withdraw(self, amount):
self.money = self.money-amount
mike = customer('Mike', 1343, 1884883)
john = customer('John', 1343, 884839)
steve = customer('Steve', 1343, 99493)
adam = customer('Adam', 1343, 10000)
</code></pre>
<p>I would like to create a function that sorts the customers by the amount of money they have but am unsure about how to do so.</p>
| 0 | 2016-09-26T09:32:20Z | 39,699,423 | <pre><code>def sort_by_money(customer)
for index in range(1,len(customer)):
currentvalue = customer[index].money
position = index
while position>0 and customer[position-1].money > currentvalue:
alist[position]=alist[position-1]
position = position-1
customer[position]=customer
</code></pre>
<p>Simple insertion sort that takes in customer array and sorts it back based on money.</p>
<p>This code will be outside your customer class that will take customer array as input.</p>
<p>There can be many correct answer to this problem. Written insertion sort to explain properly. </p>
| -1 | 2016-09-26T09:40:15Z | [
"python",
"python-2.7",
"function",
"class",
"initialization"
]
|
Create a function that sorts customers of the bank by amount of money | 39,699,257 | <p>I'm learning how to use Classes, so far I have achieved the following:</p>
<pre><code>class customer:
def __init__ (self, name, ID, money):
self.name = name
self.ID = ID
self.money = money
def deposit(self, amount):
self.money = self.money+amount
def withdraw(self, amount):
self.money = self.money-amount
mike = customer('Mike', 1343, 1884883)
john = customer('John', 1343, 884839)
steve = customer('Steve', 1343, 99493)
adam = customer('Adam', 1343, 10000)
</code></pre>
<p>I would like to create a function that sorts the customers by the amount of money they have but am unsure about how to do so.</p>
| 0 | 2016-09-26T09:32:20Z | 39,699,532 | <p>You can sort a list of objects in place by an attribute like this:</p>
<pre><code>your_list.sort(key=lambda x: x.attribute_name, reverse=True)
</code></pre>
<p>If you set <code>reverse=False</code>, the list is ordered ascending, with <code>reverse=True</code> it is sorted from highest amount to lowest.</p>
<p>So in your case:</p>
<pre><code>class customer:
def __init__ (self, name, ID, money):
self.name = name
self.ID = ID
self.money = money
def deposit(self, amount):
self.money = self.money+amount
def withdraw(self, amount):
self.money = self.money-amount
mike = customer('Mike', 1343, 1884883)
john = customer('John', 1343, 884839)
steve = customer('Steve', 1343, 99493)
adam = customer('Adam', 1343, 10000)
unsorted_list = [steve, adam, mike, john]
print [c.name for c in unsorted_list]
unsorted_list.sort(key=lambda c: c.money, reverse=True)
print [c.name for c in unsorted_list]
</code></pre>
<p><a href="http://stackoverflow.com/questions/403421/how-to-sort-a-list-of-objects-in-python-based-on-an-attribute-of-the-objects">For more information check this question too</a></p>
| 3 | 2016-09-26T09:45:21Z | [
"python",
"python-2.7",
"function",
"class",
"initialization"
]
|
How to check whether particular column completely match or not | 39,699,312 | <p>I would like to compare particular column with the other one.
For instance,when I compare A column with B by using some method,
it should return False.</p>
<pre><code> A B
0 1 2
1 2 2
2 3 3
3 4 4
</code></pre>
<p>when I try</p>
<pre><code>df.A==df.B
</code></pre>
<p>But this returns whether each elements match with the other.</p>
<p>How can I compare column with the other one ?</p>
| 1 | 2016-09-26T09:35:25Z | 39,699,332 | <p>You want to use <code>all</code></p>
<pre><code>(df.A == df.B).all()
</code></pre>
<hr>
<pre><code>df.A.eq(df.B)
0 False
1 True
2 True
3 True
dtype: bool
</code></pre>
<hr>
<pre><code>df.A.eq(df.B).all()
False
</code></pre>
| 5 | 2016-09-26T09:36:18Z | [
"python",
"pandas",
"dataframe"
]
|
How to check whether particular column completely match or not | 39,699,312 | <p>I would like to compare particular column with the other one.
For instance,when I compare A column with B by using some method,
it should return False.</p>
<pre><code> A B
0 1 2
1 2 2
2 3 3
3 4 4
</code></pre>
<p>when I try</p>
<pre><code>df.A==df.B
</code></pre>
<p>But this returns whether each elements match with the other.</p>
<p>How can I compare column with the other one ?</p>
| 1 | 2016-09-26T09:35:25Z | 39,699,360 | <p>You can use <code>equals</code>:</p>
<pre><code>df['A'].equals(df['B'])
Out: False
</code></pre>
<p>This checks whether two Series are exactly the same - labels included.</p>
| 6 | 2016-09-26T09:37:37Z | [
"python",
"pandas",
"dataframe"
]
|
Function to return elements from a list in Python | 39,699,418 | <p>I have a function:</p>
<pre><code>def funky(a):
c = [4,5,6]
return c[a]
</code></pre>
<p>I would like to be able to call:</p>
<pre><code>funky(0:1)
</code></pre>
<p>And</p>
<pre><code>funky(0,1)
</code></pre>
<p>To get the same response [4,5]. How do I modify 'funky' to do this?</p>
| 0 | 2016-09-26T09:39:59Z | 39,699,508 | <p>Enter slice(0, 1) as a parameter to your function as is. 0:1 won't work ever as it is not a passable parameter. </p>
| 1 | 2016-09-26T09:44:25Z | [
"python",
"list"
]
|
Function to return elements from a list in Python | 39,699,418 | <p>I have a function:</p>
<pre><code>def funky(a):
c = [4,5,6]
return c[a]
</code></pre>
<p>I would like to be able to call:</p>
<pre><code>funky(0:1)
</code></pre>
<p>And</p>
<pre><code>funky(0,1)
</code></pre>
<p>To get the same response [4,5]. How do I modify 'funky' to do this?</p>
| 0 | 2016-09-26T09:39:59Z | 39,699,519 | <p>You can use the slice method directly on the list:</p>
<pre><code>def funky(*a):
c = [4,5,6]
return c.__getitem__(*a)
print(funky(1, 3))
>>> [5, 6]
</code></pre>
| 4 | 2016-09-26T09:44:58Z | [
"python",
"list"
]
|
Function to return elements from a list in Python | 39,699,418 | <p>I have a function:</p>
<pre><code>def funky(a):
c = [4,5,6]
return c[a]
</code></pre>
<p>I would like to be able to call:</p>
<pre><code>funky(0:1)
</code></pre>
<p>And</p>
<pre><code>funky(0,1)
</code></pre>
<p>To get the same response [4,5]. How do I modify 'funky' to do this?</p>
| 0 | 2016-09-26T09:39:59Z | 39,699,521 | <pre><code>def funky(a,b):
c = [4,5,6]
return c[a:b+1]
</code></pre>
<p>And you can call <code>funky(0,1)</code>, And you cant't call like <code>funky(</code>0:1<code>)</code>. It's not a valid parameter.</p>
<p>You can call like <code>funky('0:1')</code> Because. If you need to take that kind of input take as string input and <code>split</code> with <code>:</code></p>
<p>like this,</p>
<pre><code>def funky(a):
c = [4,5,6]
x,y = map(int,a.split(':'))
return c[x:y+1]
</code></pre>
| 1 | 2016-09-26T09:45:08Z | [
"python",
"list"
]
|
Push notifications with minimal data usage | 39,699,461 | <p>In my project, I want to call an action on a Raspberry Pi from the Internet. Somehow like that:</p>
<ol>
<li>Visit webpage</li>
<li>Hit a button on the webpage</li>
<li>Raspberry pi executes a script</li>
</ol>
<p>The difficult part is, that the raspberry pi only has a mobile Internet connection <em>without a flatrate</em>. So, sending and receiving data from/to the Raspberry Pi is costly.</p>
<p>So this is my question:</p>
<p>Which technologies and patterns can I use to send push notifications to the raspberry pi <em>with minimal data usage</em>?</p>
| 1 | 2016-09-26T09:42:09Z | 39,701,872 | <p>Start off by creating or starting something that accepts incoming connections on your RPi. Something small as the below example would do:</p>
<pre><code>#!/usr/bin/python
from socket import *
s = socket()
s.bind(('', 8001))
s.listen(4)
while 1:
ns, na = s.accept()
print(na,'sent you:',ns.recv(8192))
</code></pre>
<p>Now, the above example will only open a port on <code>8001</code> and then print whatever the other send sent to it.</p>
<p>On the server end, I suggest you setup a web server or something else that is easily accessible that can store an IP in a database/register somewhere.</p>
<p>Then, during boot of your RPi (pref after the networking service is started) go ahead and schedule:</p>
<pre><code>curl https://your-server.eu/reg_ip.php > /dev/null 2>&1
</code></pre>
<p>Now, on the server <code>your-server.eu:443</code>, make sure <code>req_ip.php</code> saves the clients IP (client being your RPi) in a database somewhere.</p>
<p>Now, which ever application that you have that need to send out PUSH notifications can lookup the current IP of clients in the database and try to connect to port <code>8001</code> on those IP's and send whatever data you need.</p>
<p>Now two things:</p>
<ol>
<li><p>A listening TCP socket (on the RPi) won't use up any data at all but will allow for incomming connections when needed.</p></li>
<li><p>If your IP changes on the RPi (which it probably will on a moving GSM/3G/4G network for instance), you need to do another <code>curl</code> request to your server. This however could easily be tied to a for instance <code>ip monitor</code> command and perform the curl request then.</p></li>
</ol>
<h1>tl;dr</h1>
<p>Here's your chain:</p>
<p><code>Pi opens a listening socket -> Pi connects to HTTP(S) -> servers saves IP -> when server has something to send -> connect to last known IP on port X -> send data -> close connection</code></p>
<h1>Enhancing further</h1>
<p>Now, the HTTP header alone is quite big, in fact it's default 78 bytes of package data (TCP and IP headers usually isn't included in data rates, only the data being transferred is - in this case, HTTP data.). So what you could expand on is if you could use the simple example of a socket above on the server as well and just take the <code>na[0]</code> variable and send that to a database, that way you use literally 0 data-rate on your data subscription.</p>
<p>Only the actual data sent then later on from the server application as a "PUSH notification" would use up data.</p>
<h1>In case your RPi is on a NAT based network (private network)</h1>
<p>Seeing as the OP gets a <code>10.X.X.X</code> address it's unlikely that a listening socket will do the trick.</p>
<p>Instead, what you could do is you could simply try and establish a connection and keep it open and have the server send data over any open socket when it has data.</p>
<p>Here's an extremely rough idea of how you could achieve it.<br>
I kept it simple and stupid just to give an idea without solving the entire thing.</p>
<p>Again, the open socket between the client (RPi) and the Server won't use up any data until you actually send data over the channel.</p>
<p>You could in your server fetch data from a database that you want to send to the clients, you could do anything really. Since I don't know your goal I'll just leave it as it is for the time being.</p>
<h2>Server:</h2>
<pre><code>#!/usr/bin/python
from socket import *
from threading import *
from time import time, sleep
from random import randint
class ClientThread(Thread)
def __init__(self, clients):
self.clients = clients
self.messages = []
Thread.__init__(self)
self.start()
def notify(self, message):
if type(message) is str: message = bytes(message, 'UTF-8')
self.messages.append(message)
def run(self):
while 1:
if len(self.messages) > 0:
m = self.messages.pop(0)
for client in self.clients:
self.clients[client]['sock'].send(m)
class RandomMessageGenerator(Thread):
def __init__(self, notify_func):
self.notify_func = notify_func
self.last = time()
Thread.__init__(self)
self.start()
def run(self):
while 1:
self.notify_func('Time since last update: ' + str(time() - self.last))
self.last = time()
sleep(randint(0,30))
client_list = {}
client_thread_handle = ClientThread(client_list)
random_generator = RandomMessageGenerator(client_thread_handle.nofity)
s = socket()
s.bind(('', 8001))
s.listen(4)
while 1:
ns, na = s.accept()
client_list[na] = {'sock' : 'ns'}
</code></pre>
<h2>Client:</h2>
<pre><code>from socket import *
s = socket()
s.connect(('server', 8001))
while 1:
print(s.recv(8192))
</code></pre>
| 1 | 2016-09-26T11:40:34Z | [
"python",
"web",
"push-notification",
"connection",
"network-protocols"
]
|
Creating a list based on column conditions | 39,699,659 | <p>I have a DataFrame <code>df</code></p>
<pre><code>>>df
LED CFL Incan Hall Reading
0 3 2 1 100 150
1 2 3 1 150 100
2 0 1 3 200 150
3 1 2 4 300 250
4 3 3 1 170 100
</code></pre>
<p>I want to create two more column which contain <code>lists</code>, one for <code>"Hall"</code> and another for <code>"Reading"</code></p>
<pre><code>>>df_output
LED CFL Incan Hall Reading Hall_List Reading_List
0 3 2 1 100 150 [0,2,0] [2,0,0]
1 2 3 1 150 100 [0,3,0] [2,0,0]
2 0 1 3 200 150 [0,1,0] [0,0,2]
3 1 2 4 300 250 [0,2,0] [1,0,0]
4 3 3 1 100 100 [0,2,0] [2,0,0]
</code></pre>
<p>Each value within the list is populated as follows:</p>
<pre><code>cfl_rating = 50
led_rating = 100
incan_rating = 25
</code></pre>
<p>For the <code>Hall_List</code>:</p>
<p>The preference is CFL > LED > Incan. And only one of them will be used (either CFL or LED or Incan).</p>
<p>We first check if <code>CFL != 0</code> , if <code>True</code> then we calculate <code>min(ceil(Hall/CFL_rating),CFL)</code>. For <code>index=0</code> this evaluates to 2. Hence we have [0,2,0] whereas for <code>index=2</code> we have [0,1,0].</p>
<p>Similarly for <code>Reading_List</code>, the preference is LED > Incan > CFL.
For <code>index=2</code>, we have <code>LED == 0</code>, so we calculate <code>min(ceil(Reading/Incan_rating),Incan)</code> and hence Reading_List is <code>[0,0,2]</code></p>
<p><strong>My question is:</strong>
Is there a <em>"pandas/pythony-way"</em> of doing this? I am currently iterating through each row, and using if-elif-else conditions to assign values.</p>
<p>My code snippet looks like this:</p>
<pre><code>#Hall_List
for i in range(df.shape[0]):
Hall = []
if (df['CFL'].iloc[i] != 0):
Hall.append(0)
Hall.append(min((math.ceil(df['Hall'].iloc[i]/cfl_rating)),df['CFL'].iloc[i]))
Hall.append(0)
elif (df['LED'].iloc[i] != 0):
Hall.append(min((math.ceil(df['Hall'].iloc[i]/led_rating)),df['LED'].iloc[i]))
Hall.append(0)
Hall.append(0)
else:
Hall.append(0)
Hall.append(0)
Hall.append(min((math.ceil(df['Hall'].iloc[i]/incan_rating)),df['Incan'].iloc[i]))
df['Hall_List'].iloc[i] = Hall
</code></pre>
<p>This is really slow and definitely feels like a bad way to code this.</p>
| 1 | 2016-09-26T09:52:18Z | 39,708,691 | <p>I shorten your formula for simplicity sake but you should use df.apply(axis=1)</p>
<p>this take every row and return and ndarray, then you can apply whatever function you want such has :</p>
<pre><code>df = pd.DataFrame([[3, 2, 1, 100, 150], [2, 3, 1, 150, 100]], columns=['LED', 'CFL', 'Incan', 'Hall', 'Reading'])
def create_list(ndarray):
if ndarray[1] != 0:
result = [0, ndarray[1], 0]
else:
result = [ndarray[2], 0, 0]
return result
df['Hall_List'] = df.apply(lambda x: create_list(x), axis=1)
</code></pre>
<p>just change the function to whatever you like here.</p>
<pre><code>In[49]: df
Out[49]:
LED CFL Incan Hall Reading Hall_List
0 3 2 1 100 150 [0, 2, 0]
1 2 3 1 150 100 [0, 3, 0]
</code></pre>
<p>hope this helps</p>
| 0 | 2016-09-26T17:16:55Z | [
"python",
"pandas"
]
|
pyqtgraph custom scaling issue | 39,699,702 | <p>I use the pyqtgraph library for plotting. I really like the mouse interaction on the plot (zoom, pan, ...).</p>
<p>For some of my plots I would like to change the zoom behaviour when you scroll the mousewheel. The standard implementation is a scaling in both x- and y-direction simultaneously. Scaling in the x-direction doesn't make sense on those plots, so I would like to disable that. I tried the following:</p>
<pre><code>###################################################################
# #
# PLOTTING A LIVE GRAPH #
# ---------------------------- #
# #
###################################################################
import sys
import os
from PyQt4 import QtGui
from PyQt4 import QtCore
import pyqtgraph as pg
import numpy as np
# Override the pg.ViewBox class to add custom
# implementations to the wheelEvent
class CustomViewBox(pg.ViewBox):
def __init__(self, *args, **kwds):
pg.ViewBox.__init__(self, *args, **kwds)
#self.setMouseMode(self.RectMode)
def wheelEvent(self, ev, axis=None):
# 1. Pass on the wheelevent to the superclass, such
# that the standard zoomoperation can be executed.
pg.ViewBox.wheelEvent(ev,axis)
# 2. Reset the x-axis to its original limits
#
# [code not yet written]
#
class CustomMainWindow(QtGui.QMainWindow):
def __init__(self):
super(CustomMainWindow, self).__init__()
# 1. Define look and feel of this window
self.setGeometry(300, 300, 800, 400)
self.setWindowTitle("pyqtgraph example")
self.FRAME_A = QtGui.QFrame(self)
self.FRAME_A.setStyleSheet("QWidget { background-color: %s }" % QtGui.QColor(210,210,235,255).name())
self.LAYOUT_A = QtGui.QHBoxLayout()
self.FRAME_A.setLayout(self.LAYOUT_A)
self.setCentralWidget(self.FRAME_A)
# 2. Create the PlotWidget(QGraphicsView)
# ----------------------------------------
self.vb = CustomViewBox()
self.plotWidget = pg.PlotWidget(viewBox=self.vb, name='myPlotWidget')
self.LAYOUT_A.addWidget(self.plotWidget)
self.plotWidget.setLabel('left', 'Value', units='V')
self.plotWidget.setLabel('bottom', 'Time', units='s')
self.plotWidget.setXRange(0, 10)
self.plotWidget.setYRange(0, 100)
# 3. Get the PlotItem from the PlotWidget
# ----------------------------------------
self.plotItem = self.plotWidget.getPlotItem()
# 4. Get the PlotDataItem from the PlotItem
# ------------------------------------------
# The plot() function adds a new plot and returns it.
# The function can be called on self.plotWidget or self.plotItem
self.plotDataItem = self.plotItem.plot()
self.plotDataItem.setPen((255, 240, 240))
self.plotDataItem.setShadowPen(pg.mkPen((70, 70, 30), width=2, cosmetic=True))
# 5. Create the x and y arrays
# -----------------------------
n = np.linspace(0, 499, 500)
self.y = 50 + 5 * (np.sin(n / 8.3)) + 7 * (np.sin(n / 7.5)) - 5 * (np.sin(n / 1.5))
self.x = 10 * n / len(n)
self.plotDataItem.setData(x=self.x, y=self.y)
self.show()
if __name__== '__main__':
app = QtGui.QApplication(sys.argv)
QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Plastique'))
myGUI = CustomMainWindow()
sys.exit(app.exec_())
</code></pre>
<p>Just copy-paste this code into a fresh Python file, and you should get the following output:</p>
<p><a href="http://i.stack.imgur.com/E2ASR.png" rel="nofollow"><img src="http://i.stack.imgur.com/E2ASR.png" alt="enter image description here"></a></p>
<p>Unfortunately an error message pops up on every mouseWheel event:</p>
<pre><code>Traceback (most recent call last):
File "pyTest.py", line 26, in wheelEvent
pg.ViewBox.wheelEvent(ev,axis)
File "C:\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\ViewBox\ViewBox.py", line 1206, in wheelEvent
mask = np.array(self.state['mouseEnabled'], dtype=np.float)
AttributeError: 'QGraphicsSceneWheelEvent' object has no attribute 'state'
</code></pre>
<p>My system is as follows:</p>
<ul>
<li>Python version: 3.5.2</li>
<li>PyQt version: 4.11.4</li>
<li>Qt version: 4.8.7</li>
<li>pyqtgraph version: 0.9.10</li>
</ul>
| 0 | 2016-09-26T09:54:32Z | 39,702,394 | <p>My collegue pointed out that I have to add <code>self</code> as first argument when overriding the <code>wheelEvent</code> function:</p>
<pre><code># Override the pg.ViewBox class to add custom
# implementations to the wheelEvent
class CustomViewBox(pg.ViewBox):
def __init__(self, *args, **kwds):
pg.ViewBox.__init__(self, *args, **kwds)
#self.setMouseMode(self.RectMode)
def wheelEvent(self, ev, axis=None):
print(str(self.viewRange()))
# 1. Pass on the wheelevent to the superclass, such
# that the standard zoomoperation can be executed.
pg.ViewBox.wheelEvent(self,ev,axis) # <- To override the function
properly, one should add
'self' as first argument
# 2. Reset the x-axis to its original limits
self.setXRange(0,10)
</code></pre>
<p>Now it works. But the only drawback is the following code line:</p>
<pre><code> # 2. Reset the x-axis to its original limits
self.setXRange(0,10)
</code></pre>
<p>It would be nicer to do this:</p>
<pre><code>def wheelEvent(self, ev, axis=None):
# 1. Determine initial x-range
initialRange = self.viewRange()
# 2. Call the superclass method for zooming in
pg.ViewBox.wheelEvent(self,ev,axis)
# 3. Reset the x-axis to its original limits
self.setXRange(initialRange[0][0],initialRange[0][1])
</code></pre>
<p>The problem is that the function <code>self.viewRange()</code> does not return [0,10] but [-0.37, 10.37] instead. The viewBox adds some margin on the left and the right. If you keep doing that, eventually those margins will drift over time:
[-0.37, 10.37] <code>-></code> [-0.74, 10.74] <code>-></code> ...</p>
| 0 | 2016-09-26T12:07:42Z | [
"python",
"python-3.x",
"pyqt4",
"pyqtgraph"
]
|
How to create multiple VideoCapture Obejcts | 39,699,796 | <p>I wanted to create multiple VideoCapture Objects for stitching video from multiple cameras to a single video mashup.</p>
<p>for example: I have path for three videos that I wanted to be read using Video Capture object shown below to get the frames from individual videos,so they can be used for writing.</p>
<p>Expected:For N number of video paths</p>
<pre><code> cap0=cv2.VideoCapture(path1)
cap1=cv2.VideoCapture(path2)
cap2=cv2.VideoCapture(path3)
.
.
capn=cv2.VideoCapture(path4)
</code></pre>
<p>similarly I also wanted to create frame objects to read frames like</p>
<pre><code>ret,frame0=cap0.read()
ret,frame1=cap1.read()
.
.
ret,frameN=capn.read()
</code></pre>
<p>I tried using for loop on the lists where the paths are stored but every time only one path is read and frames are stored for that particular video only.I have seen in many forums it is possible to create multiple capture objects in C++ but not in python in dynamic scenario where number of videos are not known before hand.
This is my code until now</p>
<pre><code>frames=[]
for path in videoList:
indices=[]
cap = cv2.VideoCapture(path)
while(cap.isOpened()):
ret,frame=cap.read()
if not ret:
break
indices.append(cap.get(1))
frames.append(indices)
cap.release()
cv2.destroyAllWindows()
</code></pre>
| -1 | 2016-09-26T09:58:33Z | 39,702,933 | <p>I'm not a python pgogrammer, but probably the solution is something like:</p>
<pre><code>frames=[]
caps=[]
for path in videoList:
indices=[]
caps.append (cv2.VideoCapture(path) )
for cap in caps:
frames=[]
if(cap.isOpened()):
ret,frame=cap.read()
frames.append(frame)
else
// no frame for this device could be captured. What to do?
// now "frames" holds your captured images.
</code></pre>
| 1 | 2016-09-26T12:32:34Z | [
"python",
"opencv",
"video",
"video-capture",
"video-processing"
]
|
Access denied to Azure storage | 39,699,809 | <p>I am storing images on Azure storage. BUt after storing images when I am trying to access bob url it is giving me access denied error. </p>
<p>My code : </p>
<pre><code>block_blob_service = BlockBlobService(account_name=ACCOUNT_NAME, account_key=ACCOUNT_KEY)
block_blob_service.create_container('organisation', public_access=PublicAccess.Container)
org = Organisation.objects.get(pk=34)
image = download_image(org.org_logo.url)
bob = block_blob_service.create_blob_from_path(
'organisation',
org.name,
image,
content_settings=ContentSettings(content_type='image/png')
)
image_url = block_blob_service.make_blob_url('organisation', org.name) **# same url is accessible via browser but not from script**
org.org_logo = image_url **# this is giving error of access denied**
org.save()
</code></pre>
<p>I am not sure but I think need to edit CORS settings of my storage , but I am not able to figure out where to edit them from azure portal. If there is something else wrong then also please let me know .</p>
<p><strong>EDIT :</strong> </p>
<p><strong>ERROR -</strong> SuspiciousOperation: Attempted access to 'blob url' denied.</p>
| 0 | 2016-09-26T09:59:19Z | 39,721,864 | <p>Per my experience, the reason for this issue may be that your code does some suspicious access to the on-premises site directory. You could test whether you could get the image URL by running the following code. If you could see the image URL in the console, that indicates you have the access to your azure storage. If not, please let me know.</p>
<pre class="lang-html prettyprint-override"><code>from azure.storage.blob import BlockBlobService
from azure.storage.blob import PublicAccess
from azure.storage.blob import ContentSettings
block_blob_service = BlockBlobService(account_name=ACCOUNT_NAME, account_key=ACCOUNT_KEY)
block_blob_service.create_container('newcontainer', public_access=PublicAccess.Container)
block_blob_service.create_blob_from_path(
'newcontainer',
'myblockblob',
'C:\myimages\image.jpg',
content_settings=ContentSettings(content_type='image/jpg')
)
image_url = block_blob_service.make_blob_url('newcontainer', "myblockblob")
print(image_url);
</code></pre>
<p>
You may could find what the problem is by the following URLs.</p>
<p><a href="http://stackoverflow.com/questions/20747001/django-suspiciousoperation-at-upload-when-uploading-a-file">Django SuspiciousOperation at /upload/ when uploading a file</a></p>
<p><a href="http://stackoverflow.com/questions/18647182/django-suspicious-operation-on-image-upload">django suspicious operation on image upload</a></p>
<p>Hope it helps. Any concerns, please feel free to let me know.</p>
| 0 | 2016-09-27T10:06:59Z | [
"python",
"django",
"azure",
"windows-azure-storage",
"azure-storage-blobs"
]
|
Adding results from a for loop to a dictionary , and then appending to a list | 39,699,827 | <p>I'm aware that this is really simply , but I'm struggling with this. Basically I want to add the results of a for loop inside a dicionary, so i can work the results on another function, which i can print the desired field based on the key value, </p>
<p>Example:</p>
<pre><code> i = 0
b = 0
cc = []
while True:
i += 1
b += 1
abc = {b: i}
cc.append(abc)
if i == 3:
break
</code></pre>
<p>Result : <code>[{1: 1}, {2: 2}, {3: 3}]</code></p>
<p>So, the expected result would be <code>[{"1": 1, "2": 2, "3": 3}]</code></p>
<p>This is for python 2.7</p>
| 0 | 2016-09-26T09:59:55Z | 39,699,942 | <p>Based on your expected outcome, I would suggest this:</p>
<pre><code>cc = []
for i in range(0,3):
cc.append({str(i): i})
</code></pre>
<p>But please note that you do <strong>NOT</strong> get a dictionary at the end of this loop... What you get is a list of dictionaries, each dictionary featuring only one key-value pair... <code>[{'1':1},{'2':2}]</code> is not the same as <code>{'1':1, '2':2}</code> and you will probably have problems using such a list of dictionaries.</p>
<p>So my guess is you want something more along the lines of this:</p>
<pre><code>cc = dict()
for i in range(0,3):
cc[str(i)] = i
</code></pre>
<p>Please tell me if I misunderstood your problem or if you need more explanation for the solutions.</p>
| 4 | 2016-09-26T10:05:28Z | [
"python",
"python-2.7"
]
|
Python: extract text from string | 39,699,853 | <p>I try to extract text from url request, but not all dict contain key with text, and when I try to use <code>{k: v[0] for k, v in parse_qs(str).items()}</code> to urls, I lose a lot of requests, so I try <code>str = urllib.unquote(u[0])</code>.
After that I get strings like</p>
<pre><code>ÑмоÑÑеÑÑ Ð»ÑÑÑе не бÑваеÑ&clid=1955453&win=176
Jade+Jantzen&ie=utf-8&oe=utf-8&gws_rd=cr&ei=FQB0V9WbIoahsAH5zZGACg
как+ÑкÑÑÑÑ+лопоÑÑ
оÑÑÑ&newwindow=1&biw=1366&bih=657&source=lnms&sa=X&sqi=2&pjf=1&ved=0ahUKEwju5cPJy83NAhUPKywKHVHXBesQ_AUICygA&dpr=1
ÑмоÑÑеÑÑ Ð»ÑÑÑе не бÑваеÑ&clid=1955453&win=176
2&clid=1976874&win=85&msid=1467228292.64946.22901.24595&text=как вÑбÑаÑÑ ÑмаÑÑÑон
маÑкаи гейла&lr=10750&clid=1985551-210&win=213
</code></pre>
<p>And I want to get</p>
<pre><code>ÑмоÑÑеÑÑ Ð»ÑÑÑе не бÑваеÑ
Jade Jantzen
как ÑкÑÑÑÑ Ð»Ð¾Ð¿Ð¾ÑÑ
оÑÑÑ
ÑмоÑÑеÑÑ Ð»ÑÑÑе не бÑваеÑ
как вÑбÑаÑÑ ÑмаÑÑÑон
маÑкаи гейла
</code></pre>
<p>Is any way to extract that?</p>
| 0 | 2016-09-26T10:01:27Z | 39,700,043 | <p>Just split by <code>&</code> and take the first part:</p>
<pre><code>txt = urllib.unquote(u[0]).split("&")[0]
</code></pre>
<p>And don't use <code>str</code> as a variable name - it's a built-in type name in Python.</p>
<p><strong>EDIT:</strong>
Unfortunatelly this <code>2&clid=1976874&win=85&msid=1467228292.64946.22901.24595&text=как вÑбÑаÑÑ ÑмаÑÑÑон</code> line has a different pattern than the others. There's no common way to handle this one together with the others. I was tempted to use regex to match Cyrillic characters but <code>Jade Jantzen</code> wouldn't match. So for this one line, where the desired text is at the end, something like</p>
<pre><code>txt = urllib.unquote(u[0]).split("=")[-1]
</code></pre>
<p>would work. Still you didn't provide any actual criteria for desired text. As humans we can say how to transform what you get into what you want from this specific sample. But without clear rules of what to match, we can't provide a complete solution.</p>
<p><em>I'm aware that some (again some) of the lines have <code>"+"</code> in place of <code>" "</code>. This can possibly be solved with <code>.replace("+", " ")</code>.</em></p>
| 1 | 2016-09-26T10:09:48Z | [
"python",
"regex",
"urlparse"
]
|
Excel cell values filled with 0 | 39,699,960 | <p>The part of code shown below </p>
<pre><code>import collections
import csv
import sys
with open("321.csv","r") as f:
cr = csv.reader(f,delimiter=",")
d=collections.defaultdict(lambda : list())
header=next(cr) # read title. Retrieve the next item from the iterator by calling its __next__() method.
for r in cr:
d[r[0]].append(r[1]) # fill dict
with open("sorted output.csv","w") as f:
cr = csv.writer(f,sys.stdout, lineterminator='\n')
od = collections.OrderedDict(sorted(d.items()))#sort items based on dictionary key value
for k,v in od.items(): #The method items() returns a list of dict's (key, value) tuple pairs
v = [ord(i) for i in v] # convert letters into numbers
cr.writerow(v)
</code></pre>
<p>Gives me this output:</p>
<p><a href="http://i.stack.imgur.com/N4OhQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/N4OhQ.png" alt="enter image description here"></a></p>
<p>I want to fill all empty cells in the region: (A1::X30) with 0s.(Each time the cells that should be filled with 0s are defined by the length of the largest row. e.g. if the largest row had elements up until column Y the empty cells that should be filled with 0s would be in the region (A1::Y30)) </p>
<p>Can you help?</p>
| 0 | 2016-09-26T10:06:11Z | 39,700,331 | <p>I have not tested but perhaps this?</p>
<pre><code>import collections
import csv
import sys
max_len = 0
with open("321.csv","r") as f:
cr = csv.reader(f,delimiter=",")
d=collections.defaultdict(lambda : list())
header=next(cr) # read title. Retrieve the next item from the iterator by calling its __next__() method.
for r in cr:
d[r[0]].append(r[1]) # fill dict
max_len = max(len(d[r[0]]), max_len)
with open("sorted output.csv","w") as f:
cr = csv.writer(f,sys.stdout, lineterminator='\n')
od = collections.OrderedDict(sorted(d.items()))#sort items based on dictionary key value
for k,v in od.items(): #The method items() returns a list of dict's (key, value) tuple pairs
v = [ord(i) for i in v] + [0]*(max_len - len(v)) # convert letters into numbers
cr.writerow(v)
</code></pre>
| 2 | 2016-09-26T10:23:39Z | [
"python",
"excel"
]
|
Excel cell values filled with 0 | 39,699,960 | <p>The part of code shown below </p>
<pre><code>import collections
import csv
import sys
with open("321.csv","r") as f:
cr = csv.reader(f,delimiter=",")
d=collections.defaultdict(lambda : list())
header=next(cr) # read title. Retrieve the next item from the iterator by calling its __next__() method.
for r in cr:
d[r[0]].append(r[1]) # fill dict
with open("sorted output.csv","w") as f:
cr = csv.writer(f,sys.stdout, lineterminator='\n')
od = collections.OrderedDict(sorted(d.items()))#sort items based on dictionary key value
for k,v in od.items(): #The method items() returns a list of dict's (key, value) tuple pairs
v = [ord(i) for i in v] # convert letters into numbers
cr.writerow(v)
</code></pre>
<p>Gives me this output:</p>
<p><a href="http://i.stack.imgur.com/N4OhQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/N4OhQ.png" alt="enter image description here"></a></p>
<p>I want to fill all empty cells in the region: (A1::X30) with 0s.(Each time the cells that should be filled with 0s are defined by the length of the largest row. e.g. if the largest row had elements up until column Y the empty cells that should be filled with 0s would be in the region (A1::Y30)) </p>
<p>Can you help?</p>
| 0 | 2016-09-26T10:06:11Z | 39,700,830 | <p>I'm not quite sure if I understand your question correctly. Here is an attempt:</p>
<p>To create a xls file that has just 0's an alternative could be to use pandas and numpy as follows:</p>
<pre><code>import pandas as pd
import numpy as np
import io
number_of_rows = 30
number_of_columns = 24
# Create a dataframe of 0's in the dimension you define above
df = pd.DataFrame(np.array([np.zeros(number_of_columns) for i in range(number_of_rows)]))
# Give out as xls file
df.to_excel('output.xls', index=False)
</code></pre>
<p>If you want to have certain cells with non-zeros and the rest with zeros, you can easily overwrite (before df.to_excle) by using something like the following with a function of your choice:</p>
<pre><code>df.set_values(row,column,value)
</code></pre>
<p>Hope that helped a little bit.</p>
| 1 | 2016-09-26T10:47:57Z | [
"python",
"excel"
]
|
xml minidom - get the full content of childnodes text | 39,700,025 | <p>I have a Test.xml file as:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<SetupConf>
<LocSetup>
<Src>
<Dir1>C:\User1\test1</Dir1>
<Dir2>C:\User2\log</Dir2>
<Dir3>D:\Users\Checkup</Dir3>
<Dir4>D:\Work1</Dir4>
<Dir5>E:\job1</Dir5>
</Src>
</LocSetup>
</SetupConf>
</code></pre>
<p>Where node depends on user input. In "Dir" node it may be 1,2,5,10 dir structure defined. As per requirement I am able to extract data from the Test.xml with help of @Padraic Cunningham using below Python code:</p>
<pre><code>from xml.dom import minidom
from StringIO import StringIO
dom = minidom.parse('Test.xml')
Src = dom.getElementsByTagName('Src')
output = ", ".join([a.childNodes[0].nodeValue for node in Src for a in node.getElementsByTagName('Dir')])
print [output]
</code></pre>
<p>And getting the output: </p>
<pre><code>C:\User1\test1, C:\User2\log, D:\Users\Checkup, D:\Work1, E:\job1
</code></pre>
<p>But the expected output is:</p>
<pre><code>['C:\\User1\\test1', 'C:\\User2\\log', 'D:\\Users\\Checkup', 'D:\\Work1', 'E:\\job1']
</code></pre>
| -1 | 2016-09-26T10:08:59Z | 39,701,330 | <p>Well it's solved by myself:</p>
<pre><code>from xml.dom import minidom
DOMTree = minidom.parse('Test0001.xml')
dom = DOMTree.documentElement
Src = dom.getElementsByTagName('Src')
for node in Src:
output = [a.childNodes[0].nodeValue for a in node.getElementsByTagName('Dir')]
print output
</code></pre>
<hr>
<p>And getting output:
[u'C:\User1\test1', u'C:\User2\log', u'D:\Users\Checkup', u'D:\Work1', u'E:\job1']</p>
<hr>
<p>I am sure there is more simple another way .. please let me know.. Thanks in adv.</p>
| 0 | 2016-09-26T11:13:25Z | [
"python",
"xml"
]
|
For Loops in Python (Output Smallest Input) | 39,700,100 | <p>Okay so I am practicing for loops in Python and I was wondering how could I make a user input 10 intergers then it would output the smallest one. I would know how to do this with a while loop for example: </p>
<pre><code>Smallest = 0
count = 0
while count < 10:
Number = int(input("Enter a number >> "))
if Number < Smallest:
Smallest = Number
count = count + 1
print("{0} is the biggest value you have entered".format(Smallest))
</code></pre>
<p>But how do I do it in a for loop format? Here's what I have so far:</p>
<pre><code>for i in range(10):
Number = int(input("Enter a Number >> "))
if Number < Smallest:
Smallest = Number
print("{0} is the smallest value you have entered.".format(Smallest))
</code></pre>
| 1 | 2016-09-26T10:12:56Z | 39,700,199 | <p>What you have there, other than the fact you should initialise <code>Smallest</code>, is equivalent to the solution using your <code>while</code> statement.</p>
<p>So, assuming the <code>while</code> variant is considered correct, the <code>for</code> variant you have will suffice.</p>
<p>The reason I qualify it is because initialising <code>Smallest</code> to zero is actually the <em>wrong</em> thing to do. If your ten numbers are all greater than twenty (for example), <code>Smallest</code> will remain at zero, giving you the wrong answer.</p>
<p>One way to fix this (in both variants) is to change your <code>if</code> statement to:</p>
<pre><code>if i == 0 or Number < Smallest:
</code></pre>
<p>which will set <code>Smallest</code> first time through the loop regardless (though it should be <code>count</code> in the <code>while</code> variant since that's using a different loop control variable).</p>
<hr>
<p>Of course, as you learn more and more about the language, you'll come across the concept of things that are more "Pythonic" than others. An example of this is the rather more succinct:</p>
<pre><code>Smallest = min(int(input("Enter a Number >> ")) for i in range(10))
</code></pre>
<p>which removes the need totally for an explicit check-and-replace strategy (that's still done, but under the covers of the <code>min</code> function).</p>
| 2 | 2016-09-26T10:17:20Z | [
"python",
"loops",
"for-loop"
]
|
For Loops in Python (Output Smallest Input) | 39,700,100 | <p>Okay so I am practicing for loops in Python and I was wondering how could I make a user input 10 intergers then it would output the smallest one. I would know how to do this with a while loop for example: </p>
<pre><code>Smallest = 0
count = 0
while count < 10:
Number = int(input("Enter a number >> "))
if Number < Smallest:
Smallest = Number
count = count + 1
print("{0} is the biggest value you have entered".format(Smallest))
</code></pre>
<p>But how do I do it in a for loop format? Here's what I have so far:</p>
<pre><code>for i in range(10):
Number = int(input("Enter a Number >> "))
if Number < Smallest:
Smallest = Number
print("{0} is the smallest value you have entered.".format(Smallest))
</code></pre>
| 1 | 2016-09-26T10:12:56Z | 39,700,256 | <p>If you want to get the smallest of the input numbers, you need to start with a minimum a bit bigger than 0... and that is a problem you have with your while loop. It will only work if the user inputs at least one negative number, else it will return <code>0</code>.</p>
<p>Here is what I suggest:</p>
<pre><code>smallest = float("inf")
for i in range(10):
number = int(input("Enter a Number >> "))
if number < smallest:
smallest = number
print("{0} is the smallest value you have entered.".format(smallest))
</code></pre>
<p>Note that I did not capitalize the variables, because to me it makes them look like classes. ^^</p>
| 1 | 2016-09-26T10:19:57Z | [
"python",
"loops",
"for-loop"
]
|
For Loops in Python (Output Smallest Input) | 39,700,100 | <p>Okay so I am practicing for loops in Python and I was wondering how could I make a user input 10 intergers then it would output the smallest one. I would know how to do this with a while loop for example: </p>
<pre><code>Smallest = 0
count = 0
while count < 10:
Number = int(input("Enter a number >> "))
if Number < Smallest:
Smallest = Number
count = count + 1
print("{0} is the biggest value you have entered".format(Smallest))
</code></pre>
<p>But how do I do it in a for loop format? Here's what I have so far:</p>
<pre><code>for i in range(10):
Number = int(input("Enter a Number >> "))
if Number < Smallest:
Smallest = Number
print("{0} is the smallest value you have entered.".format(Smallest))
</code></pre>
| 1 | 2016-09-26T10:12:56Z | 39,700,332 | <p>Initialize your Smallest variable and all will works!</p>
<pre><code>Smallest = int(input("Enter a Number >> "))
for i in range(9):
Number = int(input("Enter a Number >> "))
if Number < Smallest:
Smallest = Number
print("{0} is the smallest value you have entered.".format(Smallest))
</code></pre>
| 3 | 2016-09-26T10:23:40Z | [
"python",
"loops",
"for-loop"
]
|
For Loops in Python (Output Smallest Input) | 39,700,100 | <p>Okay so I am practicing for loops in Python and I was wondering how could I make a user input 10 intergers then it would output the smallest one. I would know how to do this with a while loop for example: </p>
<pre><code>Smallest = 0
count = 0
while count < 10:
Number = int(input("Enter a number >> "))
if Number < Smallest:
Smallest = Number
count = count + 1
print("{0} is the biggest value you have entered".format(Smallest))
</code></pre>
<p>But how do I do it in a for loop format? Here's what I have so far:</p>
<pre><code>for i in range(10):
Number = int(input("Enter a Number >> "))
if Number < Smallest:
Smallest = Number
print("{0} is the smallest value you have entered.".format(Smallest))
</code></pre>
| 1 | 2016-09-26T10:12:56Z | 39,700,631 | <p>Since you are finding the Smallest values out of the input values from the user it is good practice to initially initialize the Smallest variable as maximum possible integer as below.</p>
<pre><code>import sys
Smallest = sys.maxint
</code></pre>
<p>Then the rest of your loop will work as properly as it is.</p>
| 0 | 2016-09-26T10:38:01Z | [
"python",
"loops",
"for-loop"
]
|
Python: subprocess Popen requires to be joined? | 39,700,122 | <p>i have a daemon running which gets command and executes it by:</p>
<pre><code>subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
</code></pre>
<p>I never do anything with it afterwards, no <code>wait()</code>, no <code>communicate()</code></p>
<p>is that okay to do so?<br>
or are joining of the process required? </p>
<p>is there a similar thing to <code>threading.deamon=True</code> for <code>subprocess.Popen</code>? </p>
| 0 | 2016-09-26T10:14:12Z | 39,700,493 | <p>Since you set <code>stdout=subprocess.PIPE, stderr=subprocess.PIPE</code>, and if you want to get the stdout, you can do this:</p>
<pre><code>p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for line in p.stdout:
# do something here
#...
</code></pre>
<p>As you say the <code>cmd</code> is executed as a daemon, I think daemon process should not be run in this way. Since once your python process exit with error, the daemon process would exited and your data will lost.</p>
<p>And if you run other process by subprocess.Popen(), such as mysql, linux comands etc, it is ok to do so. But you should know the process status(the return code), you should check the status of the process by call <code>poll()</code> or <code>wait()</code>. For more information, see <a href="https://docs.python.org/2.7/library/subprocess.html?highlight=subprocess.popen" rel="nofollow">docs of subproces.Popen</a>.</p>
| 0 | 2016-09-26T10:31:20Z | [
"python",
"subprocess"
]
|
How can I get Python to plugin my password and Username for an .exe file it opened | 39,700,155 | <p>Hey guys I'm new to programming and I would appreciate some help. My program can open an application I have but to enter the application it requires a password and username which I don't know how to make my program plug in automatically.</p>
<pre><code>os.system('"C:\\abc\\123\\Filepath\\File.exe"')
</code></pre>
<p>After the code opens the program of the .exe file how do I make it to where it can than automatically plug in the username and password for the application.</p>
<p>Please and Thank you</p>
| 0 | 2016-09-26T10:15:20Z | 39,700,745 | <p>What you need is Pywinauto, which can make simple windows operations automatically. Please have a look at below Pywinauto website, there is an example to open Notepad and input "Hello World" automatically.
<a href="https://pywinauto.github.io/" rel="nofollow">https://pywinauto.github.io/</a></p>
<p>I have another example to use Pywinauto to open putty application and connect to a remote Linux server, then input password to login, and run an Linux command.</p>
<pre><code>from pywinauto.application import Application
import time
app = Application ().Start (cmd_line=u'putty -ssh user_name@10.70.15.175')
putty = app.PuTTY
putty.Wait ('ready')
time.sleep (1)
putty.TypeKeys ("password")
putty.TypeKeys ("{ENTER}")
time.sleep (1)
putty.TypeKeys ("ls")
putty.TypeKeys ("{ENTER}")
</code></pre>
<p>I use Python 2.7 and run the above Python code on Windows successfully.</p>
<p>You may need to install SWAPY (<a href="https://github.com/pywinauto/SWAPY" rel="nofollow">https://github.com/pywinauto/SWAPY</a>) to get the Python code for automating your own "File.exe". </p>
| 1 | 2016-09-26T10:43:43Z | [
"python",
"passwords",
"username",
"os.system"
]
|
Django save Base64 image | 39,700,158 | <p>I am accepting a POST from iOS and my django code is</p>
<pre><code> image =self.request.DATA.get('image')
image_data =base64.b64decode(image)
img=ContentFile(image_data,'myImage.jpg')
</code></pre>
<p>but when i save it in django it is currupted any ideas why</p>
<p>Here is my base64image</p>
<pre><code>\/9j\/4AAQSkZJRgABAQAAAAAAAAD\/4QCARXhpZgAATU0AKgAAAAgABQESAAMAAAABAAEAAAEaAAUAAAABAAAASgEbAAUAAAABAAAAUgEoAAMAAAABAAIAAIdpAAQAAAABAAAAWgAAAAAAAAAAAAAAAQAAAAAAAAABAAKgAgAEAAAAAQAAAnSgAwAEAAAAAQAAAQYAAAAA\/+0AOFBob3Rvc2hvcCAzLjAAOEJJTQQEAAAAAAAAOEJJTQQlAAAAAAAQ1B2M2Y8AsgTpgAmY7PhCfv\/AABEIAQYCdAMBIgACEQEDEQH\/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv\/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8\/T19vf4+fr\/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv\/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8\/T19vf4+fr\/2wBDABYWFhYWFiYWFiY2JiYmNkk2NjY2SVxJSUlJSVxvXFxcXFxcb29vb29vb2+GhoaGhoacnJycnK+vr6+vr6+vr6\/\/2wBDARsdHS0pLUwpKUy3fGZ8t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7f\/3QAEACj\/2gAMAwEAAhEDEQA\/AN+iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAClpKWgD\/\/Q36KKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKWkpaAP\/9HfooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigApaSloA\/\/0t+iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAClpKWgD\/\/T36KKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKWkpaAP\/9TfooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiipUG8FT+BoAioo+tTSqPvjoaAIaKKKAAAk4FSOAgCDr3qWFcDce9RtG+4nGaAIqKUqw6g0lABRRRQBIrJja4\/Gh028jkVHViHlSD0oAr0VL5LZ9qPJfOOKACNdykHtUVWtm2MqvJqqQR14oAKKKdj5A3vigBFUsdoqR8J8q9e5psfDinTDD59aAIqKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigApaSloA\/\/V36KKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACnBGYZAptOVmX7poAXy39KlijZW3NxSCc45FHn+1ACtDlsg4zUiLtXaeaaJkPXih5QOF5NACmJD2pRGg6Cq5lc96TzH9aALlFUSSepzSUAX6Qqp6iqYdx0NWY33jnqKAIJI9hyOlR1eZQwwaYsSrz1oAhSItyeBVkAKMCkZlUZNV2mY\/d4oAskgdTQGU9DmqPXrRQBfpMg+9UiSepzSdOlAF7avpQVUjBHFVPMf1o8x\/WgCwsSqcimSRszbhUXmv60vnPQAGJx2qPpwakMrnvUdABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUtJS0Af\/1t+iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACnKxQ5FNooAvjnmmSPsXPekiOUFMn6CgCAkk5NJRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUtJS0Af\/9ffooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAoooAyQPWgC3F9wU2b7n41KAAMCmS\/cNAFSiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigApaSloA\/\/Q36KKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKALqtuUGmTH5KdH9wVHP0AoAr0UUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFLSUtAH\/\/R36KKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKO9AF1BhAPaoJ\/vAVZqCccBqAK9FFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABS0lLQB\/\/S36KKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKcg3OBTakjZUyT1oAt01xlCKj85fenebHjrQBUooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKWkpaAP\/09+iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAClpKWgD\/\/U36KKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKWkpaAP\/9XfooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigApaSloA\/\/1t+iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAClpKWgD\/\/X36KWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigBKKWigAooooA\/9k= Ci5/f2lt/9yu3 Y8v2cMpb1/DSJbz5i9R2NLwfLrWbw m T8I8////////SvMAbAAAABB0Uk5T////////////////////AOAjXRkAAACYSURBVHjaLI8JDgMgCAQ5BVG3//9t0XYTE2Y5BPq0IGpwtxtTP4G5IFNMnmEKuCopPKUN8VTNpEylNgmCxjZa2c1kafpHSvMkX6sWe7PTkwRX1dY7gdyMRHZdZ98CF6NZT2ecMVaL9tmzTtMYcwbP y3XeTgZkF5s1OSHwRzo1fkILgWC5R0X4BHYu7t/136wO71DbvwVYADUkQegpokSjwAAAABJRU5ErkJggg==enter code here
</code></pre>
| 1 | 2016-09-26T10:15:29Z | 39,700,328 | <pre><code># Python 2.7
f = open("yourfile.png", "wb")
f.write(your_base_string.decode('base64'))
f.close()
# or
with open("yourfile.png", "wb") as f:
fhfwrite(imgData.decode('base64'))
</code></pre>
| 1 | 2016-09-26T10:23:30Z | [
"python",
"django",
"base64"
]
|
Django 1.8 startup delay troubleshooting | 39,700,254 | <p>I'm trying to discover the cause of delays in Django 1.8 startup, especially, but not only, when run in a debugger (WingIDE 5 and 6 in my case).</p>
<p>Minimal test case: the Django 1.8 tutorial "poll" example, completed just to the first point where 'manage.py runserver' works. All default configuration, using SQLite. Python 3.5.2 with Django 1.8.14, in a fresh venv.</p>
<p>From the command line, on Linux (Mint 18) and Windows (7-64), this may run as fast as 2 seconds to reach the "Starting development server" message. But on Windows it sometimes takes 10+ secs. And in the debugger on both machines, it can take 40 secs.</p>
<p>One specific issue: By placing print statements at begin and end of <code>django/__init__.py setup()</code>, I note that this function is called twice before the "Starting... " message, and again after that message; the first two times contribute half the delay each. This suggests that django is getting started three times. What is the purpose of that, or does it indicate a problem? </p>
<p>(I did find that I could get rid of one of the first two startup()s using the runserver --noreload option. But why does it happen in the first place? And there's still a startup() call after the "Starting..." message.)</p>
<p>To summarize the question:
-- Any insights into what might be responsible for the delay?
-- Why does django need to start three times? (Or twice, even with --noreload).</p>
| 0 | 2016-09-26T10:19:51Z | 39,736,367 | <p>A partial answer.</p>
<p>After some time with WingIDE IDE's debugger, and some profiling with cProfile, I have located the main CPU hogging issue. </p>
<p>During initial django startup there's a cascade of imports, in which module validators.py prepares some compiled regular expressions for later use. One in particular, URLValidator.regex, is complicated and also involves five instances of the unicode character set (variable ul). This causes re.compile to perform a large amount of processing, notably in sre_compile.py _optimize_charset() and in large number of calls to the fixup() function.</p>
<p>As it happens, the particular combination of calls and data structure apparently hit a special slowness in WingIDE 6.0b2 debugger. It's considerably faster in WingIDE 5.1 debugger (though still much slower than when run from command line). Not sure why yet, but Wingware is looking into it.</p>
<p>This doesn't explain the occasional slowness when launched from the command line on Windows; there's an outside change this was waiting for a sleeping drive to awaken. Still observing.</p>
| 0 | 2016-09-28T00:47:06Z | [
"python",
"django"
]
|
Search Keys and Replace Values in XML | 39,700,390 | <p>I have an xml file which looks like below</p>
<pre><code><name>abcdefg</name>
<value>123456</value>
</code></pre>
<p>I am trying to write a script using sed to search for the tag "abcdefg" and then <strong>replace the corresponding value</strong> "123456" but unfortunately I am not able to find a logic to achieve above.
Need help!</p>
| 0 | 2016-09-26T10:26:53Z | 39,700,635 | <p>Sample data used:</p>
<pre><code> cat key
<name>abcdaaefg</name>
<value>123456</value>
<name>abcdefg</name>
<value>123456</value>
<name>abcdaaefg</name>
<value>123456</value>
</code></pre>
<p><code>sed</code> solution:</p>
<pre><code> sed '/abcdefg/!b;n;c<value>OLA<value>' key
<name>abcdaaefg</name>
<value>123456</value>
<name>abcdefg</name>
<value>OLA<value>
<name>abcdaaefg</name>
<value>123456</value>
</code></pre>
<p>For doing changes in file. </p>
<pre><code>sed -i.bak '/abcdefg/!b;n;c<value>OLA<value>' key
</code></pre>
<p><code>awk</code> Solution:</p>
<pre><code>awk '/abcdefg/ {print $0;getline;sub(/>.*</,">ola<")} {print $0}' key
<name>abcdaaefg</name>
<value>123456</value>
<name>abcdefg</name>
<value>ola</value>
<name>abcdaaefg</name>
<value>123456</value>
</code></pre>
<p>Search for a line containing <code>abcdefg</code> and then do following actions:<br>
1. print that line,<br>
2.move to next line and replace the value inside html tag to something else. Here , I have replaced <code>123456</code> with <code>ola</code>. </p>
| 2 | 2016-09-26T10:38:12Z | [
"python",
"xml",
"shell",
"replace",
"sed"
]
|
Search Keys and Replace Values in XML | 39,700,390 | <p>I have an xml file which looks like below</p>
<pre><code><name>abcdefg</name>
<value>123456</value>
</code></pre>
<p>I am trying to write a script using sed to search for the tag "abcdefg" and then <strong>replace the corresponding value</strong> "123456" but unfortunately I am not able to find a logic to achieve above.
Need help!</p>
| 0 | 2016-09-26T10:26:53Z | 39,710,159 | <p>Whenever you have tag->value pairs in your data it's a good idea to create a tag->value array in your code:</p>
<pre><code>$ awk -F'[<>]' '{tag=$2; v[tag]=$3} tag=="value" && v["name"]=="abcdefg" {sub(/>.*</,">blahblah<")} 1' file
<name>abcdefg</name>
<value>blahblah</value>
</code></pre>
| 0 | 2016-09-26T18:46:01Z | [
"python",
"xml",
"shell",
"replace",
"sed"
]
|
Search Keys and Replace Values in XML | 39,700,390 | <p>I have an xml file which looks like below</p>
<pre><code><name>abcdefg</name>
<value>123456</value>
</code></pre>
<p>I am trying to write a script using sed to search for the tag "abcdefg" and then <strong>replace the corresponding value</strong> "123456" but unfortunately I am not able to find a logic to achieve above.
Need help!</p>
| 0 | 2016-09-26T10:26:53Z | 39,710,416 | <p>Use an XML-aware tool. This will make your approach far more robust: It means that tiny changes in the textual description (like added or removed newlines, or extra attributes added to a preexisting element) won't break your script.</p>
<p>Assuming that your input's structure looks like this (with being under a single parent item, here called <code>item</code>, defining the relationship between a <code>name</code> and a <code>value</code>):</p>
<pre><code><config>
<item><name>abcdef</name><value>123456</value></item>
<item><name>fedcba</name><value>654321</value></item>
</config>
</code></pre>
<p>...you can edit it like so:</p>
<pre><code> # edit the value under an item having name "abcdef"
xmlstarlet ed -u '//item[name="abcdef"]/value' -v "new-value"
</code></pre>
<hr>
<p>If instead it's like this (with ordering between name/value pairs describing their relationship):</p>
<pre><code><config>
<name>abcdef</name><value>123456</value>
<name>fedcba</name><value>654321</value>
</config>
</code></pre>
<p>...then you can edit it like so:</p>
<pre><code># update the value immediately following a name of "abcdef"
xmlstarlet ed -u '//name[. = "abcdef"]/following-sibling::value[1]' -v new-value
</code></pre>
| 0 | 2016-09-26T19:02:24Z | [
"python",
"xml",
"shell",
"replace",
"sed"
]
|
regex to find all words after specific word? | 39,700,416 | <p>I have a string like below:</p>
<pre><code>Features: -Includes hanging accessories. -Artist: William-Adolphe Bouguereau. -Made with 100pct cotton canvas. -100pct Anti-shrink pine wood bars and Epson anti-fade ultra chrome inks. -100pct Hand-made and inspected in the U.S.A. -Orientation: Horizontal. **Subject: -Figures/Nautical and beach.** Gender: -Unisex/Both. Size: -Mini 17'' and under/Small 18''-24''/Medium 25''-32''/Large 33''-40''/Oversized 41'' and above. Style: -Fine art. Color: -Blue. Country of Manufacture: -United States. Product Type: -Print of painting. Region: -Europe. Primary Art Material: -Canvas. Dimensions: -8'' H x 12'' W x 0.75'' D: 0.72 lb. -12'' H x 18'' W x 0.75'' D: 1.14 lbs. -12'' H x 18'' W x 1.5'' D: 2.45 lbs. -18'' H x 26'' W x 0.75'' D: 1.44 lbs. Paintings Prints Tori White Wildon Photography Photos Posters Abstract Black D cor Designs Framed Hazelwood Hokku Home Landscape Oil Accent 075 12 15 18 26 40 60 8 D H W x 1 1017 1824 2532 holidays, christmas gift gifts for girls boys
</code></pre>
<p>I have to find the words after particular word. </p>
<p>I want to extract the words after the word <code>"Subject"</code> in above example.</p>
<p>The output should be like below:</p>
<pre><code>Subject: -Figures/Nautical and beach.
</code></pre>
<p>I tried below regex:</p>
<pre><code>re.compile('(?<=subject)(.{30}(?:\s|.))',re.I)
</code></pre>
<p>But there is not fixed number of words after subject keyword to specify so I can't specify exact number of words.</p>
<p>How do I stop at "peroid" or space.There is no specific stopping criterion.</p>
| 0 | 2016-09-26T10:28:06Z | 39,700,520 | <p>Your <code>(?<=subject)(.{30}(?:\s|.))</code> regex asserts the position after <code>subject</code>. then grabs 30 characters other than a linebreak symbol and then matches either a whitespace or any character but a linebreak symbol. This does not really fit your requirements as the substring can be of any length.</p>
<p>You may use alternation based regex with a capturing group:</p>
<pre><code>subject:\s*([^.]+|\S+)
</code></pre>
<p>See the <a href="https://regex101.com/r/aC3pC1/1" rel="nofollow">regex demo</a></p>
<p><strong>Details</strong>:</p>
<ul>
<li><code>subject:</code> - literal <code>subject:</code> string</li>
<li><code>\s*</code> - 0+ whitespaces</li>
<li><code>([^.]+|\S+)</code> - Group 1 capturing 1 or more non-period symbols or 1+ non-whitespace symbols</li>
</ul>
<p><strong>Note</strong>: the order of the alternatives <em>matters</em> here since <code>[^.]+</code> matches spaces, and <code>\S+</code> does not. If the substring after <code>\s*</code> starts with a dot, the <code>\S+</code> will match that substring up to a whitespace.</p>
<p><a href="https://ideone.com/JRe3y9" rel="nofollow">Python demo</a>:</p>
<pre><code>import re
p = re.compile(r'subject:\s*([^.]+|\S+)', re.IGNORECASE)
s = "Features: -Includes hanging accessories. -Artist: William-Adolphe Bouguereau. -Made with 100pct cotton canvas. -100pct Anti-shrink pine wood bars and Epson anti-fade ultra chrome inks. -100pct Hand-made and inspected in the U.S.A. -Orientation: Horizontal. **Subject: -Figures/Nautical and beach.** Gender: -Unisex/Both. Size: -Mini 17'' and under/Small 18''-24''/Medium 25''-32''/Large 33''-40''/Oversized 41'' and above. Style: -Fine art. Color: -Blue. Country of Manufacture: -United States. Product Type: -Print of painting. Region: -Europe. Primary Art Material: -Canvas. Dimensions: -8'' H x 12'' W x 0.75'' D: 0.72 lb. -12'' H x 18'' W x 0.75'' D: 1.14 lbs. -12'' H x 18'' W x 1.5'' D: 2.45 lbs. -18'' H x 26'' W x 0.75'' D: 1.44 lbs. Paintings Prints Tori White Wildon Photography Photos Posters Abstract Black D cor Designs Framed Hazelwood Hokku Home Landscape Oil Accent 075 12 15 18 26 40 60 8 D H W x 1 1017 1824 2532 holidays, christmas gift gifts for girls boys"
m = p.search(s)
if m:
print(m.group()) # this includes Subject:
print(m.group(1)) # this does not include Subject:
</code></pre>
| 1 | 2016-09-26T10:32:26Z | [
"python",
"regex",
"python-3.x",
"pattern-matching"
]
|
regex to find all words after specific word? | 39,700,416 | <p>I have a string like below:</p>
<pre><code>Features: -Includes hanging accessories. -Artist: William-Adolphe Bouguereau. -Made with 100pct cotton canvas. -100pct Anti-shrink pine wood bars and Epson anti-fade ultra chrome inks. -100pct Hand-made and inspected in the U.S.A. -Orientation: Horizontal. **Subject: -Figures/Nautical and beach.** Gender: -Unisex/Both. Size: -Mini 17'' and under/Small 18''-24''/Medium 25''-32''/Large 33''-40''/Oversized 41'' and above. Style: -Fine art. Color: -Blue. Country of Manufacture: -United States. Product Type: -Print of painting. Region: -Europe. Primary Art Material: -Canvas. Dimensions: -8'' H x 12'' W x 0.75'' D: 0.72 lb. -12'' H x 18'' W x 0.75'' D: 1.14 lbs. -12'' H x 18'' W x 1.5'' D: 2.45 lbs. -18'' H x 26'' W x 0.75'' D: 1.44 lbs. Paintings Prints Tori White Wildon Photography Photos Posters Abstract Black D cor Designs Framed Hazelwood Hokku Home Landscape Oil Accent 075 12 15 18 26 40 60 8 D H W x 1 1017 1824 2532 holidays, christmas gift gifts for girls boys
</code></pre>
<p>I have to find the words after particular word. </p>
<p>I want to extract the words after the word <code>"Subject"</code> in above example.</p>
<p>The output should be like below:</p>
<pre><code>Subject: -Figures/Nautical and beach.
</code></pre>
<p>I tried below regex:</p>
<pre><code>re.compile('(?<=subject)(.{30}(?:\s|.))',re.I)
</code></pre>
<p>But there is not fixed number of words after subject keyword to specify so I can't specify exact number of words.</p>
<p>How do I stop at "peroid" or space.There is no specific stopping criterion.</p>
| 0 | 2016-09-26T10:28:06Z | 39,700,572 | <p>Try:</p>
<pre><code>re.compile('Subject: [^*]+')
</code></pre>
<p><a href="http://pythex.org/?regex=Subject%3A%20%5B%5E%5C*%5D%2B&test_string=Features%3A%20%20-Includes%20hanging%20accessories.%20%20-Artist%3A%20William-Adolphe%20Bouguereau.%20%20-Made%20with%20100pct%20cotton%20canvas.%20%20-100pct%20Anti-shrink%20pine%20wood%20bars%20and%20Epson%20anti-fade%20ultra%20chrome%20inks.%20%20-100pct%20Hand-made%20and%20inspected%20in%20the%20U.S.A.%20%20-Orientation%3A%20Horizontal.%20%20**Subject%3A%20-Figures%2FNautical%20and%20beach.**%20%20Gender%3A%20-Unisex%2FBoth.%20%20Size%3A%20-Mini%2017%27%27%20and%20under%2FSmall%2018%27%27-24%27%27%2FMedium%2025%27%27-32%27%27%2FLarge%2033%27%27-40%27%27%2FOversized%2041%27%27%20and%20above.%20%20Style%3A%20-Fine%20art.%20%20Color%3A%20-Blue.%20%20Country%20of%20Manufacture%3A%20-United%20States.%20%20Product%20Type%3A%20-Print%20of%20painting.%20%20Region%3A%20-Europe.%20%20Primary%20Art%20Material%3A%20-Canvas.%20Dimensions%3A%20%20-8%27%27%20H%20x%2012%27%27%20W%20x%200.75%27%27%20D%3A%200.72%20lb.%20%20-12%27%27%20H%20x%2018%27%27%20W%20x%200.75%27%27%20D%3A%201.14%20lbs.%20%20-12%27%27%20H%20x%2018%27%27%20W%20x%201.5%27%27%20D%3A%202.45%20lbs.%20%20-18%27%27%20H%20x%2026%27%27%20W%20x%200.75%27%27%20D%3A%201.44%20lbs.%20%20Paintings%20Prints%20Tori%20White%20Wildon%20Photography%20Photos%20Posters%20Abstract%20Black%20D%20cor%20Designs%20Framed%20Hazelwood%20Hokku%20Home%20Landscape%20Oil%20Accent%20075%2012%2015%2018%2026%2040%2060%208%20D%20H%20W%20x%201%201017%201824%202532%20holidays%2C%20christmas%20gift%20gifts%20for%20girls%20boys&ignorecase=0&multiline=0&dotall=0&verbose=0" rel="nofollow" title="Demo">Demo</a></p>
| 0 | 2016-09-26T10:34:43Z | [
"python",
"regex",
"python-3.x",
"pattern-matching"
]
|
regex to find all words after specific word? | 39,700,416 | <p>I have a string like below:</p>
<pre><code>Features: -Includes hanging accessories. -Artist: William-Adolphe Bouguereau. -Made with 100pct cotton canvas. -100pct Anti-shrink pine wood bars and Epson anti-fade ultra chrome inks. -100pct Hand-made and inspected in the U.S.A. -Orientation: Horizontal. **Subject: -Figures/Nautical and beach.** Gender: -Unisex/Both. Size: -Mini 17'' and under/Small 18''-24''/Medium 25''-32''/Large 33''-40''/Oversized 41'' and above. Style: -Fine art. Color: -Blue. Country of Manufacture: -United States. Product Type: -Print of painting. Region: -Europe. Primary Art Material: -Canvas. Dimensions: -8'' H x 12'' W x 0.75'' D: 0.72 lb. -12'' H x 18'' W x 0.75'' D: 1.14 lbs. -12'' H x 18'' W x 1.5'' D: 2.45 lbs. -18'' H x 26'' W x 0.75'' D: 1.44 lbs. Paintings Prints Tori White Wildon Photography Photos Posters Abstract Black D cor Designs Framed Hazelwood Hokku Home Landscape Oil Accent 075 12 15 18 26 40 60 8 D H W x 1 1017 1824 2532 holidays, christmas gift gifts for girls boys
</code></pre>
<p>I have to find the words after particular word. </p>
<p>I want to extract the words after the word <code>"Subject"</code> in above example.</p>
<p>The output should be like below:</p>
<pre><code>Subject: -Figures/Nautical and beach.
</code></pre>
<p>I tried below regex:</p>
<pre><code>re.compile('(?<=subject)(.{30}(?:\s|.))',re.I)
</code></pre>
<p>But there is not fixed number of words after subject keyword to specify so I can't specify exact number of words.</p>
<p>How do I stop at "peroid" or space.There is no specific stopping criterion.</p>
| 0 | 2016-09-26T10:28:06Z | 39,700,850 | <p><strong>Regex:</strong></p>
<pre><code>(Subject:.+)\*\*
Match Subject and content after that till '**'
</code></pre>
<p><strong>Code:</strong></p>
<pre><code>str = 'Features: -Includes hanging accessories. -Artist: William-Adolphe Bouguereau. -Made with 100pct cotton canvas. -100pct Anti-shrink pine wood bars and Epson anti-fade ultra chrome inks. -100pct Hand-made and inspected in the U.S.A. -Orientation: Horizontal. **Subject: -Figures/Nautical and beach.** Gender: -Unisex/Both. Size: -Mini 17'' and under/Small 18''-24''/Medium 25''-32''/Large 33''-40''/Oversized 41'' and above. Style: -Fine art. Color: -Blue. Country of Manufacture: -United States. Product Type: -Print of painting. Region: -Europe. Primary Art Material: -Canvas. Dimensions: -8'' H x 12'' W x 0.75'' D: 0.72 lb. -12'' H x 18'' W x 0.75'' D: 1.14 lbs. -12'' H x 18'' W x 1.5'' D: 2.45 lbs. -18'' H x 26'' W x 0.75'' D: 1.44 lbs. Paintings Prints Tori White Wildon Photography Photos Posters Abstract Black D cor Designs Framed Hazelwood Hokku Home Landscape Oil Accent 075 12 15 18 26 40 60 8 D H W x 1 1017 1824 2532 holidays, christmas gift gifts for girls boys'
import re
a = re.search(r'(Subject:.+)\*\*',str)
print(a.group(1))
</code></pre>
| 0 | 2016-09-26T10:49:09Z | [
"python",
"regex",
"python-3.x",
"pattern-matching"
]
|
Python Statsmodels: Using SARIMAX with exogenous regressors to get predicted mean and confidence intervals | 39,700,424 | <p>I'm using statsmodels.tsa.SARIMAX() to train a model with exogenous variables. Is there an equivalent of get_prediction() when a model is trained with exogenous variables so that the object returned contains the predicted mean and confidence interval rather than just an array of predicted mean results? The predict() and forecast() methods take exogenous variables, but only return the predicted mean value.</p>
<pre><code>SARIMA_model = sm.tsa.SARIMAX(endog=y_train.astype('float64'),
exog=ExogenousFeature_train.values.astype('float64'),
order=(1,0,0),
seasonal_order=(2,1,0,7),
simple_differencing=False)
model_results = SARIMA_model.fit()
pred = model_results.predict(start=train_end_date,
end=test_end_date,
exog=ExogenousFeature_test.values.astype('float64').reshape(343,1),
dynamic=False)
</code></pre>
<p>pred here is an array of predicted values rather than an object containing predicted mean values and confidence intervals that you would get if you ran get_predict(). Note, get_predict() does not take exogenous variables.</p>
<p>My version of statsmodels is 0.8</p>
| 1 | 2016-09-26T10:28:24Z | 40,032,857 | <p>There has been some backward compatibility related issues due to which full results (with pred intervals etc) are not being exposed. </p>
<p>To get you what you want now: Use get_prediction and get_forecast functions with parameters described below</p>
<pre><code> pred_res = sarimax_model.get_prediction(exog=ExogenousFeature_train.values.astype('float64'), full_results=True,alpha=0.05)
pred_means = pred_res.predicted_mean
# Specify your prediction intervals by alpha parameter. alpha=0.05 implies 95% CI
pred_cis = pred_res.conf_int(alpha=0.05)
# You can then plot it (import matplotlib first)
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(1,1,1)
#Actual data
ax.plot(y_train.astype('float64'), '--', color="blue", label='data')
# Means
ax.plot(pred_means, lw=1, color="black", alpha=0.5, label='SARIMAX')
ax.fill_between(pred_means.index, pred_cis.iloc[:, 0], pred_cis.iloc[:, 1], alpha=0.05)
ax.legend(loc='upper right')
plt.draw()
</code></pre>
<p>For more info, go to:</p>
<ul>
<li><a href="https://github.com/statsmodels/statsmodels/issues/2823" rel="nofollow">https://github.com/statsmodels/statsmodels/issues/2823</a></li>
<li>Solution by the author: <a href="http://www.statsmodels.org/dev/examples/notebooks/generated/statespace_local_linear_trend.html" rel="nofollow">http://www.statsmodels.org/dev/examples/notebooks/generated/statespace_local_linear_trend.html</a></li>
</ul>
| 1 | 2016-10-13T23:55:36Z | [
"python",
"time-series",
"forecasting",
"statsmodels",
"confidence-interval"
]
|
Application started in Crontab, problems in communication between Nodejs and python | 39,700,599 | <p>I have developed an Bluetooth peripheral software (app.js) for Raspberry Pi using <a href="https://github.com/sandeepmistry/bleno" rel="nofollow">BLENO </a>NodeJS library. Inside my NodeJS application I'm calling some python script using <a href="https://github.com/extrabacon/python-shell" rel="nofollow">python-shell</a>. </p>
<p>I'm calling the python script using the following code:</p>
<pre><code>var shell = new PythonShell('example.py');
shell.on('message', function (message) {
console.log(message);
</code></pre>
<p>My example.py is just simply prints number after some delay</p>
<pre><code>time.sleep(5)
print 10
</code></pre>
<p>When I start my app.js using command "node app.js" everything works as expected. Message callback is activated after 5 seconds delay and number 10 is printed to console.</p>
<p>However when I try to start the application when Rasperry Pi boots, Nodejs application never receives message from Python script. Python script prints the number to stdout, but for some reason it is not received by Nodejs app. Any suggestions?</p>
| 0 | 2016-09-26T10:36:26Z | 39,703,232 | <p>Found a solution to my problem. Originally I started application from crontab using @reboot field. Instead of crontab, I started my application from /etc/init.d/. That fixed the problem. Maybe someone could explain the reason.</p>
| 0 | 2016-09-26T12:45:22Z | [
"python",
"node.js",
"raspberry-pi",
"bleno"
]
|
Define date format in Python / Pandas | 39,700,636 | <p>I have two .csv files joined in Python with the Pandas module. One column is date with the format "dd.mm.yyyy".</p>
<p>Now I would like to extract only the month (as 2 digit integer with leading zero) from it for further use.</p>
<p>I have so far accomplished the job but I had to cheat. Python thinks the string that I am getting is the DAY. I don't like half-baked things, so I wanted to ask the community how I can tell Python specifically which part of the date is the month so it can be returned to me?</p>
<p>Here is what I have so far:</p>
<pre><code>import pandas
def saison(input):
if input == "04" or input == "05" or input == "06" or input == "07" or input == "08" or input == "09":
return "Sommer"
else:
return "Winter"
df_1 = pandas.read_csv("a.csv", sep=';', names=["DWD_ID", "Datum"], header=0)
df_2 = pandas.read_csv("b.csv", sep=';', names=[VEG", "DWD_ID"], header=0)
df_joined = pandas.merge(df_1, df_2, on="DWD_ID")
df_joined["Datum"] = pandas.to_datetime(df_joined["Datum"])
df_joined["Saison"] = saison(df_joined["Datum"].apply(lambda x: x.strftime('%d')))
</code></pre>
<p>If I use </p>
<pre><code>x.strftime('%m')
</code></pre>
<p>instead it returns me the day.</p>
| 0 | 2016-09-26T10:38:14Z | 39,700,874 | <p>First it seems you have swap month and day in datetime, so you need add argument <code>format='%Y-%d-%m'</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a> (<a href="http://strftime.org/" rel="nofollow">Python's strftime directives</a>):</p>
<pre><code>df = pd.DataFrame({'Date': ['2016-24-02']})
print (df)
Date
0 2016-24-02
print (pd.to_datetime(df.Date, format='%Y-%d-%m'))
0 2016-02-24
Name: Date, dtype: datetime64[ns]
</code></pre>
<p>After converting you can use:</p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="nofollow"><code>dt.strftime</code></a>:</p>
<pre><code>print (df.Date.dt.strftime('%m'))
</code></pre>
<p>Another solution with extract <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.month.html" rel="nofollow"><code>month</code></a>, then convert to <code>string</code> and last add zero fill by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.zfill.html" rel="nofollow"><code>zfill</code></a>:</p>
<pre><code>print (df.Date.dt.month.astype(str).str.zfill(2))
</code></pre>
<p>Sample:</p>
<pre><code>start = pd.to_datetime('2015-02-24')
rng = pd.date_range(start, periods=10, freq='m')
df = pd.DataFrame({'Date': rng})
print (df)
Date
0 2015-02-28
1 2015-03-31
2 2015-04-30
3 2015-05-31
4 2015-06-30
5 2015-07-31
6 2015-08-31
7 2015-09-30
8 2015-10-31
9 2015-11-30
print (df.Date.dt.strftime('%m'))
0 02
1 03
2 04
3 05
4 06
5 07
6 08
7 09
8 10
9 11
Name: Date, dtype: object
</code></pre>
<hr>
<pre><code>print (df.Date.dt.month.astype(str).str.zfill(2))
0 02
1 03
2 04
3 05
4 06
5 07
6 08
7 09
8 10
9 11
Name: Date, dtype: object
</code></pre>
<p>Last you can use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a> with condition with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a>:</p>
<pre><code>saison = ["04","05","06","07","08","09"]
df['Saison'] = np.where(df.Date.dt.strftime('%m').isin(saison), 'Sommer','Winter')
print (df)
Date Saison
0 2015-02-28 Winter
1 2015-03-31 Winter
2 2015-04-30 Sommer
3 2015-05-31 Sommer
4 2015-06-30 Sommer
5 2015-07-31 Sommer
6 2015-08-31 Sommer
7 2015-09-30 Sommer
8 2015-10-31 Winter
9 2015-11-30 Winter
</code></pre>
| 1 | 2016-09-26T10:50:09Z | [
"python",
"python-2.7",
"csv",
"pandas"
]
|
Define date format in Python / Pandas | 39,700,636 | <p>I have two .csv files joined in Python with the Pandas module. One column is date with the format "dd.mm.yyyy".</p>
<p>Now I would like to extract only the month (as 2 digit integer with leading zero) from it for further use.</p>
<p>I have so far accomplished the job but I had to cheat. Python thinks the string that I am getting is the DAY. I don't like half-baked things, so I wanted to ask the community how I can tell Python specifically which part of the date is the month so it can be returned to me?</p>
<p>Here is what I have so far:</p>
<pre><code>import pandas
def saison(input):
if input == "04" or input == "05" or input == "06" or input == "07" or input == "08" or input == "09":
return "Sommer"
else:
return "Winter"
df_1 = pandas.read_csv("a.csv", sep=';', names=["DWD_ID", "Datum"], header=0)
df_2 = pandas.read_csv("b.csv", sep=';', names=[VEG", "DWD_ID"], header=0)
df_joined = pandas.merge(df_1, df_2, on="DWD_ID")
df_joined["Datum"] = pandas.to_datetime(df_joined["Datum"])
df_joined["Saison"] = saison(df_joined["Datum"].apply(lambda x: x.strftime('%d')))
</code></pre>
<p>If I use </p>
<pre><code>x.strftime('%m')
</code></pre>
<p>instead it returns me the day.</p>
| 0 | 2016-09-26T10:38:14Z | 39,700,945 | <p>You could supply the format you want to keep in the arg of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a>:</p>
<pre><code>pd.to_datetime(df['date_col'], format="%d.%m.%Y").dt.month.astype(str).str.zfill(2)
</code></pre>
| 1 | 2016-09-26T10:53:54Z | [
"python",
"python-2.7",
"csv",
"pandas"
]
|
Understanding Django queryset field lookup in | 39,700,644 | <p>Short version: Why does Model.objects.exclude(..__in=[None]) exclude every object?</p>
<p>I have encountered an interesting behaviour of django field lookup that I do not understand. Let's say I have 21 objects of a given model:</p>
<pre><code>>>> Model.objects.count()
21
</code></pre>
<p>If I exclude a given private key directly or with <code>in</code> field lookup I get the expected behaviour:</p>
<pre><code>>>> Model.objects.exclude(pk=1).count()
20
>>> Model.objects.exclude(pk__in=[1]).count()
20
</code></pre>
<p>If I exclude the private key of value <code>None</code> I get the expected result:</p>
<pre><code>>>> Model.objects.exclude(pk=None).count()
21
</code></pre>
<p>However if I do the same with the <code>in</code> field lookup I get nothing back:</p>
<pre><code>>>> Model.objects.exclude(pk__in=[None]).count()
0
</code></pre>
<p>Why is this so?</p>
| 1 | 2016-09-26T10:38:28Z | 39,701,025 | <p>I suspect this is because of the way SQL treats NULL. The query compiles to <code>SELECT COUNT(*) FROM mymodel WHERE NOT (id IN (NULL));</code>.</p>
<p>See for example <a href="http://stackoverflow.com/questions/129077/not-in-clause-and-null-values">this question</a> for a discussion of why NOT IN with NULL always returns empty.</p>
| 2 | 2016-09-26T10:57:27Z | [
"python",
"django-queryset"
]
|
Remove duplicates of IP addresses by netmask | 39,700,746 | <p>I have got an Array: </p>
<pre><code>[192.0.0.3, 0.0.0.0 , 192.0.10.24, ...]
</code></pre>
<p>With IP addresses and i want to remove duplicates for the /16 netmasks, so i got 192.0.0.3 but 192.0.10.24 will be removed (i don't mind which one of them, it would also be okay if the first one is removed). </p>
<p>My first thoughts were to use a regex to cast the netmask and remove every IP address which matches the then generated patttern. </p>
<p>Is there an easier way? </p>
| 1 | 2016-09-26T10:43:46Z | 39,700,881 | <p>You could remove duplicates using a set, with the keys being tuples of the first two parts:</p>
<pre><code>>>> ips = ["192.0.0.3", "0.0.0.0", "192.0.10.24"]
>>> seen = set()
>>> for ip in ips:
... key = tuple(ip.split(".")[:2])
... if key not in seen:
... print(ip)
... seen.add(key)
...
192.0.0.3
0.0.0.0
</code></pre>
<p>Or alternatively using the <a href="https://docs.python.org/3/library/ipaddress.html" rel="nofollow">ipaddress</a> module:</p>
<pre><code>>>> from ipaddress import ip_network
>>> ips = ["192.0.0.3", "0.0.0.0", "192.0.10.24"]
>>> seen = set()
>>> for ip in ips:
... key = ip_network(ip + "/16", strict=False)
... if key not in seen:
... print(ip)
... seen.add(key)
...
192.0.0.3
0.0.0.0
</code></pre>
| 1 | 2016-09-26T10:50:42Z | [
"python",
"arrays",
"set"
]
|
Remove duplicates of IP addresses by netmask | 39,700,746 | <p>I have got an Array: </p>
<pre><code>[192.0.0.3, 0.0.0.0 , 192.0.10.24, ...]
</code></pre>
<p>With IP addresses and i want to remove duplicates for the /16 netmasks, so i got 192.0.0.3 but 192.0.10.24 will be removed (i don't mind which one of them, it would also be okay if the first one is removed). </p>
<p>My first thoughts were to use a regex to cast the netmask and remove every IP address which matches the then generated patttern. </p>
<p>Is there an easier way? </p>
| 1 | 2016-09-26T10:43:46Z | 39,701,492 | <p>You could use a dictionary:</p>
<pre><code>>>> res = {}
>>> for ip in ["192.0.0.3", "0.0.0.0", "192.0.10.24"]:
... res[tuple(ip.split('.',2)[0:2])]=ip
>>> res.values()
['0.0.0.0', '192.0.10.24']
</code></pre>
<p>If you need the first occurence rather than the last one, a quick and dirty solution is to reverse the list first:</p>
<pre><code>>>> res = {}
>>> for ip in reversed(["192.0.0.3", "0.0.0.0", "192.0.10.24"]):
... res[tuple(ip.split('.',2)[0:2])]=ip
>>> res.values()
['0.0.0.0', '192.0.0.3']
</code></pre>
<p>Example with <code>ipaddress</code> as @eugne s suggests:</p>
<pre><code>>>> import ipaddress
>>> res = {}
>>> for ip in [u"192.0.0.3", u"0.0.0.0", u"192.0.10.24"]:
... res[ipaddress.ip_network(ip + "/16", strict=False)]=ip
>>> res.values()
[u'192.0.10.24', u'0.0.0.0']
</code></pre>
| 1 | 2016-09-26T11:21:14Z | [
"python",
"arrays",
"set"
]
|
How to sum values in treeview line using onchange event in odoo 9 | 39,700,777 | <p>I got a parent model and a child model, here is the code :</p>
<pre><code>class parent_model(osv.osv):
_name = 'parent_model'
_columns = {
'line_ids' : fields.one2many('child_model', 'line_id', 'Line ID', ondelete='cascade'),
'description' : fields.text('Description', required=True),
'grand_total' : fields.float('Grand Total'),
}
class child_model(osv.osv):
_name = 'child_model'
_columns = {
'line_id' : fields.many2one('parent_model', string='Line ID', required=True),
'item' : fields.char('Item', required=True),
'amount' : fields.float('Amount', required=True),
'qty' : fields.integer('Qty', required=True),
'subtotal' : fields.float('Total', readonly=True),
}
def get_subtotal(self, cr, uid, ids, num1, num2, context=None):
res = {}
if num1 and num2:
res['subtotal'] = num1 * num2
return {'value': res}
</code></pre>
<p>In child_model I successfully multiplying "amount" and "qty" in event onchange get_subtotal, here is the xml :</p>
<pre><code><tree >
<field name="item" />
<field name="amount" on_change="get_subtotal(amount, qty)" />
<field name="qty" on_change="get_subtotal(amount, qty)" />
<field name="subtotal" />
</tree>
</code></pre>
<p>My question is how to calculate(sum) subtotal in child_model and store the value into grand_total field in parent_model using onchange event.
Need help please, Thanks</p>
| 1 | 2016-09-26T10:45:31Z | 39,717,880 | <p>1st: move everything to new api.</p>
<p>Add an onchange <strong>to the parent model</strong> hooked to <code>line_ids</code>, like:
<code>
@api.onchange('line_ids')
def _onchange_line_ids(self):
</code></p>
| 0 | 2016-09-27T06:50:36Z | [
"python",
"openerp",
"odoo-9"
]
|
I am using jinja and want to pass a variable into a URL but it is now happening. | 39,700,818 | <pre><code>{% for x in data %}
<tr class="table-row">
<td>{{ forloop.counter }}</td>
<td><label>{{ x.0 }}</label></td>
<td><img src="{% static 'lang/hi_IN/font/**x.1**' %}"></td>
<td><label style="font-size:20px"> {{ x.2 }}</label></td>
<td><input style="font-size:20px;text-align:center" type="text" value={{x.2}} size=3 title="Text"></td>
<td><label> {{x.3}}</label></td>
</tr>
{% endfor %}
</code></pre>
<p>I want to pass this <strong>x.1</strong> value to the url so how can i do that? value 0f <strong>x.1</strong> is like <strong>images/1.jpg</strong>.</p>
| 0 | 2016-09-26T10:47:24Z | 39,700,908 | <p>I have never used jinja or django, but I believe you just need to separate the variable form the string.</p>
<pre><code><td><img src="{% static 'lang/hi_IN/font/' + x.1 %}"></td>
</code></pre>
<p>or the equivalent of this in jinja.</p>
| 0 | 2016-09-26T10:51:59Z | [
"python",
"html",
"django-templates",
"jinja2"
]
|
I am using jinja and want to pass a variable into a URL but it is now happening. | 39,700,818 | <pre><code>{% for x in data %}
<tr class="table-row">
<td>{{ forloop.counter }}</td>
<td><label>{{ x.0 }}</label></td>
<td><img src="{% static 'lang/hi_IN/font/**x.1**' %}"></td>
<td><label style="font-size:20px"> {{ x.2 }}</label></td>
<td><input style="font-size:20px;text-align:center" type="text" value={{x.2}} size=3 title="Text"></td>
<td><label> {{x.3}}</label></td>
</tr>
{% endfor %}
</code></pre>
<p>I want to pass this <strong>x.1</strong> value to the url so how can i do that? value 0f <strong>x.1</strong> is like <strong>images/1.jpg</strong>.</p>
| 0 | 2016-09-26T10:47:24Z | 39,701,196 | <p>I don't know <code>static</code> keyword in Jinja2. Maybe everything is much simpler:</p>
<pre><code><td><img src="lang/hi_IN/font/{{ x.1 }}"></td>
</code></pre>
<p>Or the problem may be deeper. Did you implement serving methods? It should looks like:</p>
<pre><code>@app.route('/media/<path:filename>')
def media(filename):
return send_from_directory(app.config['MEDIA_FOLDER'], filename.encode(app.config['ENCODING']))
</code></pre>
| 0 | 2016-09-26T11:06:50Z | [
"python",
"html",
"django-templates",
"jinja2"
]
|
I am using jinja and want to pass a variable into a URL but it is now happening. | 39,700,818 | <pre><code>{% for x in data %}
<tr class="table-row">
<td>{{ forloop.counter }}</td>
<td><label>{{ x.0 }}</label></td>
<td><img src="{% static 'lang/hi_IN/font/**x.1**' %}"></td>
<td><label style="font-size:20px"> {{ x.2 }}</label></td>
<td><input style="font-size:20px;text-align:center" type="text" value={{x.2}} size=3 title="Text"></td>
<td><label> {{x.3}}</label></td>
</tr>
{% endfor %}
</code></pre>
<p>I want to pass this <strong>x.1</strong> value to the url so how can i do that? value 0f <strong>x.1</strong> is like <strong>images/1.jpg</strong>.</p>
| 0 | 2016-09-26T10:47:24Z | 39,706,022 | <p>I'm new to jinja2 templates and mostly I work with Flask, but with jinja2 I would try this:</p>
<pre><code><img src="{{ url_for('static', filename='lang/hi_IN/font/')}}{{x.1}}">
</code></pre>
<p>And this is blind guess that I came up after reading about <strong>static</strong> in Django-Templates (from this <a href="https://docs.djangoproject.com/es/1.10/ref/templates/builtins/#static" rel="nofollow" title="page">page</a>):</p>
<pre><code>{% load static %}
<img src="{% static "images/" %}{{x.1}}" alt="img" />
</code></pre>
| 0 | 2016-09-26T14:53:53Z | [
"python",
"html",
"django-templates",
"jinja2"
]
|
How to get and ascribe irregular numbers to objects? | 39,700,896 | <p>I am a beginner and I have a question.
I have datas in csv file, I can find 100 objects and irregular number of size number for each object. In one row I have a name of the object, its size and then these irregular numbers- for one name it can be 20 of then and for the other 40. </p>
<pre><code>import glob
import csv
import re
for f_name in glob.glob("*.csv"):
with open(f_name) as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
print (row[1])
</code></pre>
<p>how can I have the numbers which are irregular? any loop? and how can I ascribe the numbers to the "size" and "name"? </p>
| 0 | 2016-09-26T10:51:38Z | 39,701,969 | <pre><code>with open('data.csv') as fp:
for line in fp:
data = line.split(',')
if data[0] == 'name':
result[name] = init_dict(name)
elif data[0] == 'weight' :
update_dict(data[1])
else:
update_dict(data[0])
</code></pre>
<p>basically you can just loop through the file and whenever you encounter a name just create a new_dict and update the corresponding attribute until you encounter the new name</p>
<pre><code>def init_dict(name):
return {'name': name, 'weight':None, 'others':None}
</code></pre>
<p>similary you can write an update dict to update the corresponding attributes of the dict of that corresponding name</p>
| 0 | 2016-09-26T11:45:36Z | [
"python"
]
|
Why use pandas.DataFrame.copy() for column extraction | 39,700,904 | <p>I've recently seen this kind of code:</p>
<pre><code>import pandas as pd
data = pd.read_csv('/path/to/some/data.csv')
colX = data['colX'].copy()
data.drop(labels=['colX'], inplace=True, axis=1)
</code></pre>
<p>I know that, to make an explicit copy of an object, I need <code>copy()</code>, but in this case, when extracting and subsequent deletion of a colum, is there a good reason to use <code>copy()</code>?</p>
| -1 | 2016-09-26T10:51:56Z | 39,720,157 | <p>@EdChum statet in the comments:</p>
<blockquote>
<p>the user may want to separate that column from the main df, of course if the user just wanted to delete that column then taking a copy is pointless if their intention is to delete the column but for instance they didn't take a copy and instead took a reference then operations on that column may or may not affect the orig df if you didn't drop it.</p>
</blockquote>
| 0 | 2016-09-27T08:48:09Z | [
"python",
"pandas"
]
|
Find all the 'h2' tags that are children of a specific div with attribute 'id' and value 'column-left' | 39,701,173 | <p>Using BeautifulSoup, I tried the following:</p>
<pre><code>q = soup.div.find_all("div", { "id" : "column-left" }, "h2")
</code></pre>
<p>But this gives me the text of the <code><p></code> as well. I just want the h2 that are children of a specific div.</p>
| 0 | 2016-09-26T11:05:56Z | 39,701,237 | <p>Why are you accessing <code>soup.div</code>?</p>
<p>Try this:</p>
<pre><code>q = soup.find('div', { 'id' : 'column-left' }).find_all('h2')
</code></pre>
<p>Also find_all has optional parameter 'id', so you do not have to write attributes map</p>
<pre><code>q = soup.find('div', id='column-left').find_all('h2')
</code></pre>
| 0 | 2016-09-26T11:08:54Z | [
"python",
"web-scraping",
"beautifulsoup"
]
|
Find all the 'h2' tags that are children of a specific div with attribute 'id' and value 'column-left' | 39,701,173 | <p>Using BeautifulSoup, I tried the following:</p>
<pre><code>q = soup.div.find_all("div", { "id" : "column-left" }, "h2")
</code></pre>
<p>But this gives me the text of the <code><p></code> as well. I just want the h2 that are children of a specific div.</p>
| 0 | 2016-09-26T11:05:56Z | 39,702,207 | <p>If you use a recent version of BeautifulSoup (and you should) you can just use a CSS selector, which might be easier to write and maintain anyway. e.g.:</p>
<pre><code>>>> from bs4 import beautifulsoup
>>> soup = BeautifulSoup('<div id=column-left><h2>Header</h2><p>Paragraph</p><h2>Another header</h2><p>Another paragraph</p></div>')
>>> soup.select('div#column-left > h2')
[<h2>Header</h2>, <h2>Another header</h2>]
</code></pre>
| 0 | 2016-09-26T11:56:58Z | [
"python",
"web-scraping",
"beautifulsoup"
]
|
How do I print out individual words within my list? | 39,701,500 | <p>I am trying to print each word from my list onto separate lines, however it is printing each letter onto individual lines</p>
<pre><code>Words = sentence.strip()
for word in sentence:
print (word)
</code></pre>
<p>My full code (for anyone wondering) is:</p>
<pre><code>import csv
file = open("Task2.csv", "w")
sentence = input("Please enter a sentence: ")
Words = sentence.strip()
for word in sentence:
print (word)
for s in Words:
Positions = Words.index(s)+1
file.write(str(Words) + (str(Positions) + "\n"))
file.close()
</code></pre>
| 0 | 2016-09-26T11:21:45Z | 39,701,541 | <p>You forgot to split sentence and use "Words" not "sentence" in first for loop.</p>
<pre><code>#file = open("Task2.csv", "w")
sentence = input("Please enter a sentence: ")
Words = sentence.split()
for word in Words:
print (word)
for s in Words:
Positions = Words.index(s)+1
#file.write(str(Words) + (str(Positions) + "\n"))
#file.close()
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>C:\Users\dinesh_pundkar\Desktop>python c.py
Please enter a sentence: I am Dinesh
I
am
Dinesh
C:\Users\dinesh_pundkar\Desktop>
</code></pre>
| 0 | 2016-09-26T11:23:54Z | [
"python"
]
|
How do I print out individual words within my list? | 39,701,500 | <p>I am trying to print each word from my list onto separate lines, however it is printing each letter onto individual lines</p>
<pre><code>Words = sentence.strip()
for word in sentence:
print (word)
</code></pre>
<p>My full code (for anyone wondering) is:</p>
<pre><code>import csv
file = open("Task2.csv", "w")
sentence = input("Please enter a sentence: ")
Words = sentence.strip()
for word in sentence:
print (word)
for s in Words:
Positions = Words.index(s)+1
file.write(str(Words) + (str(Positions) + "\n"))
file.close()
</code></pre>
| 0 | 2016-09-26T11:21:45Z | 39,701,711 | <p>You need to used <a href="https://docs.python.org/3.6/library/stdtypes.html#str.split" rel="nofollow"><code>str.split()</code></a> instead of <a href="https://docs.python.org/3.6/library/stdtypes.html#str.strip" rel="nofollow"><code>str.strip()</code></a>.</p>
<p><a href="https://docs.python.org/3.6/library/stdtypes.html#str.strip" rel="nofollow"><code>str.strip()</code></a> only removes the leading and trailing whitespaces in a string:</p>
<pre><code>>>> my_string = ' This is a sentence. '
>>> my_string.strip()
'This is a sentence.'
</code></pre>
<p><a href="https://docs.python.org/3.6/library/stdtypes.html#str.split" rel="nofollow"><code>str.split()</code></a> does what you want which is return a list of the words in the string; by default, using whitespace as the delimiter string:</p>
<pre><code>>>> my_string = ' This is a sentence. '
>>> my_string.split()
['This', 'is', 'a', 'sentence.']
</code></pre>
<p>So, your code should look more like:</p>
<pre><code>words = sentence.split()
for word in sentence:
print(word)
</code></pre>
| 0 | 2016-09-26T11:32:35Z | [
"python"
]
|
Export Python-Scopus API results into CSV | 39,701,525 | <p>I'm very new to Python so not sure if this can be done but I hope it can!</p>
<p>I have accessed the Scopus API and managed to run a search query which gives me the following results in a pandas dataframe:</p>
<pre><code> search-results
entry [{'@_fa': 'true', 'affiliation': [{'@_fa': 'tr...
link [{'@_fa': 'true', '@ref': 'self', '@type': 'ap...
opensearch:Query {'@role': 'request', '@searchTerms': 'AFFIL(un...
opensearch:itemsPerPage 200
opensearch:startIndex 0
opensearch:totalResults 106652
</code></pre>
<p>If possible, I'd like to export the 106652 results into a csv file so that they can be analysed. Is this possible at all?</p>
| 0 | 2016-09-26T11:23:12Z | 39,857,382 | <p>first you need to get all the results (see comments under question).
The data you need (search results) is inside the "entry" list.
You can extract that list and append it to a support list, iterating until you got all the results. Here i cycle and at every round i subtract the downloaded items (count) from the total number of results.</p>
<pre><code> found_items_num = 1
start_item = 0
items_per_query = 25
max_items = 2000
JSON = []
print ('GET data from Search API...')
while found_items_num > 0:
resp = requests.get(self._url,
headers={'Accept': 'application/json', 'X-ELS-APIKey': MY_API_KEY},
params={'query': query, 'view': view, 'count': items_per_query,
'start': start_item})
print ('Current query url:\n\t{}\n'.format(resp.url))
if resp.status_code != 200:
# error
raise Exception('ScopusSearchApi status {0}, JSON dump:\n{1}\n'.format(resp.status_code, resp.json()))
# we set found_items_num=1 at initialization, on the first call it has to be set to the actual value
if found_items_num == 1:
found_items_num = int(resp.json().get('search-results').get('opensearch:totalResults'))
print ('GET returned {} articles.'.format(found_items_num))
if found_items_num == 0:
pass
else:
# write fetched JSON data to a file.
out_file = os.path.join(str(start_item) + '.json')
with open(out_file, 'w') as f:
json.dump(resp.json(), f, indent=4)
f.close()
# check if results number exceed the given limit
if found_items_num > max_items:
print('WARNING: too many results, truncating to {}'.format(max_items))
found_items_num = max_items
# check if returned some result
if 'entry' in resp.json().get('search-results', []):
# combine entries to make a single JSON
JSON += resp.json()['search-results']['entry']
# set counters for the next cycle
self._found_items_num -= self._items_per_query
self._start_item += self._items_per_query
print ('Still {} results to be downloaded'.format(self._found_items_num if self._found_items_num > 0 else 0))
# end while - finished downloading JSON data
</code></pre>
<p>then, outside the while, you can save the complete file like this...</p>
<pre><code>out_file = os.path.join('articles.json')
with open(out_file, 'w') as f:
json.dump(JSON, f, indent=4)
f.close()
</code></pre>
<p>or you can follow <a href="http://blog.appliedinformaticsinc.com/how-to-parse-and-convert-json-to-csv-using-python/" rel="nofollow">this guide i found online</a>(not tested, you can search 'json to cvs python' and you get many guides) to convert the json data to a csv </p>
| 0 | 2016-10-04T16:25:08Z | [
"python",
"csv",
"python-3.5",
"scopus"
]
|
Python Script to Read CSV file and send birthday mail | 39,701,687 | <p>i need a help with writing a python script to send a Happy Birthday email after reading CSV file . The CSV file contains this </p>
<pre><code>user1,13-September-2016,email1
user2,19-October-2016,email2
user3,13-September-2016,email3
user4,25-August-2016,email44
</code></pre>
<p>So the script should match the birthday in the file with today's date and send separate emails to those who celebrate their birthday on that specific day saying "Happy Birthday "</p>
| -1 | 2016-09-26T11:31:39Z | 39,701,807 | <p>I think you should consider several modules:
1. pandas (to read and extract some data from csv)
2. time (to match the current date with the dates in the file)
3. smtplib (to send a mail)</p>
| 0 | 2016-09-26T11:37:18Z | [
"python",
"csv",
"smtp"
]
|
Pretty print a JSON in Python 3.5 | 39,701,740 | <p>I want to pretty print a JSON file, but popular solutions: <a href="http://stackoverflow.com/questions/12943819/how-to-python-prettyprint-a-json-file">How to Python prettyprint a JSON file</a> dont work for me. </p>
<p>Code:</p>
<pre><code>import json, os
def load_data(filepath):
if not os.path.exists(filepath):
print("ACHTUNG! Incorrect path")
return None
with open(filepath, 'r') as file:
return json.load(file)
</code></pre>
<p>This function is OKay - it loads jason properly.
But when i want to pp it like this:</p>
<pre><code>def pretty_print_json(data):
print(json.dumps(data, indent=4, sort_keys=True))
return None
if __name__ == '__main__':
pretty_print_json(load_data("data.json")) ,
</code></pre>
<p>it serializes the values of the dictionaries!:</p>
<pre><code>[
{
"Cells": {
"Address": "\u0443\u043b\u0438\u0446\u0430 \u0410\u043a\u0430\u0434\u0435\u043c\u0438\u043a\u0430 \u041f\u0430\u0432\u043b\u043e\u0432\u0430, \u0434\u043e\u043c 10",
"AdmArea": "\u0417\u0430\u043f\u0430\u0434\u043d\u044b\u0439 \u0430\u0434\u043c\u0438\u043d\u0438\u0441\u0442\u0440\u0430\u0442\u0438\u0432\u043d\u044b\u0439 \u043e\u043a\u0440\u0443\u0433",
"ClarificationOfWorkingHours": null,
"District": "\u0440\u0430\u0439\u043e\u043d \u041a\u0443\u043d\u0446\u0435\u0432\u043e",
"IsNetObject": "\u0434\u0430",
"Name": "\u0410\u0440\u043e\u043c\u0430\u0442\u043d\u044b\u0439 \u041c\u0438\u0440",
"OperatingCompany": "\u0410\u0440\u043e\u043c\u0430\u0442\u043d\u044b\u0439 \u041c\u0438\u0440",
"PublicPhone": [
{
"PublicPhone": "(495) 777-51-95"
}
</code></pre>
<p>What's the problem? It's anaconda 3.5 </p>
| -1 | 2016-09-26T11:34:03Z | 39,701,858 | <p><code>json.dumps()</code> produces ASCII-safe JSON by default. If you want to retain non-ASCII data as Unicode codepoints, disable that default by setting <code>ensure_ascii=False</code>:</p>
<pre><code>print(json.dumps(data, indent=4, sort_keys=True, ensure_ascii=False))
</code></pre>
<p>which, for your sample data, then produces:</p>
<pre><code>[
{
"Cells": {
"Address": "ÑлиÑа Ðкадемика Ðавлова, дом 10",
"AdmArea": "ÐападнÑй админиÑÑÑаÑивнÑй окÑÑг",
"ClarificationOfWorkingHours": null,
"District": "Ñайон ÐÑнÑево",
"IsNetObject": "да",
"Name": "ÐÑомаÑнÑй ÐиÑ",
"OperatingCompany": "ÐÑомаÑнÑй ÐиÑ",
"PublicPhone": [
{
"PublicPhone": "(495) 777-51-95"
}
</code></pre>
<p>(cut off at the same point you cut things off).</p>
| 3 | 2016-09-26T11:39:58Z | [
"python",
"json",
"pretty-print"
]
|
Mapping multiple dataframe based on the matching columns | 39,701,779 | <p>I have 25 data frames which I need to merge and find recurrently occurring rows from all 25 data frames,
For example, my data frame looks like following, </p>
<pre><code>df1
chr start end name
1 12334 12334 AAA
1 2342 2342 SAP
2 3456 3456 SOS
3 4537 4537 ABR
df2
chr start end name
1 12334 12334 DSF
1 3421 3421 KSF
2 7689 7689 LUF
df3
chr start end name
1 12334 12334 DSF
1 3421 3421 KSF
2 4537 4537 LUF
3 8976 8976 BAR
4 6789 6789 AIN
</code></pre>
<p>And In the end, I am aiming to have an output data frame like following,</p>
<pre><code>chr start end name Sample
1 12334 12334 AAA df1
1 12334 12334 AAA df2
1 12334 12334 AAA df3
</code></pre>
<p>I can get there with the following solution,
By dictionary which adds all these three data frames into one bigger data frame dfs </p>
<p>dfs = {'df1': df1, 'df2': df2} </p>
<p>Then further,</p>
<pre><code>common_tups = set.intersection(*[set(df[['chr', 'start', 'end']].drop_duplicates().apply(tuple, axis=1).values) for df in dfs.values()])
pd.concat([df[df[['chr', 'start', 'end']].apply(tuple, axis=1).isin(common_tups)].assign(Sample=name) for (name, df) in dfs.items()])
</code></pre>
<p>This gives out the resulting data frame with matching rows from all three data frames, but I have 25 data frames which I am calling as list from the directory as following,</p>
<pre><code>path = 'Fltered_vcfs/'
files = os.listdir(path)
results = [os.path.join(path,i) for i in files if i.startswith('vcf_filtered')]
</code></pre>
<p>And so how can I show the list 'results' in the dictionary and proceed further to get the desired output. Any help or suggestions are greatly appreciated.</p>
<p>Thank you</p>
| 1 | 2016-09-26T11:35:38Z | 39,701,957 | <p>Using the <a href="https://docs.python.org/2/library/glob.html" rel="nofollow"><code>glob</code></a> module, you can use</p>
<pre><code>import os
from glob import glob
path = 'Fltered_vcfs'
f_names = glob(os.path.join(path, 'vcf_filtered*.*'))
</code></pre>
<p>Then, your dictionary can be created with <a href="http://stackoverflow.com/questions/14507591/python-dictionary-comprehension">dictionary comprehension</a> using</p>
<pre><code>import pandas as pd
{os.path.splitext(os.path.split(f_name)[1])[0]: pd.read_csv(f_name,sep='\t') for f_name in f_names}
</code></pre>
| 1 | 2016-09-26T11:44:50Z | [
"python",
"pandas",
"numpy",
"dataframe"
]
|
How to screen print two columns of values from Pandas? | 39,701,881 | <p>Say I have a distribution which I have loaded in a <code>pandas</code> DataFrame. My data frame consists of 5 columns A to E, and I want to screen print the average and standard deviation next to each other:</p>
<pre><code>avg=df.mean()
stdev=df.std()
Avg St Dev
A 87.1717 A 1.354
B 87.0517 B 0.789
C 84.1717 C 1.221
D 86.8000 D 3.214
E 84.1705 E 4.170
</code></pre>
<p><strong>How can I do this by playing with the <code>print</code> formats?</strong> I might do the following</p>
<pre><code>print '%-10s' '%s' % ('Avg','St Dev')
print '%-10s' '%s' % (df.mean(),df.std())
</code></pre>
<p>but then only the headers would be correctly displayed, and the values are in a mess:</p>
<pre><code>Avg St Dev
A 87.1717
B 87.0517
C 84.1717
D 86.8000
E 84.1705
dtype: float64A 1.354
B 0.789
C 1.221
D 3.214
E 4.170
dtype: float64
</code></pre>
| 1 | 2016-09-26T11:40:54Z | 39,702,045 | <p>My suggestion would be creating a new DataFrame with 2 columns(Avg & St Dev), and then just print the new DataFrame.</p>
| 1 | 2016-09-26T11:49:16Z | [
"python",
"formatting",
"special-characters"
]
|
How to screen print two columns of values from Pandas? | 39,701,881 | <p>Say I have a distribution which I have loaded in a <code>pandas</code> DataFrame. My data frame consists of 5 columns A to E, and I want to screen print the average and standard deviation next to each other:</p>
<pre><code>avg=df.mean()
stdev=df.std()
Avg St Dev
A 87.1717 A 1.354
B 87.0517 B 0.789
C 84.1717 C 1.221
D 86.8000 D 3.214
E 84.1705 E 4.170
</code></pre>
<p><strong>How can I do this by playing with the <code>print</code> formats?</strong> I might do the following</p>
<pre><code>print '%-10s' '%s' % ('Avg','St Dev')
print '%-10s' '%s' % (df.mean(),df.std())
</code></pre>
<p>but then only the headers would be correctly displayed, and the values are in a mess:</p>
<pre><code>Avg St Dev
A 87.1717
B 87.0517
C 84.1717
D 86.8000
E 84.1705
dtype: float64A 1.354
B 0.789
C 1.221
D 3.214
E 4.170
dtype: float64
</code></pre>
| 1 | 2016-09-26T11:40:54Z | 39,702,099 | <p>Maybe you could combine the two separate columns in a new dataframe (use pd.DataFrame(means,stds)). It should be easy to print this new dataframe with the columns next to each other (even though not most efficient).</p>
<p>Not sure if relevant, but you could use the pandas describe functionality? You can find it here: <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.describe.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.describe.html</a></p>
| 1 | 2016-09-26T11:51:49Z | [
"python",
"formatting",
"special-characters"
]
|
Calling class that initiates UI class in python | 39,701,920 | <p>I have an issue while creating my small Python project. I am used to Java and this is still quite new to me.
The problem is i create a UI class from QtCreator. Then convert it to <code>.py</code> and import to my project. I have a class that for now is considered <code>main</code> that initiates and runs the UI class. The problem is i need to have a class that is really the <code>main</code> class and when app is started this class to call the second class that initiates the UI.
To sum it up now when app is started i have <code>A > calls > B(UI)</code>.
I need it to be <code>A > calls > B > init > C(UI)</code>.
Is that possible? My idea is that B must be only a manager class that sets up the UI and run it.
Here is my working code so far:
1.Manager class- </p>
<pre><code>class mainpanelManager(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = mainpanelManager()
window.show()
sys.exit(app.exec_())
</code></pre>
<p>and UI class is typical UI generated class. I will post only constructor:</p>
<pre><code>class Ui_MainWindow(QtGui.QWindow):
def setupUi(self, MainWindow):
</code></pre>
<p>In this case <code>mainpaneManager</code> runs <code>Ui_MainWindow</code> after element initiation.
I want to have a 3rd class that calls <code>mainpanelManager</code>.
What do i do with this <code>__name__</code> function? Move it?
Thanks in advance!</p>
| 1 | 2016-09-26T11:42:47Z | 39,730,444 | <p>I'm not exactly sure I understand what you're asking for, but it would seem to be as simple as this:</p>
<pre><code>class Main(object):
def __init__(self):
self.window = MainPanelManager()
self.window.show()
class MainPanelManager(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.settingsButton.clicked.connect(self.editSettings)
self.loadSettings()
def editSettings(self):
dialog = SettingsDialog(self)
if dialog.exec_() == QtWidgets.QDialog.Accepted:
self.loadSettings()
def loadSettings(self):
# do stuff to load settings...
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
main = Main()
sys.exit(app.exec_())
</code></pre>
| 0 | 2016-09-27T17:01:12Z | [
"python",
"pyqt",
"qt5",
"qt-creator"
]
|
List length check not working in Sudoku checker | 39,701,964 | <p>I want to write some Python code to check that whether a matrix accords with the rule of Sudoku. My code is presented below:</p>
<pre><code>correct = [[1,2,3],
[2,3,1],
[3,1,2]]
incorrect = [[1,2,3,4],
[2,3,1,3],
[3,1,2,3],
[4,4,4,4]]
incorrect2 = [[1,2,3,4],
[2,3,1,4],
[4,1,2,3],
[3,4,1,2]]
incorrect3 = [[1,2,3,4,5],
[2,3,1,5,6],
[4,5,2,1,3],
[3,4,5,2,1],
[5,6,4,3,2]]
incorrect4 = [['a','b','c'],
['b','c','a'],
['c','a','b']]
incorrect5 = [ [1, 1.5],
[1.5, 1]]
def check_sudoku(matrix):
n = len(matrix)
# check each row
i, j = 0, 0
while i < n:
checked = []
while j < n:
if matrix[i][j] not in checked:
checked.append(matrix[i][j])
j += 1
if len(checked) < n:
return False
i += 1
# check each column
i, j = 0, 0
while i < n:
checked = []
while j < n:
if matrix[j][i] not in checked:
len(checked)
checked.append(matrix[j][i])
j += 1
if len(checked) < n:
return False
i += 1
return True
# the output should look like this:
print(check_sudoku(incorrect))
#>>> False
print(check_sudoku(correct))
#>>> True
print(check_sudoku(incorrect2))
#>>> False
print(check_sudoku(incorrect3))
#>>> False
print(check_sudoku(incorrect4))
#>>> False
print(check_sudoku(incorrect5))
#>>> False
</code></pre>
<p>But here's a weird problem in the if statement. After the two inner while loops, the statement "len(checked)" evaluates to 0 which should not be like that. I don't know what happened.</p>
| -1 | 2016-09-26T11:45:26Z | 39,702,280 | <p>You don't zeroing <code>j</code> variable in inner loops (both inner loops).</p>
<pre><code>i, j = 0, 0
while i < n:
checked = []
j = 0 # you need set j to zero in each run
# if you don't do this: j will be equal to n in second run
while j < n:
if matrix[i][j] not in checked:
checked.append(matrix[i][j])
j += 1
if len(checked) < n:
return False
i += 1
</code></pre>
<p>Also you need to check sub matrices.</p>
| 0 | 2016-09-26T12:00:18Z | [
"python"
]
|
List length check not working in Sudoku checker | 39,701,964 | <p>I want to write some Python code to check that whether a matrix accords with the rule of Sudoku. My code is presented below:</p>
<pre><code>correct = [[1,2,3],
[2,3,1],
[3,1,2]]
incorrect = [[1,2,3,4],
[2,3,1,3],
[3,1,2,3],
[4,4,4,4]]
incorrect2 = [[1,2,3,4],
[2,3,1,4],
[4,1,2,3],
[3,4,1,2]]
incorrect3 = [[1,2,3,4,5],
[2,3,1,5,6],
[4,5,2,1,3],
[3,4,5,2,1],
[5,6,4,3,2]]
incorrect4 = [['a','b','c'],
['b','c','a'],
['c','a','b']]
incorrect5 = [ [1, 1.5],
[1.5, 1]]
def check_sudoku(matrix):
n = len(matrix)
# check each row
i, j = 0, 0
while i < n:
checked = []
while j < n:
if matrix[i][j] not in checked:
checked.append(matrix[i][j])
j += 1
if len(checked) < n:
return False
i += 1
# check each column
i, j = 0, 0
while i < n:
checked = []
while j < n:
if matrix[j][i] not in checked:
len(checked)
checked.append(matrix[j][i])
j += 1
if len(checked) < n:
return False
i += 1
return True
# the output should look like this:
print(check_sudoku(incorrect))
#>>> False
print(check_sudoku(correct))
#>>> True
print(check_sudoku(incorrect2))
#>>> False
print(check_sudoku(incorrect3))
#>>> False
print(check_sudoku(incorrect4))
#>>> False
print(check_sudoku(incorrect5))
#>>> False
</code></pre>
<p>But here's a weird problem in the if statement. After the two inner while loops, the statement "len(checked)" evaluates to 0 which should not be like that. I don't know what happened.</p>
| -1 | 2016-09-26T11:45:26Z | 39,702,462 | <p>The problem is you're not initializing <code>j</code> properly for the two inner while loops. Here's your code and the indicated modifications to make it work:</p>
<pre><code>def check_sudoku(matrix):
n = len(matrix)
# check each row
# i, j = 0, 0
i = 0
while i < n:
j = 0 # added
checked = []
while j < n:
if matrix[i][j] not in checked:
checked.append(matrix[i][j])
j += 1
if len(checked) < n:
return False
i += 1
# check each column
# i, j = 0, 0
i = 0
while i < n:
j = 0 # added
checked = []
while j < n:
if matrix[j][i] not in checked:
checked.append(matrix[j][i])
j += 1
if len(checked) < n:
return False
i += 1
return True
</code></pre>
| 0 | 2016-09-26T12:11:19Z | [
"python"
]
|
List length check not working in Sudoku checker | 39,701,964 | <p>I want to write some Python code to check that whether a matrix accords with the rule of Sudoku. My code is presented below:</p>
<pre><code>correct = [[1,2,3],
[2,3,1],
[3,1,2]]
incorrect = [[1,2,3,4],
[2,3,1,3],
[3,1,2,3],
[4,4,4,4]]
incorrect2 = [[1,2,3,4],
[2,3,1,4],
[4,1,2,3],
[3,4,1,2]]
incorrect3 = [[1,2,3,4,5],
[2,3,1,5,6],
[4,5,2,1,3],
[3,4,5,2,1],
[5,6,4,3,2]]
incorrect4 = [['a','b','c'],
['b','c','a'],
['c','a','b']]
incorrect5 = [ [1, 1.5],
[1.5, 1]]
def check_sudoku(matrix):
n = len(matrix)
# check each row
i, j = 0, 0
while i < n:
checked = []
while j < n:
if matrix[i][j] not in checked:
checked.append(matrix[i][j])
j += 1
if len(checked) < n:
return False
i += 1
# check each column
i, j = 0, 0
while i < n:
checked = []
while j < n:
if matrix[j][i] not in checked:
len(checked)
checked.append(matrix[j][i])
j += 1
if len(checked) < n:
return False
i += 1
return True
# the output should look like this:
print(check_sudoku(incorrect))
#>>> False
print(check_sudoku(correct))
#>>> True
print(check_sudoku(incorrect2))
#>>> False
print(check_sudoku(incorrect3))
#>>> False
print(check_sudoku(incorrect4))
#>>> False
print(check_sudoku(incorrect5))
#>>> False
</code></pre>
<p>But here's a weird problem in the if statement. After the two inner while loops, the statement "len(checked)" evaluates to 0 which should not be like that. I don't know what happened.</p>
| -1 | 2016-09-26T11:45:26Z | 39,702,684 | <p>The main problem with your code is that you don't reset <code>j</code> to zero at the end of the inner loops. So when you try to check the second row (and subsequent rows) the <code>j</code> values are too big. The same problem occurs when you're testing the columns.</p>
<p>However, there are other problems with this logic, eg <code>[5,6,4,3,2]</code> tests as ok because it has 5 unique elements, but they aren't the right elements, they should be some permutation of <code>[1,2,3,4,5]</code>. Similarly, the matrix of strings and the matrix containing 1.5 are treated as valid instead of invalid.</p>
<p>But anyway, here's a repaired version that fixes the <code>j</code> initialization issue mentioned earlier.</p>
<pre><code>grids = [
[[1,2,3],
[2,3,1],
[3,1,2]],
[[1,2,3,4],
[2,3,1,3],
[3,1,2,3],
[4,4,4,4]],
[[1,2,3,4],
[2,3,1,4],
[4,1,2,3],
[3,4,1,2]],
[[1,2,3,4,5],
[2,3,1,5,6],
[4,5,2,1,3],
[3,4,5,2,1],
[5,6,4,3,2]],
[['a','b','c'],
['b','c','a'],
['c','a','b']],
[[1, 1.5],
[1.5, 1]],
]
def check_sudoku(matrix):
n = len(matrix)
# check each row
i = 0
while i < n:
checked = []
j = 0
while j < n:
if matrix[i][j] not in checked:
checked.append(matrix[i][j])
j += 1
if len(checked) < n:
return False
i += 1
# check each column
i = 0
while i < n:
checked = []
j = 0
while j < n:
if matrix[j][i] not in checked:
checked.append(matrix[j][i])
j += 1
if len(checked) < n:
return False
i += 1
return True
for g in grids:
for row in g:
print(row)
print(check_sudoku(g), end='\n\n')
</code></pre>
<p><strong>output</strong></p>
<pre><code>[1, 2, 3]
[2, 3, 1]
[3, 1, 2]
True
[1, 2, 3, 4]
[2, 3, 1, 3]
[3, 1, 2, 3]
[4, 4, 4, 4]
False
[1, 2, 3, 4]
[2, 3, 1, 4]
[4, 1, 2, 3]
[3, 4, 1, 2]
False
[1, 2, 3, 4, 5]
[2, 3, 1, 5, 6]
[4, 5, 2, 1, 3]
[3, 4, 5, 2, 1]
[5, 6, 4, 3, 2]
True
['a', 'b', 'c']
['b', 'c', 'a']
['c', 'a', 'b']
True
[1, 1.5]
[1.5, 1]
True
</code></pre>
<hr>
<p>Here's an alternative strategy which is more compact, and (potentially) faster because it uses Python's fast <code>all</code> function in conjunction with sets to do the testing. This version <em>only</em> considers a matrix to be valid if it contains the integers from 1 to <em>n</em>, where <em>n</em> is the size of the matrix.</p>
<pre><code>grids = [
[[1,2,3],
[2,3,1],
[3,1,2]],
[[1,2,3,4],
[2,3,1,3],
[3,1,2,3],
[4,4,4,4]],
[[1,2,3,4],
[2,3,1,4],
[4,1,2,3],
[3,4,1,2]],
[[1,2,3,4,5],
[2,3,1,5,6],
[4,5,2,1,3],
[3,4,5,2,1],
[5,6,4,3,2]],
[['a','b','c'],
['b','c','a'],
['c','a','b']],
[[1, 1.5],
[1.5, 1]],
]
def check_sudoku(matrix):
full = set(range(1, len(matrix) + 1))
return (all(set(row) == full for row in matrix)
and all(set(row) == full for row in zip(*matrix)))
for g in grids:
for row in g:
print(row)
print(check_sudoku(g), end='\n\n')
</code></pre>
<p><strong>output</strong></p>
<pre><code>[1, 2, 3]
[2, 3, 1]
[3, 1, 2]
True
[1, 2, 3, 4]
[2, 3, 1, 3]
[3, 1, 2, 3]
[4, 4, 4, 4]
False
[1, 2, 3, 4]
[2, 3, 1, 4]
[4, 1, 2, 3]
[3, 4, 1, 2]
False
[1, 2, 3, 4, 5]
[2, 3, 1, 5, 6]
[4, 5, 2, 1, 3]
[3, 4, 5, 2, 1]
[5, 6, 4, 3, 2]
False
['a', 'b', 'c']
['b', 'c', 'a']
['c', 'a', 'b']
False
[1, 1.5]
[1.5, 1]
False
</code></pre>
<p>This part: </p>
<pre><code>all(set(row) == full for row in zip(*matrix))
</code></pre>
<p>verifies that the columns are valid because <code>zip(*matrix)</code> essentially creates a transposed version of <code>matrix</code>.</p>
<p>The <code>all</code> function is quite efficient, and it stops testing as soon as it encounters a false-ish result. On a similar note, the <code>and</code> operator short-circuits, which means that the columns aren't checked if the rows aren't valid.</p>
| 0 | 2016-09-26T12:21:34Z | [
"python"
]
|
import another module or implement an existing call | 39,702,025 | <p>This may be a subjective question so I understand if it gets shut down, but this is something I've been wondering about ever since I started to learn python in a more serious way.</p>
<p>Is there a generally accepted 'best practice' about whether importing an additional module to accomplish a task more cleanly is better than avoiding the call and 'working around it'?</p>
<p>For example, I had some feedback on a script I worked on recently, and the suggestion was that I could have replaced the code below with a <code>glob.glob()</code> call. I avoided this at the time, because it meant adding another import that seemed unecessary to me (and the actual flow of filtering the lines just meshed with my thought process for the task).</p>
<pre><code>headers = []
with open(hhresult_file) as result_fasta:
for line in result_fasta:
if line.startswith(">"):
line = line.split("_")[0]
headers.append(line.replace(">",""))
</code></pre>
<p>Similarly, I decided to use an <code>os.rename()</code> call later in the script for moving some files rather than import <code>shutil</code>.</p>
<p>Is there a right answer here? Are there any overheads associated with calling additional modules and creating more dependencies (lets say for instance, that the module wasn't a built-in python module) vs. writing a slightly 'messier' code using modules that are already in your script?</p>
| 0 | 2016-09-26T11:48:29Z | 39,702,233 | <p>This is quite a broad question, but I'll try to answer it succinctly.</p>
<p>There is no real best practice, however, it is generally a good idea to recycle code that's already been written by others. If you find a bug in the imported code, it's more beneficial than finding one in your own code because you can submit a ticket to the author and have it fixed for potentially a large group of people.</p>
<p>There are certainly considerations to be made when making additional imports, mostly when they are not part of the Python standard library.<br>
Sometimes adding in a package that is a little bit too 'magical' makes code harder to understand, because it's another library or file that somebody has to look up to understand what is going on, versus just a few lines that might not be as sophisticated as the third party library, but get the job done regardless.</p>
<p>If you can get away with not making additional imports, you probably should, but if it would save you substantial amounts of time and headache, it's probably worth importing something that has been pre-written to deal with the problem you're facing.</p>
<p>It's a continual consideration that has to be made.</p>
| 1 | 2016-09-26T11:58:18Z | [
"python"
]
|
Confused as to where to use return statement in Python | 39,702,039 | <p>Sometimes I get confused as to <em>where</em> to use the return statement. I've done the Python track on codecademy and I'm halfway through an Intro to CS class online and <em>still</em> I get it wrong sometimes. I get what it does, it's just that I don't 'get' its placement properly :/</p>
<p>Here's a short example of the same code. </p>
<p>Correct way:</p>
<pre><code>def product_list(list_of_numbers):
c = 1
for e in list_of_numbers:
c = c * e
return c
</code></pre>
<p>Wrong way (which I did initially):</p>
<pre><code>def product_list(list_of_numbers):
c = 1
for e in list_of_numbers:
c = c * e
return c
</code></pre>
<p>This probably sounds silly to most of you, but in bigger and more complicated situations I get it properly confused. If someone can clarify it to me once and for all I'd appreciate that a lot.</p>
| 1 | 2016-09-26T11:48:57Z | 39,702,267 | <p><code>return</code> in a function means you are leaving the function immediately and returning to the place where you call it.
So you should use <code>return</code> when you are 100% certain that you wanna exit the function immediately.</p>
<p>In your example, I think you don't want to exit the function until you get the final value of c, so you should place the <code>return</code> outside of the loop.</p>
| 3 | 2016-09-26T11:59:25Z | [
"python"
]
|
Confused as to where to use return statement in Python | 39,702,039 | <p>Sometimes I get confused as to <em>where</em> to use the return statement. I've done the Python track on codecademy and I'm halfway through an Intro to CS class online and <em>still</em> I get it wrong sometimes. I get what it does, it's just that I don't 'get' its placement properly :/</p>
<p>Here's a short example of the same code. </p>
<p>Correct way:</p>
<pre><code>def product_list(list_of_numbers):
c = 1
for e in list_of_numbers:
c = c * e
return c
</code></pre>
<p>Wrong way (which I did initially):</p>
<pre><code>def product_list(list_of_numbers):
c = 1
for e in list_of_numbers:
c = c * e
return c
</code></pre>
<p>This probably sounds silly to most of you, but in bigger and more complicated situations I get it properly confused. If someone can clarify it to me once and for all I'd appreciate that a lot.</p>
| 1 | 2016-09-26T11:48:57Z | 39,703,342 | <p>You're putting too much emphasis on the impact of <code>return</code> on controlling the behaviour of the <code>for</code> loop. Instead, <code>return</code> applies to the function and happens to terminate the <code>for</code> loop prematurely by primarily bringing an end to the function. </p>
<p>Instead, you can control the behaviour of the <code>for</code> loop independently from the function itself using <code>break</code>. In addition, you can have multiple <code>return</code> statements in a function depending on what action should be taken in response to particular criteria (as in <code>my_func1</code>). Consider the following:</p>
<pre><code>import random
def my_func1(my_list, entry):
'''
Search a list for a specific entry. When found, terminate search
and return the list index immediately
Return False if not found
'''
print "\n Starting func1"
index = 0
for item in my_list:
if item != entry:
print "Not found yet at index: {}".format(index)
index += 1
else:
print "found item, at index {}".format(index)
print "Terminating function AND loop at same time"
return index
print "########### ENTRY NOT IN LIST. RETURN FAlSE #############"
return False
a = my_func1(['my', 'name', 'is', 'john'], 'is')
b = my_func1(['my', 'name', 'is', 'john'], 'harry')
def my_func2(my_list):
''' Iterate through a list
For first 4 items in list, double them and save result to a list that will
be returned, otherwise terminate the loop
Also, return another list of random numbers
'''
print '\n starting func2'
return_list = []
for i in range(len(my_list)):
if i < 4:
print 'Value of i is {}'.format(i)
return_list.append(my_list[i] * 2)
else:
print 'terminating for loop, but ** keep the function going **'
break
other_list = [random.randint(1, 10) for x in range(10)]
print 'Returning both lists'
return return_list, other_list
c = my_func2([x for x in range(10)])
</code></pre>
| 1 | 2016-09-26T12:50:29Z | [
"python"
]
|
How to open .bashrc in python | 39,702,043 | <p>I have a problem with opening the <code>.bashrc</code> file in python. I have written the following code:</p>
<pre><code>mydata = open ('/home/lpp/.bashrc', 'r')
</code></pre>
<p>and I get this:</p>
<pre><code>$ /usr/bin/python2.7 /home/lpp/lpp2016/Handin3.py
Process finished with exit code 0
</code></pre>
<p>Python does not open the file <code>.bashrc</code>. What did I do wrong? </p>
| 0 | 2016-09-26T11:49:08Z | 39,702,100 | <pre><code>fp = open(os.path.join((os.path.expanduser('~'), '.bashrc'))
fp.read()
</code></pre>
<p>it is opening and reading all the content</p>
| 0 | 2016-09-26T11:51:55Z | [
"python",
"python-2.7"
]
|
Task Scheduling in amazon EC2 ubuntu instance | 39,702,113 | <p>I'm trying to run a python script every 2 minutes in an amazon EC2 ubuntu instance and i've tried a lot of things that just aren't working.</p>
<p>Could someone help me? </p>
<p>Thanks!</p>
| -1 | 2016-09-26T11:52:23Z | 39,702,478 | <p>What you want to use is cron, a Unix service that allows you to schedule commands to be executed at certain times or intervals.</p>
<p>It is based on a simple configuration text file, the crontab (from "cron table", as in, the table with scheduled commands), which coincidentally is also the name of the tool to edit the file.</p>
<p>In order to edit your user's crontab, use this command: <code>crontab -e</code>
This will open your crontab file in a text editor.</p>
<p>Three things you will want to keep in mind about cron:</p>
<ol>
<li><p>You should specify the full path to your scripts, otherwise cron will not know where to find them.</p></li>
<li><p>There's a crontab for each user and the scheduled commands are executed as the user who owns the crontab file.</p></li>
<li><p>Cron's resolution doesn't go below the minutes, i.e., you can't execute something every X <em>seconds</em>.</p></li>
</ol>
<p>This should work for you:</p>
<p><code>*/2 * * * * /usr/bin/python /path/to/your/script.py</code></p>
<p>I suggest you have a look here: <a href="http://corntab.com/" rel="nofollow">http://corntab.com/</a>
Look at the syntax and the examples, it should be enough to get you going, as well as help you create more crontabs.</p>
| 1 | 2016-09-26T12:11:59Z | [
"python",
"amazon-web-services",
"amazon-ec2",
"task",
"schedule"
]
|
Django model which could be associated with two parents | 39,702,138 | <p>I've got a model in Django that I think it needs to be associated with two parents, but I'm trying to figure out how to code it.</p>
<p>The main problem is that we've got <code>Building</code> models that are linked with a <code>Headquarter</code>. Each <code>Headquarter</code> usually have an <code>ElectricSupply</code> that supplies electricity to all the heardquarter's buildings, but also, it's possible that each <code>Building</code> could have its own <code>ElectricSupply</code>.</p>
<p>Furthermore, each <code>ElectricSupply</code> is linked with one or more <code>ElectricBill</code> model which are stored by months.</p>
<p>So, in the end I must be able to get the <code>Headquarter</code> electric consumption, no matter if the supply is from the hearquarter or each building.</p>
<pre><code>class Headquarter(models.Model):
# ...
def get_consumption(self):
# Here I need to know where to look for the supply
class Building(models.Model):
# ...
headquarter = models.ForeignKey(Headquarter, related_name='buildings')
class ElectricSupply(models.Model):
# Here I don't know where to point, Headquarter or Building, or both?
class ElectricBill(models.Model):
# ...
supply = models.ForeignKey(ElectricSupply, related_name='bills')
</code></pre>
<p>Hope you can help me. Thanks.</p>
| 0 | 2016-09-26T11:53:18Z | 39,702,236 | <p>I think that every building should have ElectricSupply, so you should point to Building from ElectricSupply, and then if you want to find Headquarter you can easily get that from Building where you also have foreign key pointed to Headquarted. Also I think that every building should be in relationship with ElectricBill, so you should change your foreign key in ElectricBill to point on Building.</p>
| 0 | 2016-09-26T11:58:21Z | [
"python",
"django",
"design",
"foreign-keys",
"models"
]
|
Cannot import matplotlib with ipython/jupyter notebook | 39,702,152 | <p>Cannot import matplotlib with ipython/jupyter notebook through a virtual environment.</p>
<p>I'm able to import matplotlib just fine using the console. Having seen other SO posts I can't seem to get this set up right.</p>
<p>I followed <a href="http://help.pythonanywhere.com/pages/IPythonNotebookVirtualenvs" rel="nofollow">this</a> to get the separate ipython/jupyter kernel.</p>
<p>When I checked my locations through jupyter I get </p>
<p><code>six.__file__</code>: <code>'/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six.pyc'</code> </p>
<p>and </p>
<p><code>datutil.__file__</code>: <code>'/Library/Python/2.7/site-packages/dateutil/__init__.pyc'</code></p>
<p>I am not sure these are correct. Main jupyter error below</p>
<pre><code>---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-3-20188fbdb2fd> in <module>()
1
----> 2 import matplotlib.pyplot as plt
3 get_ipython().magic(u'matplotlib inline')
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/pyplot.py in <module>()
27 from matplotlib import docstring
28 from matplotlib.backend_bases import FigureCanvasBase
---> 29 from matplotlib.figure import Figure, figaspect
30 from matplotlib.gridspec import GridSpec
31 from matplotlib.image import imread as _imread
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/figure.py in <module>()
34 import matplotlib.colorbar as cbar
35
---> 36 from matplotlib.axes import Axes, SubplotBase, subplot_class_factory
37 from matplotlib.blocking_input import BlockingMouseInput, BlockingKeyMouseInput
38 from matplotlib.legend import Legend
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/axes.py in <module>()
18 import matplotlib.colors as mcolors
19 import matplotlib.contour as mcontour
---> 20 import matplotlib.dates as _ # <-registers a date unit converter
21 from matplotlib import docstring
22 import matplotlib.font_manager as font_manager
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/dates.py in <module>()
117
118
--> 119 from dateutil.rrule import (rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY,
120 MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY,
121 SECONDLY)
/Library/Python/2.7/site-packages/dateutil/rrule.py in <module>()
17
18 from six import advance_iterator, integer_types
---> 19 from six.moves import _thread
20 import heapq
21
ImportError: cannot import name _thread
</code></pre>
| 0 | 2016-09-26T11:54:00Z | 39,702,510 | <p>Ok I fixed this by using the tutorial properly (<a href="http://help.pythonanywhere.com/pages/IPythonNotebookVirtualenvs" rel="nofollow">http://help.pythonanywhere.com/pages/IPythonNotebookVirtualenvs</a>)</p>
<p>You need to set up a virtualenv, then make sure that you install jupyter within it. I was using the globally installed jupyter.</p>
<p>Then set up the new jupyter kernel (linked above) and everything should work with your virtualenv pointed to correctly</p>
| 0 | 2016-09-26T12:13:43Z | [
"python",
"python-2.7",
"matplotlib",
"virtualenv",
"jupyter"
]
|
Python Flask + Threaded function | 39,702,242 | <p>I would like to make a function, that runs in background and updates a variable every X minutes for my website. </p>
<p>Basically what I need is to cache some json data and update it every X minutes.</p>
<p>What would be the best way to do it? I tried "threading" and it seems to work, but when I run it with Flask, it runs itself 2 times every time. </p>
| 0 | 2016-09-26T11:58:31Z | 39,703,250 | <p>Well, you may use <a href="http://flask.pocoo.org/docs/0.11/patterns/celery/" rel="nofollow">Celery</a> to create delayed tasks to update your data.</p>
<p>But I don't think, that update variable directly is a good idea. So, store your data in cache or database. It depends on the frequency of how you use and update data.</p>
| 0 | 2016-09-26T12:46:07Z | [
"python",
"multithreading",
"caching",
"flask"
]
|
deleting (POPing) specific elements from list | 39,702,349 | <p>I am doing book exercise on pop() function in Python (3.5). The instructions are to delete elements from the list using pop(). From the list below, I want to delete n1, n4, n5, n6, n7, n8, n9. Below code works, but very practical) and I don't understand why specific index works only up until [5]. With out using loops (I'm not there yet), what is the proper way of poping specific elements from the list? </p>
<pre><code>nameList = ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9']
print('I can only invite two people to dinner...')
print('Sorry, but ', nameList.pop(0).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(3).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(4).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(5).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(-1).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(-1).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(-1).title(), ' will not be invited to
dinner')
</code></pre>
| 0 | 2016-09-26T12:04:41Z | 39,702,423 | <p>The output is: </p>
<pre><code>I can only invite two people to dinner...
('Sorry, but ', 'N1', ' will not be invited todinner')
('Sorry, but ', 'N5', ' will not be invited to dinner')
('Sorry, but ', 'N7', ' will not be invited to dinner')
('Sorry, but ', 'N9', ' will not be invited to dinner')
('Sorry, but ', 'N8', ' will not be invited to dinner')
('Sorry, but ', 'N6', ' will not be invited to dinner')
('Sorry, but ', 'N4', ' will not be invited to dinner')
</code></pre>
<p>Lets see it:</p>
<p>At first your list has 9 elements. You remove the first with <code>pop(0)</code> so now you have a list with 8 elements namely:</p>
<pre><code>['n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9']
</code></pre>
<p>Not you remove the 3th elelemnt from this 'new' list, which is <code>n5</code> (remember indexing starts from 0)</p>
<p>And so on ...</p>
<p>After each remove the list will simply be shorter, so even after the first remove there won be an element at the eighth position to remove (this happens after pop(5) in your case).</p>
<p>There is no 'general' way of removing elements from a list, but note that lists are mutable variables.</p>
| 2 | 2016-09-26T12:09:03Z | [
"python"
]
|
deleting (POPing) specific elements from list | 39,702,349 | <p>I am doing book exercise on pop() function in Python (3.5). The instructions are to delete elements from the list using pop(). From the list below, I want to delete n1, n4, n5, n6, n7, n8, n9. Below code works, but very practical) and I don't understand why specific index works only up until [5]. With out using loops (I'm not there yet), what is the proper way of poping specific elements from the list? </p>
<pre><code>nameList = ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9']
print('I can only invite two people to dinner...')
print('Sorry, but ', nameList.pop(0).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(3).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(4).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(5).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(-1).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(-1).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(-1).title(), ' will not be invited to
dinner')
</code></pre>
| 0 | 2016-09-26T12:04:41Z | 39,702,485 | <p>Well, the length of nameList changes dynamically every time you use 'pop'.
So after you pop 4 elements(n1,n4,n5,n6), there are only 5 elements left in nameList.
You can not use pop(5) anymore because the index is out of range at that time.</p>
| 1 | 2016-09-26T12:12:34Z | [
"python"
]
|
deleting (POPing) specific elements from list | 39,702,349 | <p>I am doing book exercise on pop() function in Python (3.5). The instructions are to delete elements from the list using pop(). From the list below, I want to delete n1, n4, n5, n6, n7, n8, n9. Below code works, but very practical) and I don't understand why specific index works only up until [5]. With out using loops (I'm not there yet), what is the proper way of poping specific elements from the list? </p>
<pre><code>nameList = ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9']
print('I can only invite two people to dinner...')
print('Sorry, but ', nameList.pop(0).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(3).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(4).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(5).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(-1).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(-1).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(-1).title(), ' will not be invited to
dinner')
</code></pre>
| 0 | 2016-09-26T12:04:41Z | 39,702,631 | <p>Specific index works like a charm for all indices <strong>up to the size of your list</strong>. The problem you're running into here is that when you remove an element from a list, you shrink it, the size is reduced by 1 every time you pop.</p>
<p>Say you have a list of 3 elements, <code>l = ["a","b","c"]</code>
You pop the first one <code>l.pop(0)</code>, that will return <code>"a"</code> but it will also modify the list so that now <code>l</code> is equal to <code>["b","c"]</code>.
If, instead, you had popped the last item with <code>l.pop(2)</code> or <code>l.pop(-1)</code> (because Python lets you count elements from the last one as well, so -1 is always the last element of the list), you would have gotten <code>"c"</code> and the list <code>l</code> would have become <code>["a","b"]</code>.
Notice that in both cases, the list has shrunk and has only two elements left, so you will not be able to pop the element number <code>2</code> now, since there is no such thing.</p>
<p>If you want to read an element instead of removing it from the list, use the <code>myList[elementIndex]</code> syntax. For instance, in your example, <code>nameList[6]</code> will return <code>"n7"</code> but it will not modify the list at all.</p>
| 0 | 2016-09-26T12:18:56Z | [
"python"
]
|
deleting (POPing) specific elements from list | 39,702,349 | <p>I am doing book exercise on pop() function in Python (3.5). The instructions are to delete elements from the list using pop(). From the list below, I want to delete n1, n4, n5, n6, n7, n8, n9. Below code works, but very practical) and I don't understand why specific index works only up until [5]. With out using loops (I'm not there yet), what is the proper way of poping specific elements from the list? </p>
<pre><code>nameList = ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9']
print('I can only invite two people to dinner...')
print('Sorry, but ', nameList.pop(0).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(3).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(4).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(5).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(-1).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(-1).title(), ' will not be invited to
dinner')
print('Sorry, but ', nameList.pop(-1).title(), ' will not be invited to
dinner')
</code></pre>
| 0 | 2016-09-26T12:04:41Z | 39,703,545 | <p>This happens because your list length changes every time you pop an element from the list. So if you want to use <code>pop</code> specifically, to remove the specified elements an easy and tricky way would be the following:</p>
<pre><code>>>> nameList = ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9']
>>>
>>> nameList.pop(nameList.index('n1'))
'n1'
>>> nameList.pop(nameList.index('n4'))
'n4'
>>> nameList.pop(nameList.index('n5'))
'n5'
>>> nameList.pop(nameList.index('n6'))
'n6'
>>> nameList.pop(nameList.index('n7'))
'n7'
>>> nameList.pop(nameList.index('n8'))
'n8'
>>> nameList.pop(nameList.index('n9'))
'n9'
>>> nameList
['n2', 'n3']
</code></pre>
<p>So as you can see every time we pop an element we specify its <code>index</code> so we don't have a problem that the list length changes - cause using <code>index</code> we will get the new index of the element! And as you can see the result will be: <code>['n2', 'n3']</code> as expected!</p>
| 0 | 2016-09-26T12:58:43Z | [
"python"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.