title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python calling C DLL function output issues and restype
39,173,454
<p>I was having this issue with my C++ DLL function. My C++ DLL function description goes like this: </p> <pre><code>// Combine the lower 32 bits and upper 8 bits of a 40 bit // integer into a 64 bit double precision floating point number // // Inputs: // - Lower: lower 32 bits of the 40 bit timestamp // - Upper: up...
0
2016-08-26T19:26:15Z
39,173,780
<p>Just like any C function, Python needs to know what the return type is, in order to convert it to it's own type. By default, python infers that the return type is an int - something that isn't always the case.</p> <p>In all cases, when the return type is not int, you need to explicitly state the return type for the...
1
2016-08-26T19:52:35Z
[ "python", "c++", "c", "dll" ]
Remove third-party installed Python on Mac?
39,173,459
<p>So I installed python 2.7.11 a few months ago, now the class I'm about to take uses 3. So I installed 3 and it works fine. I also uninstalled 2.7.11 by going to applications and removing it, but going to terminal and typing which python, the directory is <code>Library/Frameworks/Python.framework/Versions/2.7/bin/pyt...
0
2016-08-26T19:26:24Z
39,173,554
<p>This doesn't answer the question in the post's title, but leave Python 2 as the default <code>python</code>. If you want to run Python 3, you run <code>python3</code> or maybe <code>python3.4</code> or <code>python3.5</code>, depending on your installation. The system and other third-party software depend on <code>p...
1
2016-08-26T19:33:22Z
[ "python", "osx", "python-2.7" ]
How to create new calculated columns in pandas and remove original?
39,173,540
<p>I have a pandas dataframe 'df' that has:</p> <pre><code>name a b greg 1 1 george 2 2 giles 3 3 giovanni 4 5 </code></pre> <p>I want to run this dataframe through a calcuate function to create new columns: c and d such that I get the following resulting dataframe:</p> <pre><code>name c d greg 11 21 george 12 22 gi...
1
2016-08-26T19:32:23Z
39,173,583
<p>Row iteration is very slow. You are much better off doing something like the following:</p> <pre><code>df['c'] = df.a + 10 df['d'] = df.b + 20 df.drop(['a', 'b'], axis='columns', inplace=True) </code></pre> <p>To implement your method, however, you would need to do this:</p> <pre><code>df['c'], df['d'] = zip(*df...
0
2016-08-26T19:35:05Z
[ "python", "pandas" ]
How to combine an index "prefix" to the data in a Pandas series? Does one create a numpy array?
39,173,560
<p>I have a pandas series:</p> <pre><code>import pandas ser = pd.Series(...) ser idx1 23421535123415135 idx2 98762981356281343 idx3 394123942916498173 idx4 41234189756983411 ... idx50 123412938479283419 </code></pre> <p>I would like to combined the index append to the front of each data row. The ...
1
2016-08-26T19:33:41Z
39,173,803
<p>Say you start with your Series:</p> <pre><code> In [34]: s = pd.Series(data=[1, 2], index=['idx0', 'idx1']) </code></pre> <p>Then you can do </p> <pre><code>In [35]: t = s.reset_index() In [36]: t['index'].astype(str) + ' ' + t[0].astype(str) Out[36]: 0 idx0 1 1 idx1 2 dtype: object </code></pre> <p>Note...
1
2016-08-26T19:53:40Z
[ "python", "arrays", "pandas", "numpy" ]
How to combine an index "prefix" to the data in a Pandas series? Does one create a numpy array?
39,173,560
<p>I have a pandas series:</p> <pre><code>import pandas ser = pd.Series(...) ser idx1 23421535123415135 idx2 98762981356281343 idx3 394123942916498173 idx4 41234189756983411 ... idx50 123412938479283419 </code></pre> <p>I would like to combined the index append to the front of each data row. The ...
1
2016-08-26T19:33:41Z
39,174,103
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.cat.html" rel="nofollow">pandas.series.str.cat</a> :</p> <pre><code>In[8]:ser Out[8]: idx0 23421535123415135 idx1 98762981356281343 idx2 394123942916498173 idx3 41234189756983411 dtype: int64 In[9]:ser=pd.S...
1
2016-08-26T20:18:45Z
[ "python", "arrays", "pandas", "numpy" ]
number instead of date string when writing xlsx file
39,173,565
<p>In a LibreOffice xlsx cell, the value is like this: 01/13/2016. When I am creating a new xlsx file using python2, then that 01/13/2016 is converting to 42461.</p> <p>python code :</p> <pre><code>sheet1.write(row,col,sheet.cell(row,col).value) tab_matching = 0 for sheet_name in book.sheet_names(): temp_sheet_n...
1
2016-08-26T19:34:11Z
39,173,643
<p>You could do this.</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; today=datetime.datetime.now() &gt;&gt;&gt; today datetime.datetime(2016, 8, 27, 1, 7, 1, 909049) &gt;&gt;&gt; value=today.strftime("%d/%m/%Y") '27/08/2016' &gt;&gt;&gt; sheet1.write(row,col,sheet.cell(row,col).value) </code></pre>
0
2016-08-26T19:40:36Z
[ "python", "libreoffice", "xlsxwriter" ]
number instead of date string when writing xlsx file
39,173,565
<p>In a LibreOffice xlsx cell, the value is like this: 01/13/2016. When I am creating a new xlsx file using python2, then that 01/13/2016 is converting to 42461.</p> <p>python code :</p> <pre><code>sheet1.write(row,col,sheet.cell(row,col).value) tab_matching = 0 for sheet_name in book.sheet_names(): temp_sheet_n...
1
2016-08-26T19:34:11Z
39,176,297
<p><code>42461</code> is the underlying date value for 04/01/2016. To show the date instead of the number, specify a date format:</p> <pre><code>format1 = new_book.add_format({'num_format': 'mm/dd/yyyy'}) sheet1.write('B1', 42461, format1) # 04/01/2016 sheet1.write('B2', 42382, format1) # 01/13/2016 </code></pre> ...
2
2016-08-27T00:25:05Z
[ "python", "libreoffice", "xlsxwriter" ]
How to match nested italic font tags with Xpath?
39,173,604
<p>Consider an <code>xml</code> structure like the following</p> <pre><code>&lt;p class="long"&gt; &lt;i&gt;Malicious&lt;/i&gt; " is the adjective based on the noun " &lt;i&gt;malice&lt;/i&gt; ", which means the desire to harm others. Both words come from the latin word " &lt;/p&gt; </code></pre> <p>I want to...
-2
2016-08-26T19:36:51Z
39,173,868
<p>Try with</p> <pre><code>examples=tree.xpath('//p[@class="long"]//text()') </code></pre> <p>(with the double slash before <code>text()</code>, which also matches nodes that aren't direct children)</p>
0
2016-08-26T19:58:09Z
[ "python", "xpath", "lxml" ]
How to match nested italic font tags with Xpath?
39,173,604
<p>Consider an <code>xml</code> structure like the following</p> <pre><code>&lt;p class="long"&gt; &lt;i&gt;Malicious&lt;/i&gt; " is the adjective based on the noun " &lt;i&gt;malice&lt;/i&gt; ", which means the desire to harm others. Both words come from the latin word " &lt;/p&gt; </code></pre> <p>I want to...
-2
2016-08-26T19:36:51Z
39,174,710
<p>Avoid the use of text() unless you have very special requirements - for exactly this reason. You're probably interested in the string value of the <code>p</code> element, not in its child text and element nodes. Exactly how to select this depends on the environment (does your XPath API allow returning a string rathe...
1
2016-08-26T21:14:33Z
[ "python", "xpath", "lxml" ]
Mac OS X error: directory that is not on PYTHONPATH and which Python does not read ".pth" files from
39,173,637
<p>I'm getting an error while trying to install FEnicS on Mac OS X 10.11.6. I've read the responses to similar questions on this website, and have tried the suggested solutions, but I must be doing something wrong. </p> <p>On running the command:</p> <pre><code>curl -s https://fenicsproject.org/fenics-install.sh | ba...
0
2016-08-26T19:39:49Z
39,273,105
<p>This was resolved by the fenics support group. to install FEniCS on OS X, Docker is a more convenient option.</p>
0
2016-09-01T13:38:39Z
[ "python", "osx", "python-2.7", "pythonpath", "pth" ]
keep tracking time in while loop and interacting with other commands in python3
39,173,700
<p>So i created a while loop that the user input and an output is returned</p> <pre><code>choice = input() while True: if choice == "Mark": print("Zuckerberg") elif choice == "Sundar": print("Pichai") </code></pre> <p>and i want to keep time so when i hit Facebook is going to keep time for FB an...
-1
2016-08-26T19:45:29Z
39,173,757
<p>In the while loop you could count seconds like so.</p> <pre><code>import time a = 0 while True: a = a + 1 time.sleep(1) </code></pre> <p>That would mean that a is about how many seconds it look to do the while loop.</p>
0
2016-08-26T19:50:34Z
[ "python", "python-3.x", "input", "time", "while-loop" ]
I have a issue which is that I use TabularInline django 1.7 does not let me save
39,173,708
<p><img src="http://i.stack.imgur.com/S11GJ.png" alt=""></p> <p><img src="http://i.stack.imgur.com/uUalb.png" alt=""></p> <p>I have a problem which is that I use TabularInline Django 1.7 does not let me save shows me everything perfectly to give to keep me throws an error this is problem that I utlizando another data...
-2
2016-08-26T19:45:46Z
39,174,771
<p>Firstly, the images aren't very clear, but what I understand from your description of the problem is that the models do not have corresponding tables in the database. Please check/ share your configuration in settings.py and run</p> <pre><code>python manage.py makemigrations </code></pre> <p>and</p> <pre><code>py...
0
2016-08-26T21:19:49Z
[ "python", "django" ]
Server-side implementation of instagram-like tags
39,173,717
<p>I'm looking for some pythonic way to implement instagram-like tags functionality.</p> <p>Let's suppose my Tag Model is:</p> <pre><code>class Tag(models.Model): slug = models.SlugField(max_length=120, unique=True) products = models.ManyToManyField(Product) def get_absolute_url(self): return rev...
0
2016-08-26T19:46:47Z
39,174,717
<p>I would suggest use of another model to link the Tags to the Comments. This model will have the tag and comment both as Many to Many relations. Now this model can be used to establish relations and perform operations. Rest depends on your logic, how well you use this model.</p>
0
2016-08-26T21:15:30Z
[ "python", "django" ]
Reshaping pyspark dataframe to 4-dimensional numpy array for Keras/Theano
39,173,761
<p>I'm trying to get a spark dataframe, traindf into a 4-d numpy array. I've tried this:</p> <pre><code>traindf = sqlContext.createDataFrame([ (1, 1, 2, 3), (1, 2, 2, 3), (1, 3, 2, 3), (1, 4, 2, 3), (2, 4, 5, 6), (2, 4, 5, 6), (3, 7, 8, 9), (2, 4, 5, 6), (3, 7, 8, 9), (3, 7, 8, ...
0
2016-08-26T19:50:59Z
39,174,017
<p>Just figured it out, tack this onto the end</p> <pre><code>x = np.reshape(x, (5, 1, 2, 4)) </code></pre>
0
2016-08-26T20:12:06Z
[ "python", "numpy", "apache-spark", "pyspark", "keras" ]
Making dynamic lists to print out variables
39,173,784
<p>How can I make a dynamic list and then print it out, this example is just an idea of what I want to do, the lists could be in the hundreds. </p> <p>But I want anything that has cat to print "cat" with any value associated with it listed below it,</p> <p>data = [["cat","one"], ["dog", "one"], ["cat", "ten"], ["fro...
-1
2016-08-26T19:52:48Z
39,173,809
<p>You can use a defaultdict.</p> <pre><code>from collections import defaultdict groups = defaultdict(list) for animal, value in data: groups[animal].append(value) for animal, values in groups.items(): print(animal) for value in values: print(value) </code></pre>
6
2016-08-26T19:54:23Z
[ "python" ]
Making dynamic lists to print out variables
39,173,784
<p>How can I make a dynamic list and then print it out, this example is just an idea of what I want to do, the lists could be in the hundreds. </p> <p>But I want anything that has cat to print "cat" with any value associated with it listed below it,</p> <p>data = [["cat","one"], ["dog", "one"], ["cat", "ten"], ["fro...
-1
2016-08-26T19:52:48Z
39,173,900
<p>You can also use <code>setdefault</code>.</p> <pre><code>result = {} for animal, value in data: result.setdefault(animal, []).append(value) print(result) </code></pre>
0
2016-08-26T20:01:32Z
[ "python" ]
Pandas: convert dtype 'object' to int
39,173,813
<p>I've read an SQL query into Pandas and the values are coming in as dtype 'object', although they are strings, dates and integers. I am able to convert the date 'object' to a Pandas datetime dtype, but I'm getting an error when trying to convert the string and integers.</p> <p>Here is an example:</p> <pre><code>&gt...
0
2016-08-26T19:54:30Z
39,216,001
<p>Documenting the answer that worked for me based on the comment by @piRSquared. </p> <p>I needed to convert to a string first, then an integer.</p> <pre><code>&gt;&gt;&gt; df['purchase'].astype(str).astype(int) </code></pre>
0
2016-08-29T22:14:43Z
[ "python", "pandas", "numpy" ]
Appending to a dataframe's multi-index and restacking in pandas
39,173,829
<p>How do I append to a dataframe's multi-index and restack by the new index column's sort order?</p> <p>I have a dataframe with a multi-index <code>['section_id','last_checkout']</code> that represents books in a library as follows:</p> <pre><code> book_id author_id se...
0
2016-08-26T19:55:15Z
39,187,545
<p>Here is a solution for you.</p> <p>First the way you are defining your series is quite unorthodox. Best to define the series as:</p> <pre><code>test = pd.Series([1,1,2,1,2,3,4,1],name='floor') </code></pre> <p>then take your multi-index data-frame and reset the index. To "append"/vertically stack a column use 'jo...
0
2016-08-28T02:36:41Z
[ "python", "pandas" ]
compute the difference of all possible rows
39,173,897
<p>Based on a selection <code>ds</code> of a dataframe <code>d</code> with:</p> <p><code>{ 'x': d.x, 'y': d.y, 'a':d.a, 'b':d.b, 'c':d.c 'row:d.n'})</code> </p> <p>Having <code>n</code> rows, <code>x</code> ranges from <code>0</code> to <code>n-1</code>. The column <code>n</code> is needed since it's a selection and ...
0
2016-08-26T20:01:14Z
39,176,214
<p>You can use <code>itertools.combinations()</code> to generate the pairs:</p> <p>Read data first:</p> <pre><code>import pandas as pd from io import StringIO import numpy as np text = """ x y a b c n 554.607085 400.971878 9789 4151 6837 146 512.231450 405.469...
1
2016-08-27T00:08:43Z
[ "python", "pandas" ]
compute the difference of all possible rows
39,173,897
<p>Based on a selection <code>ds</code> of a dataframe <code>d</code> with:</p> <p><code>{ 'x': d.x, 'y': d.y, 'a':d.a, 'b':d.b, 'c':d.c 'row:d.n'})</code> </p> <p>Having <code>n</code> rows, <code>x</code> ranges from <code>0</code> to <code>n-1</code>. The column <code>n</code> is needed since it's a selection and ...
0
2016-08-26T20:01:14Z
39,177,020
<p>This approach makes good use of Pandas and the underlying numpy capabilities, but the matrix manipulations are a little hard to keep track of:</p> <pre><code>import pandas as pd, numpy as np ds = pd.DataFrame( [ [554.607085, 400.971878, 9789, 4151, 6837, 146], [512.231450, 405.469524, 8796...
1
2016-08-27T02:55:50Z
[ "python", "pandas" ]
Floodfill segmented image in numpy/python
39,173,947
<p>I have a numpy array which represents a segmented 2-dimensional matrix from an image. Basically, it's a sparse matrix with a bunch of closed shapes that are the outlines of the segments of the image. What I need to do is colorize the empty pixels within each closed shape with a different color/label in numpy. </p> ...
0
2016-08-26T20:05:30Z
39,181,829
<p>I'm assuming that your matrix is binary where non-zero values represent the extracted segments and zero values are values you don't care about. The <code>scikit-image</code> <code>label</code> function from the <code>measure</code> module may be of interest: <a href="http://scikit-image.org/docs/dev/api/skimage.mea...
0
2016-08-27T13:44:53Z
[ "python", "image", "numpy", "image-processing", "image-segmentation" ]
Drop all data in a pandas dataframe
39,173,992
<p>I would like to drop all data in a pandas dataframe, but am getting <code>TypeError: drop() takes at least 2 arguments (3 given)</code>. I essentially want a blank dataframe with just my columns headers.</p> <pre><code>import pandas as pd web_stats = {'Day': [1, 2, 3, 4, 2, 6], 'Visitors': [43, 43, 34...
1
2016-08-26T20:09:10Z
39,174,024
<p>You need to pass the labels to be dropped.</p> <pre><code>df.drop(df.index, inplace=True) </code></pre> <p>By default, it operates on <code>axis=0</code>.</p> <p>You can achieve the same with <code>df.iloc[0:0]</code>.</p>
4
2016-08-26T20:12:46Z
[ "python", "python-2.7", "pandas" ]
Faster AUC in sklearn or python
39,174,005
<p>I have over half a million pairs of true labels and predicted scores (the length of each 1d array varies and can be between 10,000-30,000 in length) that I need to calculate the AUC for. Right now, I have a for-loop that calls:</p> <pre><code># Simple Example with two pairs of true/predicted values instead of 500,0...
0
2016-08-26T20:10:37Z
39,174,643
<blockquote> <p>Is there a faster/better way to do this?</p> </blockquote> <p>Since the calculation of each true/pred pair is independent (if I understood your setup), you should be able to reduce total processing time by using <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow"><code>mul...
1
2016-08-26T21:09:28Z
[ "python", "scikit-learn", "data-science", "auc" ]
Faster AUC in sklearn or python
39,174,005
<p>I have over half a million pairs of true labels and predicted scores (the length of each 1d array varies and can be between 10,000-30,000 in length) that I need to calculate the AUC for. Right now, I have a for-loop that calls:</p> <pre><code># Simple Example with two pairs of true/predicted values instead of 500,0...
0
2016-08-26T20:10:37Z
39,178,912
<blockquote> <p>find a better way to vectorize the AUC calculation so that it can be broadcasted across multiple rows</p> </blockquote> <p>Probably not - sklearn already uses efficient numpy operations for its calculation of relevant parts:</p> <pre><code># -- calculate tps, fps, thresholds # sklearn.metrics.rank...
0
2016-08-27T08:07:11Z
[ "python", "scikit-learn", "data-science", "auc" ]
Why is there no lookup method for Python sets?
39,174,020
<p>In Python, objects can be equal despite not being the same object (<code>==</code> vs. <code>is</code>). Consider the following sequence for arbitrary objects <code>obj1</code> and <code>obj2</code>.</p> <pre><code>assert obj1 == obj2 assert obj1 is not obj2 s = set((obj1,)) del obj1 </code></pre> <p>Is there a ge...
0
2016-08-26T20:12:18Z
39,174,042
<p>No, sets are not mappings, If <code>obj1 == obj2</code>, it <em>should not matter</em>. Sets are there to test membership and to hold unique <em>values</em> (as defined by equality), not to map back to specific objects. Use a dictionary for that instead.</p> <p>Otherwise, you'd have to iterate and pick the one obje...
7
2016-08-26T20:14:21Z
[ "python", "set" ]
Webcam is still held even after Python program ends
39,174,086
<p>I'm trying to use my webcam <a href="http://www.trust.com/en/product/16428-spotlight-webcam-pro" rel="nofollow">Trust Spotlight Webcam PRO</a> with Python and OpenCV and I have a problem with holding the webcam after the program ends.</p> <p>Simple script:</p> <pre><code>import cv2 vc = cv2.VideoCapture(1) while ...
0
2016-08-26T20:17:23Z
39,179,842
<p>It seems there really probably was some (for me hidden) process, what still held the camera. When I shut down my laptop and turn it back on everything works fine.</p>
0
2016-08-27T10:03:56Z
[ "python", "opencv", "webcam" ]
Create a dynamic nested dictionary in python using for loop
39,174,170
<p>I am new to Python, and trying to learn it "on the job". And I am required to do this.</p> <p>Is it possible to create a 'dictionary1' dynamically which takes another 'dictionary2' as value, where 'dictionary2' is also getting updated in every for loop. Basically in terms of code, I tried:</p> <pre><code>fetch_val...
3
2016-08-26T20:25:24Z
39,174,455
<p>There are two problems:</p> <ol> <li>You needed to create a copy of the result dictionary when you set a key in <code>ret</code> to it. Otherwise, it will always hold a reference back to the same dictionary.</li> <li>With that change, you would be keeping the last <code>ret</code> dictionary (containing <code>{'0':...
2
2016-08-26T20:50:49Z
[ "python", "for-loop", "dictionary", "nested", "dictionary-comprehension" ]
Map pandas dataframe on multiple keys as columns or multiIndex
39,174,255
<p>Setup: two pandas dataframes; data from df2 needs to be added to df1, as explained below:</p> <ul> <li>df1 and df2 are multiIndexed with the same four levels</li> <li>df1 contains more rows than df2</li> <li>df1 has three copies (in rows) of a value per unique combination of three out of the four levels of the inde...
0
2016-08-26T20:32:11Z
39,182,675
<p>You can temporarily change <code>df1</code> to change the index to do the join:</p> <pre><code>df_combined = df1.reset_index(3).join(df2,how='left') &gt;&gt;&gt; df_combined level_3 x y Apr CA SC Q1 1 NaN SC Q2 2 NaN SC Q3 3 NaN Dec FL Mia Q1 6 0.3 ...
1
2016-08-27T15:18:29Z
[ "python", "pandas" ]
Python: OLS Regression does not generate intercept
39,174,317
<p>Can someone please tell me where I'm missing as the summary output does not provide constant at all though I have explicitly called it out? My df is 6212 rows × 64 columns. Thanks much.</p> <pre><code>import statsmodels.api as sm from statsmodels.api import add_constant y1 = df.ix[:,-1:] x1 = df.ix[:,16:-1] x...
1
2016-08-26T20:38:06Z
39,174,452
<p>Check your data to see if it already has a column with variance zero. <code>add_constant()</code> will not, by default, add a constant column to your dataset if it already has a zero-variance column; you should explicitly tell it to add the constant even if a zero-variance column exists:</p> <pre><code>x1 = add_con...
1
2016-08-26T20:50:27Z
[ "python", "regression" ]
can't invoke "canvas" command: application has been destroyed
39,174,438
<p>When I typed the following code as per the <a href="http://greenteapress.com/wp/think-python/" rel="nofollow">Think Python</a> text book, I'm getting the error message below.</p> <p>The window does actually get displayed, but it doesn't contain the desired content.</p> <pre><code>from swampy.World import World wor...
1
2016-08-26T20:49:33Z
39,174,522
<p>The main application loop needs to be pretty much the last thing you run in your application. So move <code>world.mainloop()</code> to the end of your code like this:</p> <pre><code>from swampy.World import World world = World() canvas = world.ca(width=500, height=500, background='white') bbox = [[-150, -100], [1...
3
2016-08-26T20:56:47Z
[ "python", "python-2.7", "python-3.x" ]
How to make multiple windows through a loop?
39,174,446
<p>I'm a beginner python coder and I'm trying to make a GUI where you can enter information for multiple semesters. Once the user inputs the number of semesters, I want to ask about each semester individually but when I use a loop to do this, all of the windows open at once. Is there a way to put them into a sequence?<...
1
2016-08-26T20:49:54Z
39,205,399
<p>Something like this should get you on your way:</p> <pre><code>from Tkinter import * ## Define root and geometry root = Tk() root.geometry('200x200') # Define Frames win1, win2, win3 = Frame(root, bg='red'), Frame(root, bg='green'), Frame(root, bg='blue') # Configure Rows root.grid_rowconfigure(0, weight = 1) ro...
0
2016-08-29T11:38:18Z
[ "python", "tkinter" ]
Merge Dictionaries Preserving Old Keys and New Values
39,174,616
<p>I'm writing a Python script that parses RSS feeds. I want to maintain a dictionary of entries from the feed that gets updated periodically. Entries that no longer exist in the feed should be removed, new entries should get a default value, and the values for previously seen entries should remain unchanged.</p> <p>T...
1
2016-08-26T21:06:17Z
39,174,642
<p>This should be more efficient, since you are no longer iterating through the entire old.items(). Additionally, it's more clear what you are trying to do this way since you aren't overwriting some values.</p> <pre><code>for k, v in new.items(): if k in old.keys(): out[k] = old[k] else: out[k] = ...
2
2016-08-26T21:09:23Z
[ "python", "dictionary" ]
Merge Dictionaries Preserving Old Keys and New Values
39,174,616
<p>I'm writing a Python script that parses RSS feeds. I want to maintain a dictionary of entries from the feed that gets updated periodically. Entries that no longer exist in the feed should be removed, new entries should get a default value, and the values for previously seen entries should remain unchanged.</p> <p>T...
1
2016-08-26T21:06:17Z
39,174,645
<p>Dictionaries have <a href="https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects" rel="nofollow"><em>dictionary view objects</em></a> that act as sets. Use these to get the intersection between old and new:</p> <pre><code>def merge_preserving_old_values_and_new_keys(old, new): result = new.cop...
4
2016-08-26T21:09:33Z
[ "python", "dictionary" ]
Merge Dictionaries Preserving Old Keys and New Values
39,174,616
<p>I'm writing a Python script that parses RSS feeds. I want to maintain a dictionary of entries from the feed that gets updated periodically. Entries that no longer exist in the feed should be removed, new entries should get a default value, and the values for previously seen entries should remain unchanged.</p> <p>T...
1
2016-08-26T21:06:17Z
39,174,719
<pre><code>old = { 'a': 1, 'b': 2, 'c': 3 } new = { 'c': 'x', 'd': 'y', 'e': 'z' } def merge_preserving_old_values_and_new_keys(o, n): out = {} for k in n: if k in o: out[k] = o[k] else: out[k] = n[k] return out print merge_preserving_old_val...
0
2016-08-26T21:15:37Z
[ "python", "dictionary" ]
Merge Dictionaries Preserving Old Keys and New Values
39,174,616
<p>I'm writing a Python script that parses RSS feeds. I want to maintain a dictionary of entries from the feed that gets updated periodically. Entries that no longer exist in the feed should be removed, new entries should get a default value, and the values for previously seen entries should remain unchanged.</p> <p>T...
1
2016-08-26T21:06:17Z
39,175,047
<p>I'm not 100% the best way to add this information to the discussion: feel free to edit/redistribute it if necessary.</p> <p>Here are timing results for all of the methods discussed here.</p> <pre><code>from timeit import timeit def loop_merge(old, new): out = {} for k, v in new.items(): if k in ol...
0
2016-08-26T21:47:17Z
[ "python", "dictionary" ]
python printing with os.startfile on windows
39,174,681
<p>I tried to printing an image with </p> <pre><code>os.startfile("pathroimage", "print") </code></pre> <p>It opens windows printing dialog. How can I print iages in background. Is there another way to do printing with python. </p> <p>regards.</p>
1
2016-08-26T21:12:09Z
39,283,123
<p>on windows i use win32</p> <p>Check this: <a href="http://timgolden.me.uk/python/win32_how_do_i/print.html" rel="nofollow">http://timgolden.me.uk/python/win32_how_do_i/print.html</a></p> <p>or this: <a href="http://nullege.com/codes/show/src@c@o@colony_plugins-HEAD@printing@src@printing@win32@system.py" rel="nofol...
0
2016-09-02T01:35:55Z
[ "python", "printing" ]
label a point in graph using matplotlib for timeseries
39,174,694
<p>I have a pandas dataframe with 3 columns. I plot col1 on Y axis and a time_stamps series on X axis. For this series whenever col2 is -1, I want to highlight that point on graph as anomaly. I tried to get the coordinate and highlight using ax.text but I cannot get the correct coordinate since X axis is a time series....
0
2016-08-26T21:13:19Z
39,175,835
<p>I figured it out that I can convert it to seconds and then label the points as anomalies. This is what i did.</p> <pre><code>def changetotimedelta(row): return pd.to_timedelta(row["time_stamps"])/ np.timedelta64(1,'D') def main() df=pd.read_csv(inputFile) df["time"]=df.apply(changetotimedelta,axis=1) ...
1
2016-08-26T23:16:45Z
[ "python", "pandas", "matplotlib", "dataframe", "time-series" ]
Reading file as array
39,174,768
<p>I have a <em>cvs</em> file which has three columns of numbers up to three digits each:</p> <pre><code>1 0 0 2 0 0 3 0 0 4 0 0 5 0 0 6 0 0 7 0 0 8 0 0 9 0 0 10 0 0 11 0 0 </code></pre> <p>I want to read the columns separately and be able to use them as arrays with:</p> <pre><code>data = np.loadtxt('file.csv') x = ...
0
2016-08-26T21:19:29Z
39,175,474
<p>Simplest solution to this could be to use pandas module in python, it gives the freedom to use column values as numpy array, which you can convert to list easily.</p> <pre><code> import pandas as pd df = pd.read_csv(open("name_of_the_csv.csv")) # For one column, lets say the 1st one column_1_list = ...
0
2016-08-26T22:31:05Z
[ "python", "arrays", "numpy" ]
Reading file as array
39,174,768
<p>I have a <em>cvs</em> file which has three columns of numbers up to three digits each:</p> <pre><code>1 0 0 2 0 0 3 0 0 4 0 0 5 0 0 6 0 0 7 0 0 8 0 0 9 0 0 10 0 0 11 0 0 </code></pre> <p>I want to read the columns separately and be able to use them as arrays with:</p> <pre><code>data = np.loadtxt('file.csv') x = ...
0
2016-08-26T21:19:29Z
39,175,524
<p>With your sample:</p> <pre><code>In [1]: data=np.loadtxt('stack39174768.txt') In [2]: data Out[2]: array([[ 1., 0., 0.], [ 2., 0., 0.], [ 3., 0., 0.], [ 4., 0., 0.], [ 5., 0., 0.], [ 6., 0., 0.], [ 7., 0., 0.], [ 8., 0., 0.], ...
0
2016-08-26T22:37:57Z
[ "python", "arrays", "numpy" ]
Read data from large tar.gz file from the website
39,174,778
<p>1) How should I read the data from all the csv files in the tar.gz file on website and write them to the CSVs on a folder in the most memory and space efficient way? 2) How can I loop it to go over all the CSVs in the tar.gz file? 3) Since the CSV files are huge, how can I loop it to read and write, let's say, 1 mi...
0
2016-08-26T21:20:32Z
39,176,276
<ol> <li>Download an archive to your local storage.</li> <li>Display the list of files in the archive. Run <strong>man tar</strong> to see options for command line.</li> <li>Extract files one by one from the archive.</li> <li>Use SAX xml parser <a href="https://docs.python.org/2/library/xml.sax.reader.html" rel="nofoll...
-1
2016-08-27T00:22:08Z
[ "python", "python-2.7", "csv", "urllib2", "tar" ]
how np.argsort works in pandas data frame
39,174,810
<p>i have pandas dataframe named "index" like</p> <pre><code>tz 521.0 Africa/Cairo 3.0 Africa/Casablanca 1.0 Africa/Ceuta 2.0 Africa/Johannesburg 1.0 dtype: float64 </code></pre> <p>when i applied <code>index.argsort()</code> i get something like this</p>...
0
2016-08-26T21:23:46Z
39,175,107
<p><code>argsort</code> returns the index positions of the values being sorted if they were to be sorted. Keep in mind that this is a numpy function and its assignment to series or dataframe indices is erroneous.</p> <ul> <li><code>2</code> refers to the item in the <code>2</code> position (3rd) was the minimum <ul>...
0
2016-08-26T21:53:03Z
[ "python", "python-3.x", "pandas", "numpy" ]
Archive Dynamodb based on date/days
39,174,834
<p>I want to archive dynamodb table, keeping data only for 90 days. I have a field called recorded_on in the table which I can use to track 90days. Looked at Datapipeline and it seems little overkill with EMR since we don't need it. Any better ways to do this? </p> <pre><code>1. Cronjob that will continue to run every...
0
2016-08-26T21:26:36Z
39,177,213
<p>Why do you think using AWS data pipeline is overkill? You can use custom job but it will require additional work which pipeline does it for you automatically. </p> <p>The fact that it uses EMR cluster behind the scenes shouldn't be a problem as its details are anyway abstracted away from you. Setting up pipeline to...
0
2016-08-27T03:35:02Z
[ "python", "amazon-s3", "amazon-dynamodb", "boto3", "amazon-data-pipeline" ]
Archive Dynamodb based on date/days
39,174,834
<p>I want to archive dynamodb table, keeping data only for 90 days. I have a field called recorded_on in the table which I can use to track 90days. Looked at Datapipeline and it seems little overkill with EMR since we don't need it. Any better ways to do this? </p> <pre><code>1. Cronjob that will continue to run every...
0
2016-08-26T21:26:36Z
39,180,460
<p>You could create a scheduled Lambda function that runs daily (or at whatever interval you want) that performs the query and archives the items. </p> <p>Or, if you want that to scale and perform better, you could have the Lambda function perform the query and then write a message to an SNS topic for each item that ...
0
2016-08-27T11:10:09Z
[ "python", "amazon-s3", "amazon-dynamodb", "boto3", "amazon-data-pipeline" ]
number of weeks in a given month python
39,174,857
<p>I'm trying to get the number of weeks in any month. for example:</p> <p><code>for this month August 2016, the days of the month streches over 5 weeks. while for October 2016 the number of weeks are 6</code>. </p> <p>Is there any elegant way to find out this number? tried using calendar and datetime but I couldn't ...
0
2016-08-26T21:28:14Z
39,174,902
<p>Here's a quicky:</p> <pre><code>&gt;&gt;&gt; import calendar &gt;&gt;&gt; print calendar.month(2016,10) October 2016 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 </code></pre> <p>Count the lines :)</p> <pre><code>len(calendar....
3
2016-08-26T21:32:23Z
[ "python", "calendar" ]
number of weeks in a given month python
39,174,857
<p>I'm trying to get the number of weeks in any month. for example:</p> <p><code>for this month August 2016, the days of the month streches over 5 weeks. while for October 2016 the number of weeks are 6</code>. </p> <p>Is there any elegant way to find out this number? tried using calendar and datetime but I couldn't ...
0
2016-08-26T21:28:14Z
39,174,914
<p>First thing that comes to mind: get the week number for the first day of the month, and the week number of the last day of the month. The number of weeks strechted by the month is then the difference of the week numbers.</p> <p>To get the week number for a date: <a href="http://stackoverflow.com/questions/2600775/h...
1
2016-08-26T21:33:42Z
[ "python", "calendar" ]
Django CustomField inheritance from models.CharField -- unexpected keyword argument
39,174,935
<p>My application needs few attributes that are required for the fields, so I went and followed the code to create <a href="https://docs.djangoproject.com/en/1.10/howto/custom-model-fields/" rel="nofollow">custom fields</a>. </p> <p>This is my CustomCharacterField:</p> <pre><code>class CustomCharField(models.CharFiel...
0
2016-08-26T21:36:06Z
39,175,041
<p>It is because of the order in which you pass the arguments. The trace back shows that success_order is being passed to the constructor of CharField, which should not be. This is because it is being passed in kwargs. Changing the order should do the trick. unique=True will be accepted by the CharField constructor.</p...
-1
2016-08-26T21:46:40Z
[ "python", "django", "postgresql", "django-models" ]
Django CustomField inheritance from models.CharField -- unexpected keyword argument
39,174,935
<p>My application needs few attributes that are required for the fields, so I went and followed the code to create <a href="https://docs.djangoproject.com/en/1.10/howto/custom-model-fields/" rel="nofollow">custom fields</a>. </p> <p>This is my CustomCharacterField:</p> <pre><code>class CustomCharField(models.CharFiel...
0
2016-08-26T21:36:06Z
39,175,045
<p>I think you just have a typo here - <code>def __int__</code> should be <code>def __init__</code>, and the <code>super(...).__int__(..)</code> call should be <code>super(...).__init__(..)</code>.</p>
3
2016-08-26T21:47:10Z
[ "python", "django", "postgresql", "django-models" ]
python code with lambda and filter
39,175,195
<p>Can anyone help me understand the following piece of python code:</p> <pre><code>for i, char in filter(lambda x: x[1] in str1, enumerate(str2)): # do something here ... </code></pre> <p>str1 and str2 are strings, I sort of understand that the "lambda x: x[1] in str1" is filtering condition, but why x[1] ?</p> ...
0
2016-08-26T22:00:55Z
39,175,228
<p>Because of <code>enumerates</code>.</p> <p>Enumerates returns tuples of <code>(index, value)</code> for an iterable of values.</p> <p><code>x</code> is a tuple of index, char.</p> <p>I would write <code>lambda (index, char): char in str1</code> for clarity</p>
0
2016-08-26T22:03:55Z
[ "python", "lambda", "filter" ]
python code with lambda and filter
39,175,195
<p>Can anyone help me understand the following piece of python code:</p> <pre><code>for i, char in filter(lambda x: x[1] in str1, enumerate(str2)): # do something here ... </code></pre> <p>str1 and str2 are strings, I sort of understand that the "lambda x: x[1] in str1" is filtering condition, but why x[1] ?</p> ...
0
2016-08-26T22:00:55Z
39,175,251
<p>This appears functionality equivalent to:</p> <pre><code>for i, char in enumerate(str2): if char in str1: # do something here </code></pre> <p><code>filter</code> is taking a list of tuples consisting of the index and elements of <code>str2</code>, filtering out those elements that do not appear in <co...
3
2016-08-26T22:06:25Z
[ "python", "lambda", "filter" ]
Simple python iteration exercise..stuck with try and except
39,175,218
<p>Write a program which repeatedly reads numbers until the user enters "done". Once "done" is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.</p> <p>This ...
0
2016-08-26T22:03:01Z
39,175,299
<p>The problem is when you try to use your input:</p> <pre><code>try: total += numbers </code></pre> <p>First, there is no value <strong>numbers</strong>; your variable is singular, not plural. Second, you have to convert the text input to a number. Try this:</p> <pre><code>try: total += int(number) </code...
0
2016-08-26T22:11:46Z
[ "python" ]
Simple python iteration exercise..stuck with try and except
39,175,218
<p>Write a program which repeatedly reads numbers until the user enters "done". Once "done" is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.</p> <p>This ...
0
2016-08-26T22:03:01Z
39,175,303
<p>It's because there is no len(number) when number is an int. len is for finding the length of lists/arrays. you can test this for yourself by commenting out the try/except/continue. I think the code below is more what you are after?</p> <pre><code>total = 0 count = 0 average = 0 while True: number = input("Enter...
0
2016-08-26T22:12:06Z
[ "python" ]
Simple python iteration exercise..stuck with try and except
39,175,218
<p>Write a program which repeatedly reads numbers until the user enters "done". Once "done" is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.</p> <p>This ...
0
2016-08-26T22:03:01Z
39,175,354
<p>A solution...</p> <pre><code>total = 0 count = 0 average = 0 while True: number = input("Enter a number:") if number == "done": break else: try: total += int(number) count += 1 average = total / count except ValueError as ex: print ...
0
2016-08-26T22:17:22Z
[ "python" ]
Change the axis length of a plot to make the diagrams look better in Python
39,175,245
<p>I used the following code in Python to plot four vectors. However, as you can see the plot does not look nice as different curves stick to each other in some points and they are very close to each other. How can I change the plot so that the curves get separated better and the plot look better?</p> <pre><code>plt.g...
1
2016-08-26T22:05:41Z
39,177,407
<p>How about separating them into four subplots?</p> <p><a href="http://i.stack.imgur.com/46bl5.png" rel="nofollow"><img src="http://i.stack.imgur.com/46bl5.png" alt="enter image description here"></a></p> <p>You could mimic a seaborn/ggplot/pandas style just using matplotlib like:</p> <pre><code>import matplotlib a...
0
2016-08-27T04:17:16Z
[ "python", "matplotlib", "plot" ]
How to get the parent xml element after finding a child xml element using lxml and python
39,175,263
<p>I have a bit of a tough nut to crack. It has been so long since I've used LXML that I need some help to get started. I have an XML file that has a list of categories and proxy elements. Please see the snippet below:</p> <pre><code>&lt;categories&gt; &lt;category name="Light"&gt; &lt;proxy&gt;fan&lt;/proxy&...
0
2016-08-26T22:07:36Z
39,175,280
<p>If all you need is the name, might as well do it all in one search:</p> <pre><code>import lxml.etree as ET root = ET.XML(''' &lt;categories&gt; &lt;category name="Light"&gt; &lt;proxy&gt;fan&lt;/proxy&gt; &lt;/category&gt; &lt;category name="UI"&gt; &lt;proxy&gt;doorbell&lt;/proxy&gt; &lt;/category...
2
2016-08-26T22:09:23Z
[ "python", "xml", "lxml" ]
Passing all elements of tuple in function 1 (from *args) into function 2 (as *args) in python
39,175,288
<p>I am writing a function to take *args inputs, assess the data, then pass all inputs to the next appropriate function (align), also taking *args</p> <p>*args seems to be a tuple. I have tried various ways of passing each element of the tuple into the next function, the latest two being:</p> <pre><code> f...
1
2016-08-26T22:10:30Z
39,175,384
<p>You "unpack them" with <code>*args</code>. Then the receiving function can mop them up into a tuple again (or not!). </p> <p>These examples should enlighten things: </p> <pre><code>&gt;&gt;&gt; def foo(*f_args): ... print('foo', type(f_args), len(f_args), f_args) ... bar(*f_args) ... &gt;&gt;&gt; ...
1
2016-08-26T22:21:07Z
[ "python", "function", "tuples", "args" ]
Python script for searching variable strings between two constant strings
39,175,350
<pre><code>import re infile = open('document.txt','r') outfile= open('output.txt','w') copy = False for line in infile: if line.strip() == "--operation():": bucket = [] copy = True elif line.strip() == "StartOperation": for strings in bucket: outfile.write( strings + ',') ...
1
2016-08-26T22:16:56Z
39,175,788
<p>It looks like you are simply trying to find strings within the LOG document and trying to parse the lines of characters using keywords. You can go line by line which is what you are doing currently or you could go through the document once (assuming the LOG document never gets huge) and add each subsequent line to a...
1
2016-08-26T23:11:05Z
[ "python" ]
Python script for searching variable strings between two constant strings
39,175,350
<pre><code>import re infile = open('document.txt','r') outfile= open('output.txt','w') copy = False for line in infile: if line.strip() == "--operation():": bucket = [] copy = True elif line.strip() == "StartOperation": for strings in bucket: outfile.write( strings + ',') ...
1
2016-08-26T22:16:56Z
39,176,691
<p>This looks like a job for Regular Expressions! Several in fact. Thankfully, they are not very complicated to use in this case.</p> <p>There are 2 main observations that would make me choose regexes over something else:</p> <ol> <li>Need to extract one bit of variable text from between two known constant values</...
1
2016-08-27T01:44:20Z
[ "python" ]
Print a list of every combination of dictionary keys with the associated sum of the key values to the right
39,175,538
<p>I have several dictionaries and I want to print a table where each row is a unique combination of the keys in all dictionaries. For each row, I also want to print the sum of the values for the keys in that particular combination.</p> <p>So, if I have these dictionaries:</p> <pre><code>dict1 = {"Main": 8, "Optiona...
1
2016-08-26T22:39:30Z
39,175,662
<p>I think this would be something like:</p> <pre><code>import itertools dict1 = {"Main": 8, "Optional": 6, "Obscure": 4} dict2 = {"Global": 8, "Regional": 4, "Local": 2} merged = {'{}, {}'.format(prod[0], prod[1]): dict1[prod[0]] + dict2[prod[1]] for prod in itertools.product(dict1, dict2)} for k, v in ...
1
2016-08-26T22:53:46Z
[ "python", "dictionary", "product", "itertools", "cartesian-product" ]
Print a list of every combination of dictionary keys with the associated sum of the key values to the right
39,175,538
<p>I have several dictionaries and I want to print a table where each row is a unique combination of the keys in all dictionaries. For each row, I also want to print the sum of the values for the keys in that particular combination.</p> <p>So, if I have these dictionaries:</p> <pre><code>dict1 = {"Main": 8, "Optiona...
1
2016-08-26T22:39:30Z
39,175,677
<p>Use <code>product</code> from <code>itertools</code> on the dictionary items() where you can get the both key and value at the same time, and with the combination of key-value pairs you can construct the final result pretty straightforwardly:</p> <pre><code>from itertools import product sorted([(k1, k2, v1+v2) for ...
1
2016-08-26T22:55:12Z
[ "python", "dictionary", "product", "itertools", "cartesian-product" ]
Print a list of every combination of dictionary keys with the associated sum of the key values to the right
39,175,538
<p>I have several dictionaries and I want to print a table where each row is a unique combination of the keys in all dictionaries. For each row, I also want to print the sum of the values for the keys in that particular combination.</p> <p>So, if I have these dictionaries:</p> <pre><code>dict1 = {"Main": 8, "Optiona...
1
2016-08-26T22:39:30Z
39,175,681
<p>You've read right. Just add <code>sorted()</code>:</p> <pre><code>from itertools import product from operator import itemgetter results = [(k1, k2, dict1[k1] + dict2[k2]) for k1, k2 in product(dict1.keys(), dict2.keys())] for k1, k2, sum_ in sorted(results, key=itemgetter(2), reverse=True): print(...
1
2016-08-26T22:56:01Z
[ "python", "dictionary", "product", "itertools", "cartesian-product" ]
Print a list of every combination of dictionary keys with the associated sum of the key values to the right
39,175,538
<p>I have several dictionaries and I want to print a table where each row is a unique combination of the keys in all dictionaries. For each row, I also want to print the sum of the values for the keys in that particular combination.</p> <p>So, if I have these dictionaries:</p> <pre><code>dict1 = {"Main": 8, "Optiona...
1
2016-08-26T22:39:30Z
39,175,866
<p>This method is built to support a variable amount of dictionaries. You pass your dictionaries to the <code>get_product_sums()</code> method, which then creates a cartesian product from the tuple of dictionaries. </p> <p>We then iterate through our new <code>subitem</code> to calculate sums by doing a look up in our...
2
2016-08-26T23:21:59Z
[ "python", "dictionary", "product", "itertools", "cartesian-product" ]
mongoDB: store audio files (Best way) using python
39,175,540
<p>I've a bunch of audio files (.wav) and I'd like know from you guys, what's the best way to store them in mongoDB? What I'm doing today is, just storing the path of the file.(as you can see below). But I think it's not good because I'm creating a "fake reference" to the file and I wonder If by chance I delete the fi...
0
2016-08-26T22:39:42Z
39,181,683
<p>Take a look at MongoDB <a href="https://docs.mongodb.com/manual/core/gridfs/" rel="nofollow"><code>gridfs</code></a>:</p> <blockquote> <p>GridFS is a specification for storing and retrieving files that exceed the BSON-document size limit of 16 MB</p> </blockquote> <p>Using pymongo you can put files inside like...
0
2016-08-27T13:30:17Z
[ "python", "mongodb", "audio" ]
Why I use list as a parameter of a function and the function can't change the value of the actual parameter but only the formal parameter?
39,175,549
<p>It's the similar question with this one I asked (Visit <a href="http://stackoverflow.com/questions/39160682/how-can-python-function-actually-change-the-parameter-rather-than-the-formal-par?noredirect=1#comment65665408_39160682">How can python function actually change the parameter rather than the formal parameter?</...
0
2016-08-26T22:40:57Z
39,175,590
<p>I think your issue is that you should be adding to the values in the list, but instead you're reassigning. Change <code>=</code> to <code>+=</code>:</p> <pre><code>def twomerger(lx, ly): if lx[0] == ly[0]: lx[0] += ly[0] ly[0] = 0 if lx[1] == ly[1]: lx[1] += ly[1] ly[1] = 0 ...
3
2016-08-26T22:46:44Z
[ "python", "function", "python-3.x" ]
Pig: is it possible to use pytz or dateutils for Python udfs?
39,175,648
<p>I am using <code>datetime</code> in some Python udfs that I use in my <code>pig</code> script. So far so good. I use pig 12.0 on Cloudera 5.5</p> <p>However, I also need to use the <code>pytz</code> or <code>dateutil</code> packages as well and they dont seem to be part of a vanilla python install. </p> <p>Can I u...
6
2016-08-26T22:52:34Z
39,206,029
<p>From the answer to <a href="http://stackoverflow.com/questions/7831649/how-do-i-make-hadoop-find-imported-python-modules-when-using-python-udfs-in-pig">a different but related question</a>, it seems that you should be able to use resources as long as they are available on each of the nodes.</p> <p>I think you can t...
1
2016-08-29T12:11:07Z
[ "python", "apache-pig", "jython", "cloudera", "pytz" ]
Pig: is it possible to use pytz or dateutils for Python udfs?
39,175,648
<p>I am using <code>datetime</code> in some Python udfs that I use in my <code>pig</code> script. So far so good. I use pig 12.0 on Cloudera 5.5</p> <p>However, I also need to use the <code>pytz</code> or <code>dateutil</code> packages as well and they dont seem to be part of a vanilla python install. </p> <p>Can I u...
6
2016-08-26T22:52:34Z
39,259,780
<p>Well, as you probably know all Python UDF functions are not executed by Python interpreter, but Jython that is distributed with Pig. By default in 0.12.0 it should be <a href="http://stackoverflow.com/questions/17711451/python-udf-version-with-jython-pig">Jython 2.5.3</a>. Unfortunately <code>six</code> package supp...
3
2016-08-31T22:10:42Z
[ "python", "apache-pig", "jython", "cloudera", "pytz" ]
ImportError with module in same directory
39,175,653
<p>I am trying to test the mechanism that one python program calling python functions defined in other files. For instance, the main program is <code>run.py</code>, </p> <pre><code>import os import shutil import ae.autoencoder if __name__ == '__main__': main() </code></pre> <p>which calls the <code>autoencoder.p...
0
2016-08-26T22:52:50Z
39,176,000
<p>Probably even if you import the module <code>data</code> from the module <code>autoencoder</code> that is in the same folder, it doesn't work because the path where modules are searched is always the path containing the first file that gets executed, so the path of <code>run.py</code> in your case. Both <code>autoen...
0
2016-08-26T23:40:24Z
[ "python" ]
ImportError with module in same directory
39,175,653
<p>I am trying to test the mechanism that one python program calling python functions defined in other files. For instance, the main program is <code>run.py</code>, </p> <pre><code>import os import shutil import ae.autoencoder if __name__ == '__main__': main() </code></pre> <p>which calls the <code>autoencoder.p...
0
2016-08-26T22:52:50Z
39,176,103
<p>First things first, no need to add the <code>.py</code> extension when importing :) That's implied. </p> <p>The syntax for relative imports (importing modules in the same directory) got a little stricter between Python versions 2 and 3. The way you have it set up will work with Python 2.x, but I'm guessing you're r...
0
2016-08-26T23:51:39Z
[ "python" ]
Frames showing on top of othe frames in tkinter
39,175,675
<p>I'm trying to make a simple GUI with multiple frames in python with tkinter, but what is happening is one frame is showing on top of the other frame. Can anybody help me with why this is and how it can be fixed? Here's my code: ''' SCRATCH GUI By Sigton</p> <pre><code>This is a GUI built on Dylan5797's ...
-2
2016-08-26T22:54:49Z
39,176,068
<p>The frames are appearing exactly how they should.The problem is that you are putting the "hi" label in the root window, which is also where you put the container for the frames. Even though you use the <code>_in</code> parameter, you need to make that label have a parent of <code>self</code> due to the way this spec...
0
2016-08-26T23:47:50Z
[ "python", "tkinter" ]
Python Unit Testing Mock incorrectly
39,175,756
<p>I am new to unit testing in Python. I trying to write unit tests for my class. However I am running into issues:</p> <pre><code>from &lt;path1&gt; import InnerObj from &lt;path2&gt; import new_obj from &lt;path3&gt; import XYZ class ClassToBeTested(object): def __init__(self): obj = new_obj(param1 = "XYZ", ti...
1
2016-08-26T23:06:48Z
39,192,559
<p><code>patch</code> should target the import that is being used and not the path to the import.</p> <p>For example </p> <p><code>@patch('&lt;path1&gt;.InnerObj', new=MagicMock())</code></p> <p><code>&lt;path1&gt;</code> is the location to the definition of <code>InnerObj</code> and not the file using it. To addre...
1
2016-08-28T14:56:59Z
[ "python", "unit-testing", "mocking" ]
Difference between coding of dictionaries in python versions
39,175,767
<p>I have following codestrings:</p> <pre><code>#coding: utf import json import base64 from lxml import html, etree import urllib2 somedictionary={} url1="someurl1" base64string = base64.b64encode('%s:%s' % ('user', 'pass')) xml1request = urllib2.Request(url1) xml1request.add_header("Authorization", "Basic %s" % base...
0
2016-08-26T23:07:55Z
39,175,905
<p>The only way it could work in python3 and not python2 is if <em>somelist</em> is empty in python3 so you never reach the code inside the loop:</p> <pre><code>In [20]: l = [] In [21]: for ele in l: print(not_defined) # never reach here ....: In [22]: l = [1] In [23]: for ele in l: ...
1
2016-08-26T23:26:26Z
[ "python" ]
'datetime.datetime' object is not subscriptable
39,175,822
<p>I've checked every other post about this, but none can fix my issue.</p> <p>I made a list that holds tuples with an id and a datetime object. Everytime I try to clean up the list with: <code>last_encounters = [item for item in last_encounters if item[1] &lt; datetime.utcnow]</code> I get the error that <code>'datet...
0
2016-08-26T23:15:00Z
39,175,890
<p>Try calling <code>utcnow</code> as a method <code>utcnow()</code>:</p> <pre><code>last_encounters = [item for item in last_encounters if item[1] &lt; datetime.utcnow()] </code></pre> <p>I couldn't reproduce your error with a version of your code, but a version with items in the list lead to this fix.</p>
0
2016-08-26T23:25:23Z
[ "python", "python-2.7", "datetime", "tuples" ]
'datetime.datetime' object is not subscriptable
39,175,822
<p>I've checked every other post about this, but none can fix my issue.</p> <p>I made a list that holds tuples with an id and a datetime object. Everytime I try to clean up the list with: <code>last_encounters = [item for item in last_encounters if item[1] &lt; datetime.utcnow]</code> I get the error that <code>'datet...
0
2016-08-26T23:15:00Z
39,175,939
<p>When you do <code>last_encounters += (a, b)</code>, you are adding two sequences together, <code>last_encounters</code> and <code>(a,b)</code>. This means you end up with <code>a</code> and <code>b</code> stuck on the end of the list, rather than just adding the tuple to the list.</p> <p>There are two options to f...
1
2016-08-26T23:31:17Z
[ "python", "python-2.7", "datetime", "tuples" ]
'datetime.datetime' object is not subscriptable
39,175,822
<p>I've checked every other post about this, but none can fix my issue.</p> <p>I made a list that holds tuples with an id and a datetime object. Everytime I try to clean up the list with: <code>last_encounters = [item for item in last_encounters if item[1] &lt; datetime.utcnow]</code> I get the error that <code>'datet...
0
2016-08-26T23:15:00Z
39,175,950
<p>It looks like your problem is the way you add the tuple to the list. Here is an example to show the problem :</p> <pre><code>l = [] l += ("a", "b") print l l = [] l.append( ("a", "b")) print l </code></pre> <p>Which gives :</p> <pre><code>&gt;&gt;&gt; ['a', 'b'] &gt;&gt;&gt; [('a', 'b')] </code></pre> <p>So <...
0
2016-08-26T23:32:06Z
[ "python", "python-2.7", "datetime", "tuples" ]
python3 upload files to ondrive or sharepoint?
39,175,891
<p>Anyone know if this is possible? I just want to automate dropping some documents into my onedrive for business account.</p> <p>I tried </p> <pre><code> import onedrivesdk from onedrivesdk.helpers import GetAuthCodeServer from onedrivesdk.helpers.resource_discovery imp...
0
2016-08-26T23:25:24Z
39,211,002
<p>I wrote this sample code you posted. You replaced the <code>auth_server_URL</code>with the authentication URL for Microsoft Account authentication, which can only be used to access OneDrive (the consumer product). You need to continue using the <code>login.microsoftonline.com</code> URL to log into your OneDrive for...
0
2016-08-29T16:33:41Z
[ "python", "python-3.x", "sharepoint", "upload", "onedrive" ]
python3 upload files to ondrive or sharepoint?
39,175,891
<p>Anyone know if this is possible? I just want to automate dropping some documents into my onedrive for business account.</p> <p>I tried </p> <pre><code> import onedrivesdk from onedrivesdk.helpers import GetAuthCodeServer from onedrivesdk.helpers.resource_discovery imp...
0
2016-08-26T23:25:24Z
39,521,342
<p>Onerive's website shows "Not Yet" on "OneDrive SDK for Python" to "OneDrive for Business" <a href="https://dev.onedrive.com/SDKs.htm" rel="nofollow">https://dev.onedrive.com/SDKs.htm</a></p> <p>The github sample codes did not work for me either, it tried to popup a window of authentication, but IE can not find the ...
0
2016-09-15T22:36:49Z
[ "python", "python-3.x", "sharepoint", "upload", "onedrive" ]
Pythai on Mac OS
39,175,912
<p>Dose anyone have experience installing pythai on mac OS. I get the following error when I try and install it with "pip install pythai"</p> <pre><code>gcc -fno-strict-aliasing -I/Users/roopal/anaconda/include -arch x86_64 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Users/roopal/anaconda/include/python2.7 -c...
-1
2016-08-26T23:27:14Z
39,176,153
<p>If you Google <code>pythai</code>, the first result that comes up is the project's <a href="https://github.com/hermanschaaf/pythai" rel="nofollow">Github page</a>. If you click on it, then scroll down to the readme, it says in the Installation section</p> <blockquote> <p>PyThai requires <code>libthai-dev</code> t...
2
2016-08-26T23:59:09Z
[ "python", "osx", "python-2.7", "pip" ]
Python COM server with VBA late biding + skip win register (no admin rights)
39,175,926
<p>I'm trying to <code>import</code> Python code into in VBA.</p> <p>The code below works but <strong>requires admin rights</strong>. Is there a way to go around the win register need (assume I just don't have admin rights) but keep the 'late biding' behavior (dont want to Tools>>Reference every time I compile somethi...
0
2016-08-26T23:28:55Z
39,176,974
<p>In short, no. The VBA runtime basically uses the <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms684007(v=vs.85).aspx" rel="nofollow">CoGetClassObject</a> COM API under the hood - the <code>CreateObject()</code> function is essentially just a thin wrapper around it (it calls <a href="https://msd...
3
2016-08-27T02:48:23Z
[ "python", "vba", "com", "winreg" ]
Apply rotation matrix to vector + plot it
39,175,928
<p>I have created a vector (v) and would like to perform the rotMatrix function on it. I cannot figure out how to call the function rotMatrix with a degree of 30 on the vector (v). I am also plotting the vectors. </p> <p>Here is my code: </p> <pre><code>import numpy as np import matplotlib.pyplot as plt import seabor...
0
2016-08-26T23:29:15Z
39,176,029
<p>In your rotMatrix function you have used the arcsin() function. You want to use -sin() You should also convert your degrees value to radians</p> <pre><code>return np.array([[np.cos(np.radians(angle)), -np.sin(np.radians(angle))], [np.sin(np.radians(angle)), ...
0
2016-08-26T23:43:35Z
[ "python", "numpy", "matplotlib", "vector", "rotational-matrices" ]
Apply rotation matrix to vector + plot it
39,175,928
<p>I have created a vector (v) and would like to perform the rotMatrix function on it. I cannot figure out how to call the function rotMatrix with a degree of 30 on the vector (v). I am also plotting the vectors. </p> <p>Here is my code: </p> <pre><code>import numpy as np import matplotlib.pyplot as plt import seabor...
0
2016-08-26T23:29:15Z
39,176,073
<p>When in doubt, play around with the calculations in an interactive Python/numpy session.</p> <pre><code>In [23]: 30/180*np.pi # do it yourself convsion - easy Out[23]: 0.5235987755982988 In [24]: np.radians(30) # degrees to radians - samething Out[24]: 0.52359877559829882 In [25]: np.sin(np.radians(30)) ...
0
2016-08-26T23:48:26Z
[ "python", "numpy", "matplotlib", "vector", "rotational-matrices" ]
Scala MurmurHash3 library not matching Python mmh3 library
39,176,052
<p>I have a need to MurmurHash strings in both Python and Scala. However they are giving very different results. Scala's builtin <code>MurmurHash3</code> library does not seem to give the same results as any of the other libraries I have tried including online ones. The odd thing is it seems to match on a single charac...
4
2016-08-26T23:46:37Z
39,177,996
<p>Scala uses Java strings which are encoded as UTF-16. These are packed two at a time into an <code>Int</code>; Python uses a <code>char*</code> (8 bits), so packs in four characters at a time instead of two.</p> <p>Edit: Scala also packs the chars in MSB order, i.e. <code>(s.charAt(i) &lt;&lt; 16) | (s.charAt(i+1))...
3
2016-08-27T05:59:49Z
[ "python", "scala", "encryption", "hash", "murmurhash" ]
How can I run a bash executable from a python script with the same i/o?
39,176,066
<p>So, what I'm trying to do is execute a program from a python script, which I execute in the shell. I've read other questions so I can do it with:</p> <pre><code>def bash(cmd): subprocess.Popen(cmd, shell=True, executable='/bin/bash') bash('./my/file') </code></pre> <p>Now the first problem with this is I often...
0
2016-08-26T23:47:38Z
39,176,766
<p>For you first question, try <code>preexec_fn</code> argument:</p> <pre><code>import signal import ctypes libc = ctypes.CDLL("libc.so.6") def set_pdeathsig(sig = signal.SIGTERM): def callable(): return libc.prctl(1, sig) return callable p = subprocess.Popen(args, preexec_fn = set_pdeathsig(signal.SIG...
0
2016-08-27T02:01:55Z
[ "python", "bash", "shell", "executable" ]
operations on lists while unpacking
39,176,128
<p>I have a list of strings:</p> <pre><code>my_list = ['text_1','ibno0d',' text_2 ' ] </code></pre> <p>And I want to save the first and third value in new variables:</p> <p>a,_,b = my_list</p> <p>Since text_1 and text_2 have some spaces I use strip method to clean those values.</p> <pre><code>a = a.strip() b = b.s...
-1
2016-08-26T23:55:19Z
39,176,250
<pre><code>a = my_list[0].strip() b = my_list[2].strip() </code></pre>
-1
2016-08-27T00:14:26Z
[ "python", "list" ]
operations on lists while unpacking
39,176,128
<p>I have a list of strings:</p> <pre><code>my_list = ['text_1','ibno0d',' text_2 ' ] </code></pre> <p>And I want to save the first and third value in new variables:</p> <p>a,_,b = my_list</p> <p>Since text_1 and text_2 have some spaces I use strip method to clean those values.</p> <pre><code>a = a.strip() b = b.s...
-1
2016-08-26T23:55:19Z
39,176,264
<p>I prefer using <code>map</code> for this..</p> <pre><code>a, _, b = map(str.strip, my_list) </code></pre>
1
2016-08-27T00:18:21Z
[ "python", "list" ]
operations on lists while unpacking
39,176,128
<p>I have a list of strings:</p> <pre><code>my_list = ['text_1','ibno0d',' text_2 ' ] </code></pre> <p>And I want to save the first and third value in new variables:</p> <p>a,_,b = my_list</p> <p>Since text_1 and text_2 have some spaces I use strip method to clean those values.</p> <pre><code>a = a.strip() b = b.s...
-1
2016-08-26T23:55:19Z
39,176,312
<p>You could iterate only over the indexes you are interested about. Doesn't matter too much here but in case list is longer it makes a difference:</p> <pre><code>a, b = (my_list[i].strip() for i in [0, 2]) </code></pre>
1
2016-08-27T00:27:03Z
[ "python", "list" ]
pandas load data with data type issues
39,176,131
<p>Here is the code, output and raw csv file data, the dtypes are all object type from output, is there a way to recognize each column as string (and last column as float type)? Using Python 2.7 with miniconda.</p> <p>Code,</p> <pre><code>import pandas as pd sample=pd.read_csv('123.csv', sep=',',header=None) print sa...
0
2016-08-26T23:55:44Z
39,176,699
<p>You have to use the argument <code>dtype</code>. And since you do not want the header, you must skip it with <code>skiprows</code> because the third element is not a float.</p> <pre><code>df = pd.read_csv('123.csv', header=None, skiprows=1, dtype={0:str, 1:str, 2:str, 3:float}) </code></pre> <p>The out...
1
2016-08-27T01:46:04Z
[ "python", "python-2.7", "pandas" ]
transform string column of a pandas data frame into 0 1 vectors
39,176,190
<p><code>LabelEncoder</code> and <code>OneHotEncoder</code> works pretty good for numpy array, which transform string into <code>0,1</code> based vectors.</p> <p>My question is, is there a neat API to convert a column of a pandas data frame into <code>0, 1</code> vectors? I showed my code and raw content of the pandas...
1
2016-08-27T00:05:21Z
39,176,249
<p>Are you looking for <code>get_dummies</code>?</p> <pre><code>s = pd.Series(["a", "b", "a", "c"]) pd.get_dummies(s) </code></pre> <p>If you want <code>ints</code>:</p> <pre><code>pd.get_dummies(s).astype(np.uint8) </code></pre> <p>reference:</p> <p><a href="http://stackoverflow.com/questions/27468892/pandas-get-...
2
2016-08-27T00:14:05Z
[ "python", "python-2.7", "pandas", "numpy", "one-hot-encoding" ]
Get distribution name from scipy.stats.distribution object? (SciPy | Python 3)
39,176,236
<p>I'm trying out a bunch of different fits for distributions. </p> <p><strong>Is there any way to get the name of the distribution back from the distribution object?</strong> </p> <p>I found a way but it doesn't seem very efficient. </p> <pre><code>distribution = "gamma" distr = getattr(stats, distribution) print...
1
2016-08-27T00:12:14Z
39,176,310
<p>You can use the <code>name</code> attribute:</p> <pre><code>from scipy import stats print(stats.gamma.name) </code></pre>
4
2016-08-27T00:26:52Z
[ "python", "numpy", "scipy", "statistics", "distribution" ]
Get distribution name from scipy.stats.distribution object? (SciPy | Python 3)
39,176,236
<p>I'm trying out a bunch of different fits for distributions. </p> <p><strong>Is there any way to get the name of the distribution back from the distribution object?</strong> </p> <p>I found a way but it doesn't seem very efficient. </p> <pre><code>distribution = "gamma" distr = getattr(stats, distribution) print...
1
2016-08-27T00:12:14Z
39,176,311
<p>Use the <code>name</code> attribute:</p> <pre><code>&gt;&gt;&gt; from scipy import stats &gt;&gt;&gt; distribution = "gamma" &gt;&gt;&gt; distr = getattr(stats, distribution) &gt;&gt;&gt; distr.name 'gamma' </code></pre>
2
2016-08-27T00:27:01Z
[ "python", "numpy", "scipy", "statistics", "distribution" ]
Python: convert numpy array of signs to int and back
39,176,308
<p>I'm trying to convert from a numpy array of signs (i.e., a numpy array whose entries are either <code>1.</code> or <code>-1.</code>) to an integer and back through a binary representation. I have something that works, but it's not Pythonic, and I expect it'll be slow.</p> <pre><code>def sign2int(s): s[s==-1.] =...
2
2016-08-27T00:26:41Z
39,176,491
<p>Here are some vectorized versions of your functions: </p> <pre><code>def sign2int(s): return int(''.join(np.where(s == -1., 0, s).astype(int).astype(str)), 2) def int2sign(i, m): tmp = np.array(list(bin(i)[2:].zfill(m))) return np.where(tmp == "0", "-1", tmp).astype(int) s0 = np.array([1., -1., 1., 1....
0
2016-08-27T00:58:04Z
[ "python", "arrays", "numpy", "binary" ]
Python: convert numpy array of signs to int and back
39,176,308
<p>I'm trying to convert from a numpy array of signs (i.e., a numpy array whose entries are either <code>1.</code> or <code>-1.</code>) to an integer and back through a binary representation. I have something that works, but it's not Pythonic, and I expect it'll be slow.</p> <pre><code>def sign2int(s): s[s==-1.] =...
2
2016-08-27T00:26:41Z
39,176,524
<p>For 1d arrays you can use this one linear Numpythonic approach, using <code>np.packbits</code>:</p> <pre><code>&gt;&gt;&gt; np.packbits(np.pad((s0+1).astype(bool).astype(int), (8-s0.size, 0), 'constant')) array([11], dtype=uint8) </code></pre> <p>And for reversing:</p> <pre><code>&gt;&gt;&gt; unpack = (np.unpackb...
1
2016-08-27T01:05:00Z
[ "python", "arrays", "numpy", "binary" ]
Python: convert numpy array of signs to int and back
39,176,308
<p>I'm trying to convert from a numpy array of signs (i.e., a numpy array whose entries are either <code>1.</code> or <code>-1.</code>) to an integer and back through a binary representation. I have something that works, but it's not Pythonic, and I expect it'll be slow.</p> <pre><code>def sign2int(s): s[s==-1.] =...
2
2016-08-27T00:26:41Z
39,176,895
<p>I'll start with <code>sig2int</code>.. Convert from a sign representation to <em>binary</em></p> <pre><code>&gt;&gt;&gt; a array([ 1., -1., 1., -1.]) &gt;&gt;&gt; (a + 1) / 2 array([ 1., 0., 1., 0.]) &gt;&gt;&gt; </code></pre> <p>Then you can simply create an array of powers of two, multiply it by the <em>bi...
1
2016-08-27T02:32:19Z
[ "python", "arrays", "numpy", "binary" ]
Python: convert numpy array of signs to int and back
39,176,308
<p>I'm trying to convert from a numpy array of signs (i.e., a numpy array whose entries are either <code>1.</code> or <code>-1.</code>) to an integer and back through a binary representation. I have something that works, but it's not Pythonic, and I expect it'll be slow.</p> <pre><code>def sign2int(s): s[s==-1.] =...
2
2016-08-27T00:26:41Z
39,178,113
<p>After a bit of testing, the Numpythonic approach of @wwii that doesn't use strings seems to fit what I need best. For the <code>int2sign</code>, I used a for-loop over the exponents with a standard algorithm for the conversion---which will have at most 64 iterations for 64-bit integers. Numpy's broadcasting happens ...
0
2016-08-27T06:19:06Z
[ "python", "arrays", "numpy", "binary" ]
Python: convert numpy array of signs to int and back
39,176,308
<p>I'm trying to convert from a numpy array of signs (i.e., a numpy array whose entries are either <code>1.</code> or <code>-1.</code>) to an integer and back through a binary representation. I have something that works, but it's not Pythonic, and I expect it'll be slow.</p> <pre><code>def sign2int(s): s[s==-1.] =...
2
2016-08-27T00:26:41Z
39,185,245
<p>I think <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.packbits.html" rel="nofollow"><code>numpy.packbits</code></a> is worth another look. Given a real-valued sign array <code>a</code>, you can use <code>numpy.packbits(a &gt; 0)</code>. Decompression is done by <a href="http://docs.scipy.org/...
0
2016-08-27T20:02:12Z
[ "python", "arrays", "numpy", "binary" ]
difference between multithreading and multiprocessing threadpool?
39,176,517
<p>I have list of 20 items in file A and these are passed to file B for processing and the result to be returned.</p> <p>Currently I am doing with multithreading. And came accross concept of threadpool and multiprocessing and was wondering whats the difference between multithreading and threadpool and will my program...
-1
2016-08-27T01:03:35Z
39,176,578
<blockquote> <p>whats the difference between multithreading and threadpool</p> </blockquote> <p>Multithreading is the ability of a CPU to execute multiple processes/threads concurrently. See <a href="https://en.wikipedia.org/wiki/Multithreading_(computer_architecture)" rel="nofollow">multithreading</a> for details. ...
1
2016-08-27T01:17:11Z
[ "python", "multithreading", "python-2.7", "python-3.x", "python-multithreading" ]
Django Charfield null=False Inegrity Error not raised
39,176,618
<p>I have a model:</p> <pre><code>class Discount(models.Model): code = models.CharField(max_length=14, unique=True, null=False, blank=False) email = models.EmailField(unique=True) discount = models.IntegerField(default=10) </code></pre> <p>In my shell when I try and save a Discount object with no input, i...
1
2016-08-27T01:26:48Z
39,176,848
<p>No default Django behavior will save <code>CHAR</code> or <code>TEXT</code> types as <code>Null</code> - it will always use an empty string (<code>''</code>). <code>null=False</code> has no effect on these types of fields. </p> <p><code>blank=False</code> means that the field will be required by default when the mo...
1
2016-08-27T02:19:55Z
[ "python", "django", "django-models" ]
Python raw_input issue
39,176,638
<p>Here's my code</p> <pre><code>def player_input(): input = raw_input('Choose X or O') if input == "X": print input else: print 'Please choose an X or an O' player_input() player_input() </code></pre> <p>Not sure why I'm getting this. No matter what I type, it seems to jump to th...
0
2016-08-27T01:31:18Z
39,176,971
<p>To your second question answered in the comments</p> <blockquote> <p>Thanks all! Turns out it was an issue with PyCharms interpreter :( As soon as I used the python interpreter on my OS it came out fine. My next issue is using the 'or' comparison. This -> if input == "x" or "X" or "o" or "O": yields the result of...
-1
2016-08-27T02:48:17Z
[ "python" ]
ModelForm displays ForeignKey table values, not choices
39,176,735
<p>I'm creating a Django app where each site has a single category, selected from a range of possible categories. So I have two models: <code>Site</code>, and <code>Category</code>. </p> <p>I want a many-to-one relationship between the <code>Site</code> and <code>Category</code> models. The <code>Category</code> table...
1
2016-08-27T01:54:18Z
39,176,771
<p>You need to specify <code>Category</code> model:</p> <pre><code>class NewSiteForm(ModelForm): class Meta: model = Category # &lt;-- fields = ['Category'] </code></pre>
1
2016-08-27T02:03:19Z
[ "python", "django", "django-models", "django-forms", "modelform" ]
ModelForm displays ForeignKey table values, not choices
39,176,735
<p>I'm creating a Django app where each site has a single category, selected from a range of possible categories. So I have two models: <code>Site</code>, and <code>Category</code>. </p> <p>I want a many-to-one relationship between the <code>Site</code> and <code>Category</code> models. The <code>Category</code> table...
1
2016-08-27T01:54:18Z
39,194,270
<p>My model structure was bad. It didn't make sense to have separate choices for the <code>Category</code> model. What I should have done was:</p> <p>1) Either just deleted the <code>Category</code> model altogether and used the <code>CATEGORY_CHOICES</code> directly for the <code>Category</code> field in the <code>Si...
0
2016-08-28T18:03:05Z
[ "python", "django", "django-models", "django-forms", "modelform" ]
Get average grade for 10 students - python
39,176,762
<p>I have a program that asks a user to enter a Student NETID and then what grades they got on 5 assignments plus the grade they got on the mid-term and final. It then adds them and divides to get that students average grade which displays in table format.</p> <p>What I need to do, is loop through that whole process 9...
0
2016-08-27T02:01:31Z
39,176,845
<p>You really did the hardest part. I don't see why you couldn't so the loop of the average. Anyway:</p> <pre><code>student_count = 5; A = [student_count] for id_student in range(student_count): print("STUDENT #", id_student+1) # x holds the list of grades x = [] # count of assignments assi...
2
2016-08-27T02:19:46Z
[ "python", "loops" ]
Am i overenginering it with websocket for IOT device Pushing data to endpoint
39,176,800
<p>I have a raspberry pi running unix and it has a gps chip that sends text over its serial com pots.</p> <p>I want to forward this data without doing any kind of parsing, just forward the data stream directly to a endpoint (running aspnet core, webapi and signalr).</p> <p>Just like if i was doing <code>sudo cat &lt;...
1
2016-08-27T02:10:08Z
39,177,450
<p>as compared to http websocket is always a good choice for such cases.</p> <p><a href="https://www.engineyard.com/articles/websocket" rel="nofollow">benefits of websockets</a></p> <p>but for iot related stuff MQTT is preferred.</p> <p>here it is articulated really well <a href="https://systembash.com/mqtt-vs-webso...
1
2016-08-27T04:25:38Z
[ "python", "websocket", "signalr", "asp.net-web-api2" ]