Unnamed: 0 int64 0 1.91M | id int64 337 73.8M | title stringlengths 10 150 | question stringlengths 21 64.2k | answer stringlengths 19 59.4k | tags stringlengths 5 112 | score int64 -10 17.3k |
|---|---|---|---|---|---|---|
2,700 | 52,867,693 | Converting IntVar() value to Int | <p>Iam trying to convert <code>Intvar()</code> value to <code>Int</code> by </p>
<pre><code>self.var1 = IntVar()
self.scale = ttk.LabeledScale(self.frame1, from_ = 3, to = 7, variable = self.var1).grid(row = 2, sticky = 'w')
value = int(self.var1)
</code></pre>
<p>but got an error saying </p>
<p><strong>TypeError: i... | <p>You need to invoke the .get method of IntVar which returns the object's value as an integer.</p> | python-3.x | 7 |
2,701 | 47,965,004 | Get the last coordinates list from a text file | <p>I am reading coordinates of nodes (76 nodes). Basically I split the string of all coordinates. After splitting I have a result for coordinates of node, first number is the number of node, accordingly coordinates (x,y). Example:</p>
<p>['1', '3600', '2300']</p>
<p>I only want to get coordinates of node from 61 to t... | <p>You should use an if statement inside <code>while line != "EOF":</code> like so:</p>
<pre><code>while line != "EOF":
values = line.split()
if int(values[0]) > 61:
coord.append([float(values[1]), float(values[2])])
line = iFile.readline().strip()
</code></pre>
<p>An alternate solution would b... | python|coordinate | 0 |
2,702 | 7,456,638 | True privateness in Python | <p>PEP 8 states that (emphasis mine):</p>
<blockquote>
<p>We don't use the term "private" here, since no attribute is really private in Python (<strong>without a generally unnecessary amount of work</strong>).</p>
</blockquote>
<p>I guess it refers to defining the actual class in some other language and then exposi... | <p>No, nothing is truly private in Python.</p>
<p>If you know the method name, you can get it.</p>
<p>I think you might come up with a clever hack, but it would be just that - a hack. No such functionality exists in the language.</p> | python|private | 4 |
2,703 | 7,017,408 | how to write in next row using python? | <p>1234 5678 9876 542 1231; 2333 1234 5678 579</p>
<p>i want to write this data in a csv (myfile.csv) file from a .txt (murtuz.txt) file such that after semi colon it starts from the next row.</p>
<p>I have tried the code mentioned below, it helps me to write data in csv file but i am failed to change the line after ... | <p><code>csv.reader</code> can accept any iterable as input. In particular, you can feed it lines yielded from a generator. You can use that generator to massage your input data -- for example, to split on semicolons:</p>
<pre><code>input csv
input textwrap
input io
def splitter(iterable):
for line in iterable:
... | python|file-io|csv | 3 |
2,704 | 39,851,416 | Extract rows as column from pandas data frame after melt | <p>I'm working with pandas and I have this table:</p>
<pre><code>ID 1-May-2016 1-Jun-2016 20-Jul-2016 Class
1 0.2 0.52 0.1 H
2 0.525 0.20 0.01 L
...
</code></pre>
<p>and I'd like to obtain this table:</p>
<pre><code>ID Date Value Class
1 1-May-2016 0.2 H
... | <p>You need add <code>Class</code> to <code>id_vars</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>melt</code></a>:</p>
<pre><code>print (pd.melt(df,id_vars=["ID", 'Class'], var_name = "Date", value_name='Vals'))
ID Class Date Vals
0 1 ... | python|pandas|pivot-table|melt | 2 |
2,705 | 16,384,948 | Loop that will create new Pandas.DataFrame column | <p>Following the <a href="http://scikit-learn.github.io/scikit-learn-tutorial/general_concepts.html#handling-categorical-features" rel="nofollow">scikit-learn tutorial here</a>, if we have a <code>Pandas.DataFrame</code> that has a column named <code>colors</code>, how can we create a loop to loop through all of the Da... | <p>You can use the <code>pandas.get_dummies</code> function to do that:</p>
<pre><code>>>> import pandas as pd
>>> pd.get_dummies(listings['color'], 'color')
</code></pre> | python|python-2.7|numpy|pandas|scikit-learn | 3 |
2,706 | 16,570,955 | How to "listen" to a multiprocessing queue in Python | <p>I will start with the code, I hope it is simple enough:</p>
<pre><code>import Queue
import multiprocessing
class RobotProxy(multiprocessing.Process):
def __init__(self, commands_q):
multiprocessing.Process.__init__(self)
self.commands_q = commands_q
def run(self):
self.listen()... | <p>You need to use multiprocessing.Queue instead of Queue.Queue in order to have the Queue object be shared across processes.</p>
<p>See here: <a href="http://docs.python.org/2/library/multiprocessing.html#pipes-and-queues" rel="noreferrer">Multiprocessing Queues</a></p> | python|python-2.7|queue|multiprocessing | 5 |
2,707 | 32,035,731 | Python ValueError: Substring not found | <p>I have been working on this code and I have tried to debug it for almost a day by now, but I can't seen to find where the problem lies. </p>
<p>I stop the debugger at line 66.
When I step into or over the code I get an error message. </p>
<pre><code>Traceback (most recent call last):
File "/home/johan/pycharm-c... | <p>You should process the case when <code>letter</code> doesn't exist in <code>self.value</code> (line 41):</p>
<pre><code>dist += abs(i - self.value.index(letter))
</code></pre>
<p><code>string.index</code> raise an exception when the letter doesnt exist. Better use <code>string.find</code> instead, it gives <code>-... | python|a-star | 1 |
2,708 | 31,990,150 | Python Socket Timing out | <p>I am attempting to open a socket to google on port 80 but for the life of me I can't figure out why this is timing out. If I don't set a timeout it just hangs indefinitely. </p>
<p>I don't think my companies firewall is blocking this request. I can navigate to google.com in the browser so there shouldn't be any han... | <p>This will work:</p>
<pre><code>import socket
HOST = 'www.google.com'
PORT = 80
IP = socket.gethostbyname(HOST)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, PORT))
message = b"GET / HTTP/1.1\r\n\r\n"
s.sendall(message)
data = s.recv(1024)
print(data.decode('utf-8'))
s.close()
</code></p... | python|sockets | 3 |
2,709 | 38,669,242 | Why Do I need Range(Len)) for a nested if? | <p>This works as is but when I didn't have range(len..)) in and do <code>for i in arr</code> and <code>for j in arr</code>, I get <code>IndexError: list index out of range</code> on the if statement. Why is this?</p>
<pre><code>arr = [2,2,2,2,4,5,2,45,3,4,4]
mostFrq = 0
mostFrqAmount = 0
for i in range(len(arr)):
... | <p>When you're iterating over a list, you get its elements. Since you're then accessing list elements at the index of that element, it won't work when it's out of bounds (and wouldn't do what you expected anyways).</p>
<p>Instead, just use the items you're provided by the loop:</p>
<pre><code>mostFrq = 0
mostFrqAmoun... | python | 0 |
2,710 | 40,636,572 | trying to fill a new column in a dataframe with a for loop | <p>Based on a value of another column I'd like to fill out a new column with a for loop. Regrettably not getting the results I need;</p>
<pre><code>profit = []
# For each row in the column,
for row in df3['Result']:
# if value is;
if row == 'H':
# Append a Profit/Loss
profit.append(df3['column... | <p>I think you need double <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a>:</p>
<pre><code>df3['profit'] = np.where(df3['Result'] == 'H', df3['column value H'],
np.where(df3['Result'] == 'D', df3['column value... | python|pandas | 2 |
2,711 | 9,705,416 | Detection of available non-standard hash algorithms using hashlib in Python | <p>According to the Python documentation, only a few hash algorithms are guaranteed to be supported by the hashlib module (MD5 and SHA***). How would I go about detecting if other algorithms are available? (like RIPEMD-160) Of course, I could try to use it using the RIPEMD-160 example from the documentation, but I'm no... | <p>Just try it in a shell:</p>
<pre><code>>>> h = hashlib.new('ripemd161')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/hashli... | python|hash|python-2.7|checksum|ripemd | 4 |
2,712 | 68,283,862 | Parsing a json gives JSONDecodeError: Unterminated string | <p>I have a document with new-line-delimited json's, to which I apply some functions. Everything works up until this line, which looks exactly like this:</p>
<pre><code>{"_id": "5f114", "type": ["Type1", "Type2"], "company": ["5e84734"], "answer... | <p>The unprintable character embedded in the <code>"answer 2"</code> string is a <a href="https://www.fileformat.info/info/unicode/char/2029/index.htm" rel="nofollow noreferrer">paragraph separator</a>, which is treated as whitespace by <code>.splitlines()</code>:</p>
<pre><code>>>> 'foo\u2029bar'.sp... | python|json|dictionary|parsing | 3 |
2,713 | 68,147,311 | Is it possible to get the source code of a (possibly decorated) Python function body, including inline comments? | <p>I am trying to figure out how to only get the source code of the body of the function.</p>
<p>Let's say I have:</p>
<pre class="lang-py prettyprint-override"><code>def simple_function(b = 5):
a = 5
print("here")
return a + b
</code></pre>
<p>I would want to get (up to indentation):</p>
<pre><co... | <p>I wrote a simple regex that does the trick. I tried this script with classes and without. It seemed to work fine either way. It just opens whatever file you designate in the <code>Main</code> call, at the bottom, rewrites the entire document with all function/method bodies doc-stringed and then save it as whatever y... | python | 1 |
2,714 | 68,283,157 | Fast Fourier Transforms on existing dataframe is showing unexpexted results | <p>I have a <code>.csv</code> file with voltage data, when I plot the data with time I can see that it is a sinusoidal wave with <code>60hz</code> frequency.</p>
<p><img src="https://i.stack.imgur.com/fssJM.png" alt="Voltage data plot wrt time" /></p>
<p>Now when I try to perform <code>fft</code> using the <code>scipy/... | <p>Data should be fine and FFT calculation (upto a constant) is fine too. It is about how the the results are plotted. To make the x-axis values represent the frequency information in terms of Hertz, you need</p>
<pre><code>frequency = np.arange(N) / N * sampling_rate
</code></pre>
<p>and then you can crop the half of ... | python|pandas|numpy|fft | 2 |
2,715 | 32,534,687 | Django Query Performance | <p>I have a rather performance related question about django queries. </p>
<p>Say I have a table of employees with 10,000 records. Now If I'm looking to select 5 random employees that are of age greater than or equal to 20, let's say some 5,500 employees are 20 or older. The django query would be:</p>
<pre><code>Empl... | <p>I did a quick check on my existing project:</p>
<pre><code>queryset = BlahModel.objects.order_by('?')[:5]
print queryset.query
</code></pre>
<p>The result is:</p>
<pre><code>SELECT `blah_model`.`id`, `blah_model`.`date` FROM `blah_model` ORDER BY RAND() LIMIT 5;
</code></pre>
<p>So, they are the same.</p>
<p>I ... | python|mysql|sql-server|django|performance | 1 |
2,716 | 44,196,979 | Hashing Pandas dataframe breaks | <p>First import:</p>
<pre><code>import pandas as pd
import numpy as np
import hashlib
</code></pre>
<p>Next, consider the following:</p>
<pre><code>np.random.seed(42)
arr = np.random.choice([41, 43, 42], size=(3,3))
df = pd.DataFrame(arr)
print(arr)
print(df)
print(hashlib.sha256(arr.tobytes()).hexdigest())
print(ha... | <p>A pandas <code>DataFrame</code> or <code>Series</code> can be hashed using the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.util.hash_pandas_object.html" rel="nofollow noreferrer"><code>pandas.util.hash_pandas_object</code></a> function, starting in version 0.20.1.</p> | python|pandas|numpy|hash | 1 |
2,717 | 43,989,153 | How to wait for RxPy parallel threads to complete | <p>Based on this <a href="https://stackoverflow.com/questions/32450932/subscribe-on-with-from-iterable-range-in-rxpy/33847875#33847875">excellent SO answer</a> I can get multiple tasks working in parallel in RxPy, my problem is how do you wait for them to all complete? I know using threading I can do <code>.join()</cod... | <p>Posting complete solution here:</p>
<pre><code>from __future__ import print_function
import os, sys
import time
import random
from rx import Observable
from rx.core import Scheduler
from threading import current_thread
from rx.concurrency import ThreadPoolScheduler
def printthread(val):
print("{}, thread: {}".... | python|multithreading|python-multithreading|reactivex|rx-py | 7 |
2,718 | 34,633,672 | Omit one column in Google Chart | <p>As the title says, I want to display a Google Chart omitting one column of my data table. My table has the following structure:</p>
<pre><code>['2016-01-05 12:45:05', 1.187, 20.375, 45.375],
['2016-01-05 13:00:04', 1.687, 21.437, 43.937],
['2016-01-05 13:15:04', 2.062, 22.062, 43.25],
</code></pre>
<p>There are fo... | <p>Why not just filter the table like </p>
<pre><code>table_filtered = [ [row[0], row[2], row[3]] for row in table]
</code></pre>
<p>and pass <code>table_filtered</code> to the print </p> | python|google-visualization | 0 |
2,719 | 34,843,852 | Python script won't let me exit after executing a exe in os.system | <pre><code>def x():
os.system('x.exe')
sys.exit()
</code></pre>
<p>This is what i used in my script but when i run the program it never gets up to sys.exit.</p> | <p>I think os.system function will execute shell command. and sys.exit() command is no problem . I suggest you to make a test ,like the following script:</p>
<p>import sys</p>
<p>sys.exit()</p>
<p>print "sys.exit is not Ok!"</p> | python-2.7|os.system | 0 |
2,720 | 27,358,208 | Python Django POST issues | <p>I am facing a problem with posting data in Django.</p>
<p>I have defined one URL in urls.py:</p>
<pre><code> url(r'^lares_conf_123kmk_$', 'lares.call_sta.my_func', name='home'),
</code></pre>
<p>My function is my_func is defined as:</p>
<pre><code>def my_func(request):
u = request.POST.get("parsed_news", "")... | <p>That looks to me like you're falling foul of Django's <a href="https://docs.djangoproject.com/en/dev/ref/csrf/" rel="nofollow">Cross Site Request Forgery protection</a>.</p>
<p>You can test that theory by marking the view as exempt, using <a href="https://docs.djangoproject.com/en/dev/ref/csrf/#django.views.decorat... | python|django | 2 |
2,721 | 8,129,826 | Change the font style of one item in a wx python ListCtrl | <p>I am having issues changing the font of a single item in an wx list ctrl. I have 1 row and 3 columns in my ListCtrl. The code below should change the font of the item located at row = 0 col = 0 to bold. But instead it changes the font style of ALL the items in row 0 to bold. In summary, I only want the first item i... | <p>with wx.ListCtrl, you can't have control at the sub item level.
If you change font, it will change for entire row.</p>
<p>Therefore this is not possible.</p>
<p>Heres the ticket number:
<a href="http://trac.wxwidgets.org/ticket/3030" rel="nofollow">http://trac.wxwidgets.org/ticket/3030</a></p> | python|fonts|wxwidgets|listctrl | 1 |
2,722 | 42,033,213 | Convert google directions into a shapefile line | <p>Is it possible to take the json returned from the Google directions API and convert that information into a shapefile line that is the same as the polyline for the route?</p>
<p>I would like to plot a trip I took on a map I am making in QGIS.</p> | <p>I finally figured out how to do this using <a href="http://toblerity.org/fiona/manual.html" rel="nofollow noreferrer">Fiona</a> and <a href="http://toblerity.org/shapely/manual.html" rel="nofollow noreferrer">Shapely</a> and a <a href="https://github.com/mgd722/decode-google-maps-polyline/blob/master/polyline_decode... | python|json|python-2.7|google-maps|gis | 1 |
2,723 | 41,778,355 | pandas: grouping by key to cluster messy strings | <p>I have a table that looks like this:</p>
<pre><code>company_id,company_name
1,Amazon
1,Amazon Ltd
2,Google
1,Amazon
2,Gogle
3,Facebook Ltd
3,Facebook LTD
1,AMAZON
1,AMAZON LTD
2,GOOGLE
3,Facebook
3,Face book
</code></pre>
<p>So I have a unique identifier for each company, but their textual representation differs. ... | <p>I've tested your solution on a fairly large DataFrame using <code>map</code> and it looks pretty efficient:</p>
<pre><code>prng = np.random.RandomState(0)
df = pd.DataFrame({'company_id': prng.randint(10**6, size=10**7),
'company_name': prng.rand(10**7).astype('str')})
# It has 10m unique identi... | python|pandas|data-cleaning | 3 |
2,724 | 70,833,417 | How to not match substrings with regex | <p>String to match:</p>
<pre><code>{abc}
</code></pre>
<p>Strings to not match:</p>
<pre><code>$${abc{abc}{abc}}$$
</code></pre>
<hr />
<p>How do I satisfy this requirement with regex?<br />
The context is trying to match <code>{abc}</code> elements for replacement with Python, but I don't want them mixed up with <a hr... | <p>If you simply need to match the expressions on individual lines, all you need is to add line anchors.</p>
<pre><code>^\{[^{}]+\}$
</code></pre>
<p>If your input is a single string with multiple lines in it, you'll need to add the <code>re.MULTILINE</code> flag to say that <code>^</code> and <code>$</code> should mat... | python|regex | 1 |
2,725 | 11,603,736 | running python web application on aws | <p>I'm to use amazon web services with some python scripts I have created.
I have used PHP in the past and now I want to write a web application using python but without a web frame work such as Django (I found many tutorials for that). </p>
<p>While using PHP, it was enought to place my files in a dedicated directory... | <p>It varies slightly based on the framework that you're using, but in general you need to point your web server at a <code>wsgi</code> file. For doing this with Django, see: <a href="https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/" rel="nofollow">https://docs.djangoproject.com/en/dev/howto/deployment/wsgi... | python|apache | 0 |
2,726 | 33,638,530 | Implementing Logistic Regression with Scipy: Why does this Scipy optimization return all zeros? | <p>I am trying to implement a one versus many logistic regression as in Andrew Ng's <a href="https://www.coursera.org/learn/machine-learning/home/week/5" rel="nofollow noreferrer">machine learning class</a>, He uses an octave function called <code>fmincg</code> in his implementation. I have tried to use several functi... | <p>The problem lies in your <code>Gradient</code> function. In <code>numpy</code> assignment is <strong>not copying objects</strong>, so your line</p>
<pre><code>reg = theta
</code></pre>
<p>makes <code>reg</code> a reference to <code>theta</code>, so each time you compute gradient you actually modify your current so... | python|optimization|machine-learning|scipy|numerical-methods | 2 |
2,727 | 37,832,460 | How to create masked array with a vector that separates sections of a 2d array? | <p>Let's say I have a standard 2d numpy array, let's call it my2darray with values. In this array there are two major sections. Let's say for each column, there is a specific row which separates "scenario1" and "scenario2". How can i create 2 masked arrays that represent the top section of my2darray and the bottom of m... | <p>Using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy's broadcasted comparison</code></a>, we can create such a <code>2D</code> mask in a vectorized manner. Rest of the work is all about <code>sum-reduction</code> along the first axis for which we can take help from... | python|numpy|masked-array | 0 |
2,728 | 37,822,586 | Sending email with optional attachment in django | <p>I am working on a form to send email where have optional attachment.</p>
<p>When I try to send the email without attach a file.
I got this error</p>
<p><strong>Key 'file' not found in MultiValueDict: {}</strong></p>
<p>Any idea what I am doing wrong? I would like to send it directly to the email address without u... | <p>If you don't send a file, request.FILE will be a blank dictionary-like object. <a href="https://docs.djangoproject.com/ja/1.9/ref/request-response/#django.http.HttpRequest.FILES" rel="nofollow">Documentation</a></p>
<p>Based on this, you need to check if key is present at this dict. examples:</p>
<pre><code> if 'f... | python|django|django-forms | 0 |
2,729 | 29,890,647 | Using Elixir, erlport with Python 2.7.9, receiving an arity error | <p>I am trying to use Python with Elixir and I wrote the following functional code (you can find the repo I'm building here: <a href="https://github.com/arthurcolle/elixir_with_erlport" rel="nofollow">https://github.com/arthurcolle/elixir_with_erlport</a>) </p>
<pre><code>defmodule Snake do
use Application
def st... | <pre><code>{:ok, pp} = :python.start_link()
:python.call(pp, :sys, String.to_atom("version.__str__"), [])
</code></pre> | python|elixir|arity|beam | 2 |
2,730 | 57,001,771 | How to use list comprehensions for for-loop with additional operations | <p>I want to simplify this construction with list comprehensions:</p>
<pre><code>words = {}
counter = 0
for sentence in text:
for word in sentence:
if word not in words:
words[word] = counter
counter += 1
</code></pre>
<p>If there was something like post-increment, it could be wri... | <p>There are many ways to do this. This one is without using any external modules, one liner:</p>
<pre><code>s = "a a a b b a a b a b a b"
d = [[(out, out.update([(v, out.get(v, 0) + 1)])) for v in s.split()] for out in [{}]][0][0][0]
print(d)
</code></pre>
<p>Prints:</p>
<pre><code>{'a': 7, 'b': 5}
</code></pre> | python|list|dictionary|list-comprehension | 1 |
2,731 | 27,666,625 | Get Host name using IP address -Python | <p>I am trying to display all the connected machine names using ip address, I could get the IP address by checking the connection</p>
<pre><code>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((addr,80))
</code></pre>
<p>I have tried using <code>s.getsockname</code>,<code>socket.gethostname</code> an... | <p>I do not know if this will help, but <code>socket.getfqdn(IP_ADDRESS)</code> returns the hostname.</p> | python|sockets|networking|python-3.x | 0 |
2,732 | 36,925,839 | Adding numpy 3D array across one dimension | <p>I have a numpy array with following shape:</p>
<pre><code>(365L, 280L, 300L)
</code></pre>
<p>I want to sum up the array across the first dimension (365), so that I get 365 values as result.</p>
<p>I can do <code>np.sum()</code>, but how to specify which axis?</p>
<p>--EDIT:</p>
<p>The answer should have shape:... | <h1>NumPy version >= 1.7</h1>
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html" rel="nofollow"><code>np.sum</code></a> allows the use of a <code>tuple of integer</code> as <code>axis</code> argument to calculate the sum along multiple axis at once:</p>
<pre><code>import numpy as np
arr =... | python|numpy | 3 |
2,733 | 48,744,499 | How to reset numbered sections in Sphinx? | <p>I have several documents that are independant from each others: </p>
<pre><code>index.rst
foo.rst
bar.rst
conf.py
Makefile
</code></pre>
<p>I would like to access <code>foo.rst</code> from <code>index.rst</code>, but I would like the two subdocuments to start their numbering at 1.</p>
<p>In <code>index.rst</code>... | <p>You cannot have it both ways. See Sphinx documentation for <a href="http://www.sphinx-doc.org/en/master/markup/toctree.html" rel="nofollow noreferrer">Section numbering under the <code>toctree</code> directive</a> for the explanation:</p>
<blockquote>
<p><strong>Section numbering</strong></p>
<p>If you want to have ... | python-sphinx|sections|toctree | 1 |
2,734 | 20,252,484 | Can sklearn Random Forest classifier adjust sample size by tree, to handle class imbalance? | <p>Perhaps this is too long-winded. Simple question about sklearn's random forest: </p>
<p><em>For a true/false classification problem, is there a way in sklearn's random forest to specify the sample size used to train each tree, along with the ratio of true to false observations?</em></p>
<p>More details are below:<... | <p>In version 0.16-dev, you can now use <code>class_weight="auto"</code> to have something close to what you want to do. This will still use all samples, but it will reweight them so that classes become balanced. </p> | python|r|scikit-learn|classification|random-forest | 3 |
2,735 | 20,139,382 | mimetools.Message() to python 3 email.message.Message | <p>I try to port a python 2.x code to python 3.
The line im struggeling with is </p>
<pre><code>from mimetools import Message
...
headers = Message(StringIO(data.split('\r\n', 1)[1]))
</code></pre>
<p>i have figured out that mimetools are no longer present in python 3 and that the replacement is the email class.
I tr... | <p>Alex's own solution from his comment:</p>
<pre><code>import email
stream = io.StringIO()
rxString = data.decode("utf-8").split('\r\n', 1)[1]
stream.write(rxString)
headers = email.message_from_string(rxString)
</code></pre> | python|python-3.x|python-2.x | 4 |
2,736 | 4,085,121 | get some substring from readline() in python with regular expression | <p>I use tcpdump to sniff my network packet and I want to get some info out of the stored file. My file have 2 separated lines but they repeated many times.</p>
<pre><code>23:30:43.170344 IP (tos 0x0, ttl 64, id 55731, offset 0, flags [DF], proto TCP (6), length 443)
192.168.98.138.49341 > 201.20.49.239.80: Flags [... | <p><strong>For the first portion, to get timestamp, id and offset.</strong></p>
<p>I am sure this is a crude regex. </p>
<pre><code>>>> import re
>>> l = '23:30:43.170344 IP (tos 0x0, ttl 64, id 55731, offset 0, flags [DF], proto TCP (6), length 443)'
>>> k = re.compile(r'^([0-9:]+\.[0-9]+)... | python|regex | 2 |
2,737 | 4,754,003 | Dynamically instantiate Player class in a loop | <p>I am making a simple Python game. I have a text file with the following on each line:</p>
<pre><code>player name, player IP, player health, player items
</code></pre>
<p>I have a loop which goes through each line in the file and get the variables for each player (each line in the text file is a player).</p>
<p>I ... | <p>Sven has a good answer but you can even do away with the first line and just do</p>
<pre><code>config = [line.split(',') for line in open("config")]
</code></pre>
<p>Or as you may want to actually instantiate the players:</p>
<pre><code>config = [Player(line.split(',')) for line in open("config")]
</code></pre>
... | python|list|loops | 1 |
2,738 | 48,135,848 | Getting Error while writing a Large datarame of 60K rows into csv in Pandas | <p>I am trying to build an prediction model. I am trying to do that in 2 parts</p>
<ol>
<li>Preprocesing of the data in python file(.ipynb) and saving this preprocesed
data into a csv file
<ol start="2">
<li>Calling this preprocessed file in the Step 1 Model Prediction (.ipynb) file.</li>
</ol></li>
</ol>
<p><str... | <p>A better approach is to use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_pickle.html" rel="nofollow noreferrer">to_pickle</a>:</p>
<pre><code>train.to_pickle('C:/Users/Documents/Tesfile_Preprocessed.pickle')
</code></pre>
<p>Too many indices' means you've given too many index... | python|pandas|dataframe|scikit-learn | 1 |
2,739 | 51,298,772 | Drawing multiple charts using for loop in bokeh | <p>I need to draw a couple of horizontal bar charts. I applied the following for loop to draw them, but I get an error</p>
<pre><code>chart_cols = 'respondent_age respondent_gender respondent_edu respondent_occupation Religion Caste_cat CM_choice Likely_winner'.split()
for f in chart_cols:
count = df[f].value_coun... | <p>The following code works now.
for f in chart_cols:
count = df[f].value_counts()</p>
<pre><code>p = figure(plot_height=400, plot_width=400, title='Chart',toolbar_location=None)
p.title.align = "right"
p.xaxis.axis_label = 'Number of respondents'
p.yaxis.axis_label = str(f)
p.hbar(y=sorted(df[f].unique()), heig... | python|pandas|data-visualization|bokeh | 2 |
2,740 | 69,967,016 | How can I get rows that present outliers for the column? | <p>First I needed to create a function that returns True when the z-score is lower than -3 or larger than 3, and False otherwise. Then apply that function to dataframe. But now
I want to show the rows that present outliers for the column stand_Gross.SqFt. subset by passing the outliers series. How do I do that? Everyth... | <p>you do not want to do "apply" as you slow your code way down</p>
<p>start with</p>
<pre><code>housing['is_outlier'] = housing['stand_Gross.SqFt'] > 3
# print outliers
print(housing[housing['is_outlier']])
</code></pre>
<p>you can of coarse simply skip the first step</p>
<pre><code>outliers = housing[hou... | python|pandas|numpy|jupyter-notebook|data-analysis | 0 |
2,741 | 73,013,261 | Numpy: applying a function to axis 0 of a 2D matrix | <p>I have the function <code>test_outlier</code> that returns <code>True</code> if an <code>(x, y)</code> coordinate is greater than some <code>threshold</code> value away from a line segment that connects two points, otherwise <code>False</code>:</p>
<pre><code>import numpy as np
def test_outlier(point1: np.ndarray, p... | <p>This is the answer:</p>
<pre><code>def count_outliers(point1: np.ndarray, point2: np.ndarray, coordinates: np.ndarray, threshold: float) -> int:
num_outliers = 0
for elem in range(coordinates.shape[1]):
if test_outlier(point1, point2, coordinates[:, elem, None], threshold) is True:
num... | python|numpy | 0 |
2,742 | 73,359,763 | Extract month level precision from a date time column and make all day to 1 in pandas | <p>I have a time series, month level data as shown below.
df:</p>
<pre><code> date
0 1997-01-01 00:00:00
1 1997-02-02 00:00:00
2 1997-03-03 00:00:00
3 1997-04-02 00:00:00
4 1997-05-02 00:00:00
5 1997-06-01 00:00:00
6 1997-07-01 00:00:00
7 1997-08-31 00:00:00
8 1997-09-30 00:00:00
9 ... | <p>Use:</p>
<pre><code>df['date'] = pd.to_datetime(df['date']) + pd.offsets.DateOffset(day=1)
print (df)
date
0 1997-01-01
1 1997-02-01
2 1997-03-01
3 1997-04-01
4 1997-05-01
5 1997-06-01
6 1997-07-01
7 1997-08-01
8 1997-09-01
9 1997-10-01
10 1997-11-01
11 1997-12-01
12 1998-01-01
13 1998-02-01
14 1... | python-3.x|pandas|dataframe|datetime | 3 |
2,743 | 66,520,019 | Create a function to calculate median cost across different years | <p>I have a sample dataset which contains id and costs in diff years as the one below:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Id</th>
<th>2015-04</th>
<th>2015-05</th>
<th>2015-06</th>
<th>2015-07</th>
<th>2016-04</th>
<th>2016-05</th>
<th>2016-06</th>
<th>2016-07</th>
<th>2017-04<... | <p>First we split the column names on <code>-</code> and get only the year. Then we groupby over <code>axis=1</code> based on these years and take the median:</p>
<pre><code>df = df.set_index("Id")
df = df.groupby(df.columns.str.split("-").str[0], axis=1).median().reset_index()
# or get first 4 char... | python|pandas|function|median | 3 |
2,744 | 64,849,047 | Multiple foreign key lookups | <p>I have the following models in my app</p>
<p><strong>Account</strong></p>
<pre><code>class Account(CommonModel): # Accounts received from Client
client = models.ForeignKey('Client', on_delete=models.RESTRICT)
reference = models.CharField(db_index=True, max_length=50)
def __str__(self):
return f... | <p>I'd change the datamodel slightly to be more Django-y. Django has the concept of ManyToMany fields which is what you're trying to accomplish. (<a href="https://docs.djangoproject.com/en/3.1/ref/models/fields/#django.db.models.ManyToManyField" rel="nofollow noreferrer">https://docs.djangoproject.com/en/3.1/ref/models... | python|django | 0 |
2,745 | 53,147,822 | Convert DataFrame column date from 2/3/2007 format to 20070223 with python | <p>I have a dataframe with 'Date' and 'Value', where the Date is in format m/d/yyyy. I need to convert to yyyymmdd. </p>
<pre><code>df2= df[["Date", "Transaction"]]
</code></pre>
<p>I know datetime can do this for me, but I can't get it to accept my format. </p>
<p>example data files:</p>
<pre><code>6/15/2006,-4... | <p>You first need to convert to <code>datetime</code>, using <code>pd.datetime</code>, then you can format it as you wish using <code>strftime</code>:</p>
<pre><code>>>> df
Date Transaction
0 6/15/2006 -4.27
1 6/16/2006 -2.27
2 6/19/2006 -6.35
df['Date'] = pd.to_datetime(df['... | python|datetime | 3 |
2,746 | 68,705,559 | Seaborn lineplot unexpected behaviour in the range of xticks | <p>I am starting my studies on pandas and seaborn. I'm testing the lineplot, but the plot's x-axis does not show the range I expected for this attribute (<code>num_of_elements</code>). I expected that each value of this attribute shows up on the x-axis. Can someone explain what I'm missing on this plot? Thanks.</p>
<p>... | <p>The line:</p>
<pre><code>sns.despine(offset=0, trim=True, left=True)
</code></pre>
<p>removes the spines from plot, so it could cause confusion. The x axis is actually going from 6.75 to 144.25:</p>
<pre><code>print(ax.get_xlim())
# (6.75, 144.25)
</code></pre>
<p>But only ticks for 50 and 100 values are shown.<br /... | python|matplotlib|seaborn|line-plot|xticks | 2 |
2,747 | 71,683,007 | i need helping having it print the random names | <p>im trying to make it so the code prints out the random roles and the random name but when i run the code it gives <<strong>main</strong>.players object at 0x7f7b87db0bb0> get the <<strong>main</strong>.items object at 0x7f7b87dbf3d0> this response</p>
<p>i tried to add .name to the print but it would say... | <p>Add <code>__str__</code> methods to your classes to change the way that they're printed:</p>
<pre><code>class players:
def __init__ (self, role, inkey):
self.name = role
self.key=inkey
def __str__(self):
return self.name
class items:
def __init__ (self, name):
self.itemname = name
self.own... | python | 0 |
2,748 | 61,914,990 | Writing to a global variable with different processes in Python | <p>I have a global variable to which I want to write in with different processes (code below).
I use a reentrant lock to avoid race conditions (writing to the same place with many threads).
Interestingly it seems that the global variable doesn't get modified at all, but using only the main thread modifies it successful... | <p>Processes behave differently from threads, and specifically, they don’t share memory. Global variables are copied into the respective process which means their value in the main process doesn’t change - which is what caused the confusion in the question.</p>
<p>However, as stated in the documentation: <a href="http... | python|multithreading | 1 |
2,749 | 62,028,396 | Pandas: Subtract Date by factor until greater than another date | <p>As title suggest, I want to subtract factor from the date until date is just less than another date. </p>
<pre><code>op_d = {'ADate':[20200301,20200301,20200301,20200301,20200301,20200301],
'MDate':[20520801,20531001,20550405,20540701,20540910,20510701] ,
'EDate':[20200201,20200201,20200205,20200101... | <p>You can compose a function, then apply:</p>
<pre><code>def reduce(row):
a,m,f = row[['ADate','MDate','Frequency']]
offset = pd.DateOffset(months=f)
while m > a: m -= offset
return m
df['EDate'] = df.apply(reduce, axis=1)
</code></pre>
<p>Output:</p>
<pre><code> ADate MDate EDat... | python|pandas|timedelta | 1 |
2,750 | 60,718,772 | Python: how to avoid double loop in this case and speed up the performance? | <p>I am new to python. How do I <strong>vectorize</strong> or <strong>apply</strong> the code below, instead of using a double for loop? </p>
<p>It would be great if i can get a solution that significantly reduce the runtime and speed up the performance. Can this be done using <strong>vectorized</strong> or <code>app... | <p>From the top of my head, I don't know how to solve the problem efficiently, using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>pandas.DataFrame.apply()</code></a> method. </p>
<p>However, using vectors, it can be done much simpler. ... | python|vectorization | 1 |
2,751 | 56,851,679 | How to separate Pandas column that contains values stored as text and numbers into two seperate columns | <p>I have a Pandas column that contains results from a survey, which are either free text or numbers from 1-5. I am retrieving these from an API in JSON format and convert them into a DataFrame. Each row represents one question with the answer of a participant like this:</p>
<pre><code>Memberid | Question | Answer
... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html" rel="noreferrer"><code>Series.str.extract</code></a> with a regex pattern:</p>
<ul>
<li><code>(\d+)?</code> will extract consecutive digits</li>
<li><code>(\D+)</code> will extract consecutive non-digit c... | python|python-3.x|pandas | 9 |
2,752 | 61,124,749 | creating a Field based on the data in choice field in django | <p>I am trying to write a program for registering plates. However we have three types of plate and i've created a choice field for these three. the thing i wanna do is that i need to create a OneToOne field which it's given model is based on the data of the choice filed for example if the user chose 1 i need to have On... | <p>Apparently these kind of settings are not allowed in models, but you can write a global field for every one of them and then in the front-end part of the project you can only get the fields that you want for the chosen choice field</p> | python-3.x|django-models | 0 |
2,753 | 61,117,035 | numba.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend) Type of variable 'argmax' cannot be determined | <p>I try to speed up my python code by using <code>numba</code>. But after days of trying and hundreds of error messages, I still fail to get it work.</p>
<p>My current problem is this error message:</p>
<pre><code>Traceback (most recent call last):
File "E:/Studium/Masterarbeit/Masterarbeit/code/fast_simulation.p... | <p>I opened an issue on the <a href="https://github.com/numba/numba/issues/5547" rel="nofollow noreferrer">numba github page</a> for this question. The problem was that numba could not determine the type of the list <code>random_values</code>.
The solution for this is to use a typed list as follows:</p>
<p><code>random... | python|python-3.x|numba | 0 |
2,754 | 61,069,958 | Error importing googleanalytics on Python 3.8 | <p><code>pip install googleanalytics</code>
and
<code>pip3 install googleanalytics</code></p>
<p>both work fine, but </p>
<pre><code>import googleanalytics
</code></pre>
<p>returns:</p>
<p>optional_warn_function.func_name = f.func_name
AttributeError: 'function' object has no attribute 'func_name'</p> | <p>Reinstall the package using the following comment.</p>
<pre><code>pip install -e git+https://github.com/dvska/gdata-python3#egg=gdata
</code></pre>
<p>Or use <code>f.__name__</code> instead of <code>f.func_name</code> in the code.</p>
<p>For more information, see <a href="https://github.com/google/gdata-python-c... | python|google-analytics|python-import|google-analytics-api | 2 |
2,755 | 68,207,179 | Simple bot in python, i think i got the 'or' operator, and some other stuff messed up | <p>I'm trying to create a simple, veery simple bot. But its All messed up, pls help</p>
<pre><code>
inp = input('')
if inp == ('Hello' or 'hello' or 'hi' or 'Hi'):
inp1 = input('Hello, How are you? \n')
else:
sys.exit('hmmm')
if inp1 == "I'm Fine" or "i'm fine" or "i'm Fine" or &q... | <p><code>or</code> is applied between logical values, such as:</p>
<pre><code>inp == "Hello" or inp == "hello"
</code></pre>
<p>However, you can also achieve what you want using the <code>in</code> operator, which checks if a value is in a list</p>
<pre><code>inp in ('Hello', 'hello', 'hi', 'Hi')
</... | python | 0 |
2,756 | 59,672,071 | Reference to the pushed button | <p>I wanted to make an easy python project with the use of tkinter. In the screen, I need 81 buttons, so I thought the easiest way to perform this is by double "for" cycle but, when one of the buttons is pressed I need to configure its text but I don't know how to refer to it. Thank you for the answers. Here is my take... | <p>You can assign function with argument using <code>lambda</code> but to use button you have to do it after creating this button. </p>
<p>You have to also use <code>x=btn</code> (if you run it in loop) to copy value from <code>btn</code> to new variable <code>x</code>. Without this all <code>command</code> will have ... | python|button|tkinter | 0 |
2,757 | 67,988,321 | How to merge multiple dataframes of different length | <p>I want to merge multiple dataframe by a common column such that all the non matching data has NA.</p>
<pre><code>D1: D2:
ID val1 val2 ID Target
1 x y 1 0
1 x y 1 1
1 a b
1 a... | <p>Use this code:</p>
<pre><code>df1 = D1.merge(D2, how='left', on='ID')
df2 = D3.merge(D4, how='left', on='ID')
</code></pre>
<p>then merge <code>df1</code> and <code>df2</code></p> | python|pandas|dataframe | 0 |
2,758 | 67,084,019 | How to shift an entire column down (including the header) and then rename the header 'Name'? | <p>I am still learning coding and would be grateful for any help that I can get.</p>
<p>I have a dataframe where a person's name is the column header. I would like to shift the column header down 1 row and rename the column 'Name'. The column header will be different with each dataframe, though. It won't always be the ... | <p>Maybe this helps:</p>
<pre><code>df = pd.DataFrame({'index': range(4), 'Patrick': ['Stan', 'Frank', 'Emily', 'Tami']})
names = pd.concat([pd.Series(df.columns[1]),df.iloc[:, 1]]).reset_index(drop=True)
df = pd.DataFrame({'Names': names})
df
index Names
0 Patrick
1 Stan
2 Frank
... | python|dataframe|shift | 1 |
2,759 | 57,505,124 | Is it possible to fit a special size for tkinter window? | <p>I use tkinter in python and I want to fix the size of a window in tkinter for always it means that if user wants to change it by restore button the window size not changed.</p>
<pre><code>from tkinter import *
root=Tk()
root.geometry("1800x900")
root.mainloop()
</code></pre> | <p>I'm not sure I've fully understood your question, but to enforce a fixed window size I've used to set min and max to the same value, as follows.</p>
<pre class="lang-py prettyprint-override"><code>from Tkinter import Tk
root=Tk()
fixed_geometry=180,90
root.minsize(*fixed_geometry)
root.maxsize(*fixed_geometry)
root... | python|tkinter | 0 |
2,760 | 42,551,391 | Tensorflow Java API in windows | <p>I was trying to configure Tensorflow API for java in windows.</p>
<p>As per the read me
<a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/java/README.md" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/java/README.md</a></p>
<p>It says we have to bui... | <p>From the official <a href="https://www.tensorflow.org/install/install_sources" rel="nofollow noreferrer">website</a>:</p>
<blockquote>
<p>We don't officially support building TensorFlow on Windows; however,
you may try to build TensorFlow on Windows if you don't mind using the
highly experimental Bazel on Win... | java|c|compilation|tensorflow|native | 3 |
2,761 | 42,504,788 | Testing my classifier on a review | <p>Okay so I have been able to train my movie review classifier using the NaiveBayes Algorithm. The task is to: </p>
<blockquote>
<p>Test your classifier against a negative review of the walking dead. <a href="http://metro.co.uk/2017/02/27/the-walking-dead-season-7-episode-11-hostiles-and-calamities-wasnt-as-excitin... | <p>Your program can read the contents of a URL like this:</p>
<pre><code>with urllib.urlopen("http://example.com/review.html") as rec:
data = rec.read()
</code></pre>
<p>However, the URL you suggest points to an HTML document, so you'll need to "scrape" the contents (i.e., extract the body of the review and conve... | python|nlp|classification|nltk|document-classification | 1 |
2,762 | 20,762,250 | python Weather API location id | <pre><code>a=pywapi.get_loc_id_from_weather_com("pune")
{0: (u'TTXX0257', u'Pune, OE, Timor-leste'),
1: (u'INXX0102', u'Pune, MH, India'),
2: (u'BRPA0444', u'Pune, PA, Brazil'),
3: (u'FRBR2203', u'Punel, 29, France'),
4: (u'IDVV9705', u'Punen, JT, Indonesia'),
5: (u'IRGA2787', u'Punel, 19, Iran'),
6: (u'IRGA... | <p>I look the source code of pywapi, and found that the searchstring would be quoted(url encode, e.g. ',' will be quoted to "%2C") in <code>get_loc_id_from_waather_com</code>.</p>
<p>So when you call <code>pywapi.get_loc_id_from_weather_com(" Pune,MH,India")</code> it will request the url:<code>http://xml.weather.com/... | python-2.7 | 1 |
2,763 | 35,978,655 | Django - Leaving socket open while receiving data | <p>When I try to load in a largish (50mb) video, the server throws this error:</p>
<pre><code>[14/Mar/2016 02:16:13] "GET /media/media/uploads/SampleVideo_1280x720_50mb.mp4 HTTP/1.1" 200 52464391
[14/Mar/2016 02:16:13] "GET /media/media/uploads/SampleVideo_1280x720_50mb.mp4 HTTP/1.1" 200 286720
Traceback (most recent ... | <p>Using AWS S3 to store and handle the media this problem was fixed on all browsers. It must have something to do with the development server.</p> | python|django|html|sockets | 0 |
2,764 | 46,626,247 | tensorflow variable declaration what does point do? | <p>when we declare the Tensorflow variable<br/></p>
<pre><code>W = tf.Variable([.3], dtype = tf.float32)
b = tf.Variable([-.3], dtype = tf.float32)
</code></pre>
<p>what does .3 and -.3 mean in this declaration? </p> | <p>Initialize the variable with the given array.</p> | tensorflow | 1 |
2,765 | 46,586,914 | How to exact pattern matches? | <p>I have a file list like this: <code>aaa.txt bbb.doc ccc.gjf ddd.exe</code>. I want the file whoes extention is <code>gjf</code>. For some reasons, this file can not be the first or the last file in the file list. In other words, there must be a space before and after the file.
However, I tried many regular expressio... | <p>I do not think regex is entirely necessary for this problem:</p>
<pre><code>s = 'aaa.txt bbb.doc ccc.gjf ddd.exe'
final_data = [i for i in s.split()[1:-1] if i.endswith('.gjf')]
</code></pre>
<p>Output:</p>
<pre><code>['ccc.gjf']
</code></pre>
<p>However, if you really need regex, you can try this:</p>
<pre><co... | python|regex | 5 |
2,766 | 46,525,266 | Pseudowire ethernet control word support in scapy | <p>Is there any support for PW ethernet control word in scapy? I need to create a packet that contains this control word. Thank you!</p> | <p>Did some research into the scapy manual about how to build new layers and I have written this code. I took some example from the mpls code in scapy. I have tested it and it seems to add the PW Ethernet Control Word in the packet. </p>
<pre><code>from scapy.packet import Packet, bind_layers, Padding
from scapy.field... | python|networking|scapy | 2 |
2,767 | 47,944,185 | Python Zipline : "pandas_datareader._utils.RemoteDataError" & local data | <p>It's my first post, I hope it will be well done.</p>
<p>I'm trying to run the following ZipLine Algo with local AAPL data : </p>
<pre><code>import pandas as pd
from collections import OrderedDict
import pytz
from zipline.api import order, symbol, record, order_target
from zipline.algorithm import TradingAlgorithm
... | <p>Only reference and workaround I found regarding this issue is <a href="https://github.com/pydata/pandas-datareader/issues/394" rel="nofollow noreferrer">here</a>:</p>
<pre class="lang-py prettyprint-override"><code>from pandas_datareader.google.daily import GoogleDailyReader
@property
def url(self):
return 'ht... | python-2.7|csv|windows-7-x64|zipline | 1 |
2,768 | 37,200,939 | which python IDE is close to R for running a line code after the whole file | <p>I switched from R to python. I can not find any proper IDE that can run a single run after running the whole file. Spyder seems promissing but the text editor is terrible. Atom is good but everytime I have to run whole .py file. here is exact my problme:<br>
I run machine learning and load data through .py file and ... | <p>You don't need any special IDE to do this. Just launch your python program with the -i option. If you are looking for an IDE that makes it easy to do this (although you don't need an IDE to do it) in PyCharm you can just click on tab and be at the terminal where you can run this command. </p>
<p>Example code:</p>
... | python|ide | 1 |
2,769 | 40,352,859 | Checking whether user did like the post or not through template tag Django | <p>I am using template tag to check whether user liked the question in the feed previously in order to show him liked "red heart" img or otherwise not. I send user profile and pk of question as arguments to the functions, I want to know whether that user profile is one of that who liked the question. How can I impleme... | <p>I think you're just missing <code>.all()</code> on the end of <code>question_object.who_liked</code> in your pseudo code</p> | python|django | 0 |
2,770 | 43,949,711 | How to extract django objects having maximal value? | <p>Supposing I have a django model:</p>
<pre><code>class Score(models.Model):
name = models.CharField(max_length=32)
value = models.IntegerField()
status = models.BooleanField()
def __unicode__(self):
return u"{}: {} {}".format(self.name, self.value, self.status)
</code></pre>
<p>And the tabl... | <p>Solution:</p>
<pre><code>def process(names):
# Finding max scores
result = Score.objects.filter(name__in=names).\
values('name').annotate(Max('value'))
value_max_items = set(
row['value__max']
for row in result
)
# Query for objects having max scores
result = Score.... | python|mysql|django|python-2.7 | 0 |
2,771 | 27,079,890 | Is there a more elegant or simple way to accomplish my goal? | <p>I know the brute force way to do what I want but I am pretty sure there is a much more elegant way to accomplish my task. So I’m looking for help on an approach that’s better than the brute force way.</p>
<p>I have a spreadsheet like application with 21 rows and 5 columns on a grid. The first columns in the first r... | <p>This is quite involved, so I''ll just give you an overview and some pointers
on how to complete it.</p>
<p>The general outline is this:</p>
<ol>
<li>Create an <code>Equation</code> object to record the functional relationship between widgets.</li>
<li>Write a function which takes an Equation object and recomputes ... | python|pyqt | 4 |
2,772 | 40,954,293 | IN clause for Oracle Prepared Statement in Python cx_Oracle | <p>I'd like to use the IN clause with a prepared Oracle statement using cx_Oracle in Python.</p>
<p>E.g. query - <code>select name from employee where id in ('101', '102', '103')</code></p>
<p>On python side, I have a list <code>[101, 102, 103]</code> which I converted to a string like this <code>('101', '102', '103'... | <p>This concept is not supported by Oracle -- and you are definitely not the first person to try this approach either! You must either:</p>
<ul>
<li>create separate bind variables for each in value -- something that is fairly easy and straightforward to do in Python</li>
<li><p>create a subquery using the cast operato... | python|oracle|prepared-statement|cx-oracle | 4 |
2,773 | 40,998,634 | Adapting matrix array multiplication to use Numpy Tensordot | <p>I'm trying to speed up my code to perform some numerical calculations where I need to multiply 3 matrices with an array. The structure of the problem is the following:</p>
<ul>
<li>The array as a shape of (N, 10)</li>
<li>The first matrix is constant along the dynamic dimension of the array and has a shape of (10, ... | <p>Here's an approach using a combination of <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html" rel="nofollow noreferrer"><code>np.dot</code></a> and <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow noreferrer"><code>np.einsum</code></a> -</p>
<p... | python|arrays|algorithm|numpy|matrix | 2 |
2,774 | 40,788,432 | How to restructure a pandas dataframe even in the presence of missing data | <p>If I had a pandas DataFrame which looks like this:</p>
<pre><code> df=pandas.DataFrame(range(8))
0
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
</code></pre>
<p>What would be the best way to restructure this frame into two columns of five rows, regardless of the fact I only have 8 numbers? </p>
<p>so the outp... | <p>Try this:</p>
<pre><code>pd.DataFrame([df[0].values[:6], df[0].values[6:]]).T
0 1
0 0.0 5.0
1 1.0 6.0
2 2.0 7.0
3 3.0 NaN
4 4.0 NaN
</code></pre>
<p>And if you really want to repeat the <code>5</code> twice:</p>
<pre><code>pd.DataFrame([df[0].values[:6], df[0].values[5:]]).T
0 1
0 0.... | python|pandas|dataframe|pivot | 2 |
2,775 | 40,960,079 | Bisection algorithm to find multiple roots | <p>Is there a way to find all the roots of a function using something on the lines of the bisection algorithm?</p>
<p>I thought of checking on both sides of the midpoint in a certain range but it still doesn't seem to guarantee how deep I would have to go to be able to know if there is a root in the newly generated ra... | <p>The bisection algorithm can be used to find a root in a range where the function is monotonic. You can find such segments by studying the derivative function, but in the general case, no assumptions can be made as to the monotonicity of a given function over any range.</p>
<p>For example, the function <code>f(x) = ... | python|c++|c|algorithm | 1 |
2,776 | 40,857,188 | how to pass subprocess object to array | <ol>
<li>I need to pass the subprocess object to an array, so I can process the contents of the path.</li>
<li>here is my code</li>
<li><p>under "/file/path" the content is as such:
id1 name1 location1 hive 1 2014-10-01 4:02 /file/path</p>
<pre><code>p = subprocess.Popen(["hdfs", "dfs", "-ls", "/file/path"], stdout... | <p>OK, so the results of the screen output from the command <code>hdfs dfs -ls /some/path</code> is going to be a string. If your intention is to actually obtain file names you'll have to parse that string. If you want to add those paths to an array that contains the path a cheap way to do that is:</p>
<pre><code>impo... | python|object|hadoop|subprocess | 0 |
2,777 | 38,428,294 | How to restore a tensorflow model? | <p>I am trying to restore a model using a <code>.ckpt</code> file, which I got by running <code>word2vec_optimized.py</code> in <code>tensorflow/models/embedding</code>. I am not sure how to go about restoring the variables so that I can load the model and use it because all of the tf variables are encapsulated and ini... | <p>When you call the save function on your saver you pass it the tf.Session that you were using to train the model on. This contains a reference to the graph which contains all the variables. Don't confuse python variables with tensorflow variables. Even if you no longer have a variable in python which points to a te... | python|tensorflow|word2vec | 1 |
2,778 | 31,006,587 | generate a list of permutations that preserve a given partitioning (context: Graph Isomorphism) | <p>I'm working on a python program that tests two given networkx graphs G and H for an isomorphism by using a brute force method. Each node in each graph has been assigned a label and color attribute, and the program should test all possible bijections between graph G, for which the labeling is fixed, and graph H, for... | <p>To answer the algorithmic part of your question: Say your partition has k cells: C_1, ..., C_k. There is a 1 to 1 correspondence between permutations of the overall set that preserve the partition and the Cartesian product P_1 x P_2 x ... x P_k where P_i is the set of permutations of the cell C_i. itertools contains... | python|graph|permutation|networkx|isomorphism | 0 |
2,779 | 31,013,670 | Python - Grab Random Names | <p>Alright, so I have a question. I am working on creating a script that grabs a random name from a list of provided names, and generates them in a list of 5. I know that you can use the command</p>
<pre><code>items = ['names','go','here']
rand_item = items[random.randrange(len(items))]
</code></pre>
<p>This, if I a... | <p>You could use <a href="https://docs.python.org/2/library/random.html#random.choice" rel="nofollow"><code>random.choice()</code></a> to get one item only:</p>
<pre><code>items = ['names','go','here']
rand_item = random.choice(items)
</code></pre>
<p>Now just repeat this 5 times (a for loop!)</p>
<p>If you want the... | python|python-3.x | 3 |
2,780 | 31,064,190 | Python os.listdir and path with escape character | <p>I have a string variable that I have read from a file which is a path that contains an escape character i.e. </p>
<pre><code>dir="...Google\\ Drive"
</code></pre>
<p>I would like to then list all the files and directories in that path with os.listdir i.e.</p>
<pre><code>os.listdir(dir)
</code></pre>
<p>But I get... | <p>If the path could be arbitrary , you can split the the strings using <code>\\</code> removing any '' you may get along the way and then do <code>os.path.join</code> , Example -</p>
<pre><code>>>> import os.path
>>> l = "Google\Drive\\\\ Temp"
>>> os.path.join(*[s for s in l.split('\\') if... | python | 0 |
2,781 | 31,015,780 | Python os.walk topdown true with regular expression | <p>I am confused as to why the following ONLY works with <code>topdown=False</code> and returns nothing when set to <code>True</code> ?</p>
<p>The reason I want to use <code>topdown=True</code> is because it is taking a very long time to traverse through the directories. I believe that going topdown will increase the ... | <p>That is because your root directory doesn't match the regex, so after the first iteration, dirs is set to empty.</p>
<p>If what you want is to find all subdirectories which match the pattern, you should either:</p>
<ol>
<li>use topdown = False, or</li>
<li>do not prune the directories</li>
</ol> | python|regex|os.walk | 1 |
2,782 | 39,964,625 | How do I iterate through a list of strings and print each item? | <p>I have a list of strings and print each of the strings in the list, meaning not <code>['word1','word2','word3']</code> but instead: <code>word1</code>, <code>word2</code>, <code>word3</code>.</p>
<p>I tried doing this:</p>
<pre><code>for i in list:
print list[i]
</code></pre>
<p>but I get the message </p>
<... | <pre><code>for i in list:
print i
</code></pre>
<p>I is the list element: in other words, it takes on the values of the member strings, in order.</p> | python|string|list | 3 |
2,783 | 40,319,980 | Draw breaklines(dotted line/dashed line) in Opencv | <p>How to add breakline(dotted line/dashed line) in OpenCV drawing functions like <code>cv2.line()</code>,<code>cv2.rectangle()</code> ?</p>
<p>Is there a line type for break lines?</p> | <p>If the line is horizontal or vertical, you can do something like this. Kind of hacky, but gets the job done in just a few lines if you don't need anything fancy.</p>
<pre class="lang-py prettyprint-override"><code>y = 100 # vertical position of the line
thickness = 2 # thickness of the line
x0 = 0 # leftmost part... | python|opencv|drawing | 1 |
2,784 | 28,989,082 | Regex to match multiline text between two words including the words | <p>I'm editing a dictionary and trying to place every pronunciation tag <code>[s]...[/s]</code> after the transcription tag <code>[c darkslategray]...[/c]</code>. The problem is that not all the words contain both pronunciation and transcription.</p>
<p>Here's my current regex and the part of the dictionary:</p>
<pre... | <p>You regex should have a negative lookahead to make sure no nested <code>[s]...[/s]</code> is matched. Use this regex:</p>
<pre><code>(\s\[s\].*?\[\/s\])
(?s)(\s(?:(?!\[s\].*?\[\/s\]).)*?\[c darkslategray\].*?\[\/c\])
</code></pre>
<p><a href="https://regex101.com/r/cG3yK3/6" rel="nofollow">Updated RegEx Demo</a></... | python|regex|perl | 3 |
2,785 | 28,959,677 | Returning a string containing HTML in Python | <p>I am just wondering if anyone could help me to get this function to work. I am wishing to return a string which contains an HTML list for each of the items given in a list. </p>
<pre><code>def returnString(l):
hi = []
hi.append(l)
ol = "<ol>"
for i in hi:
ol += "<li>"+i+"</li>"
ol += "<... | <p>This depends on the type of items in the list but assuming that they can be converted to string a possibility would be to do the following:</p>
<pre><code>for i in hi:
ol += "<li>"+str(i)+"</li>"
ol += "</ol>"
return ol
</code></pre> | python|html | 1 |
2,786 | 29,158,621 | I am having a syntax error | <p>I am having a syntax error at </p>
<p><code>if first2 == 1:</code></p>
<pre><code>import time
name = raw_input("What is your name? ")
print "Hello, " + name
time.sleep(1.5)
print "Welcome to Kill the Dragon."
time.sleep(2)
print "In this game, you will choose an option, and if you make the right
choices, yo... | <pre><code>if first2 == 1:
print "Oh, good. If you had declined, we would have thrown you into the dungeons.
</code></pre>
<p>Add a quotation mark at the end</p>
<pre><code>if first2 == 1:
print "Oh, good. If you had declined, we would have thrown you into the dungeons."
</code></pre> | python|syntax | 0 |
2,787 | 58,900,989 | Multivariate time series forecasting with 3 months dataset | <p>I have 3 months of data (each row corresponding to each day) generated and I want to perform a multivariate time series analysis for the same : </p>
<p>the columns that are available are - </p>
<pre><code>Date Capacity_booked Total_Bookings Total_Searches %Variation
</code></pre>
<p>Each Date has 1 entry in ... | <p>One manner to improve your accuracy is to look to the autocorrelation of each variable, as suggested in the VAR documentation page:</p>
<p><a href="https://www.statsmodels.org/dev/vector_ar.html" rel="nofollow noreferrer">https://www.statsmodels.org/dev/vector_ar.html</a></p>
<p>The bigger the autocorrelation valu... | python|machine-learning|time-series|prediction | 1 |
2,788 | 52,057,927 | Extending array by repeating values if another array is not continues | <p>I am tracking some particles on a flat surface using the TrackPy plugin. This results in a dataframe with positions in x and y and a corresponding frame number, here illustrated by a simple list:</p>
<pre><code>x=[80.1,80.2,80.1,80.2,80.3]
y=[40.1,40.2,40.1,40.2,40.3]
frame = [1,2,3,4,5]
</code></pre>
<p>However, ... | <p>You can use Pandas, which internally utilizes NumPy arrays:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'x': x, 'y': y}, index=frame)
df = df.reindex(np.arange(df.index.min(), df.index.max()+1)).ffill()
</code></pre>
<p><strong>Result</strong></p>
<pre><code>print(df)
x y
1 80.1 40.1
2 8... | python|arrays|pandas|sorting|numpy | 4 |
2,789 | 56,317,919 | How to join a dataframe and dictionary on two rows | <p>I have a dictionary and a dataframe. The dictionary contains a mapping of one letter to one number and the dataframe has a row containing these specific letters and another row containing these specific numbers, adjacent to each other (not that it necessarily matters).</p>
<p>I want to update the row containing the... | <p>It's a little weird, but:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame(np.array([[4, 5, 6], ['a', 'b', 'c'], [7, 8, 9]]))
d = {'a': 2, 'b': 3, 'c': 5}
df.iloc[0] = df.iloc[1].map(lambda x: d[x] if x in d.keys() else x)
df
# 0 1 2
# 0 2 3 5
# 1 a b c
# 2 7 8 9
</code></pre>
<... | python|pandas|dataframe|dictionary|join | 1 |
2,790 | 36,505,501 | Python 3: JSON File Load with Non-ASCII Characters | <p>just trying to load this JSON file(with non-ascii characters) as a python dictionary with Unicode encoding but still getting this error:</p>
<p>return codecs.ascii_decode(input, self.errors)[0]</p>
<p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 90: ordinal not in range(128)</p>
<p>JSON f... | <p>You have several problems as near as I can tell. First, is the file encoding. When you open a file without specifying an encoding, the file is opened with whatever <code>sys.getfilesystemencoding()</code> is. Since that may vary (especially on Windows machines) its a good idea to explicitly use <code>encoding="utf-8... | python|json|python-3.x | 9 |
2,791 | 58,014,937 | TypeError: unhashable type: 'list' in Django/djangorestframework | <p>first of all I know there are some answers about this TypeError but none of them resolved my case. I did the research and that is why I am posting this question.</p>
<p>I got sutck at error saying TypeError: unhashable type:'list' in Django/djangorestframework.<br>
I am not even sure where the error is located at b... | <p>The error you get is because the underlying code tries to get the username field for the User model, but you have set it to a list instead of a string, which means that it cannot find the specified field.</p>
<p>Change <code>USERNAME_FIELD = ['email']</code> to <code>USERNAME_FIELD = 'email'</code></p> | python|django|django-rest-framework | 3 |
2,792 | 43,637,924 | How call result of a function in another function in a class? | <p>I have a code like this, in Python 2.7 :</p>
<pre><code>class App(ttk.frame):
def __init__(self, master=None):
ttk.Frame.__init__(self, master)
self.grid()
self.createWidgets()
def createWidgets(self):
self.okButton = ttk.Button(self, text = "OK", command = self.function2)
... | <p>You save the values <code>"x"</code> and <code>"y"</code> into <code>self.arg1</code> and <code>self.arg2</code> in <code>function1()</code>, so you must refer to them by those names in <code>function2()</code> also:</p>
<pre><code>class App(Object)
def function1(self, arg1, arg2):
self.arg1 = arg1
... | python|python-2.7|function|class | 2 |
2,793 | 54,463,257 | Ubuntu "git pull --rebase" gets errors of "can't stat objects" - can you suggest what is the problem | <p>I've been installing packages on my VM, (python / dev 3.6 oriented especially), and it seems I corrupted some setup, so now I get the following errors:</p>
<p>git pull --rebase
Auto packing the repository in background for optimum performance.
See "git help gc" for manual housekeeping.
error: The last gc run report... | <p>"git gc" solved the problem (see <a href="https://git-scm.com/docs/git-gc" rel="nofollow noreferrer">git docs</a>)</p> | python-3.x|git|ubuntu | 0 |
2,794 | 54,677,568 | flow of for loop in python | <p>I just new in python, I code for fetch array value from user, for this reason I asked a question yesterday in stackoverflow. Darius Morawiec and Austin give me the best salutation, but I don't understand the flow of for loop, I google it, but I don't understand those explanation.can any body explain the control of "... | <p>Despite share the same keywords, that's not a <code>for</code> loop; it's a list comprehension nested in <em>another</em> list comprehension. As such, you need to evaluate the inner list first:</p>
<pre><code>[
[int(input("Enter value for {}. row and {}. column: ".format(r + 1, c + 1)))
for c in range(n_col... | python|for-loop|multidimensional-array | 0 |
2,795 | 9,041,681 | OpenCV Python rotate image by X degrees around specific point | <p>I'm having a hard time finding examples for rotating an image around a specific point by a specific (often very small) angle in Python using OpenCV.</p>
<p>This is what I have so far, but it produces a very strange resulting image, but it is rotated somewhat:</p>
<pre><code>def rotateImage( image, angle ):
if ... | <pre><code>import numpy as np
import cv2
def rotate_image(image, angle):
image_center = tuple(np.array(image.shape[1::-1]) / 2)
rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)
result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR)
return result
</code></pre>
<p>Assuming... | python|opencv|rotation | 145 |
2,796 | 39,393,405 | Regex not returning specific match | <p>I am trying to extract a link from a script tag on a website.
currently my regex returns the whole block for some reason..</p>
<p>This is the content of the script tag I want to get the link from:</p>
<pre><code><script type="text/javascript">
var key = '';
var url = 'http://stream1.song365.me/h1/20160129/17... | <p>Pre-compile the pattern and <em>reuse</em> for both locating the element and extracting the link:</p>
<pre><code>pattern = re.compile("var hqurl = '(.*?mp3)';", re.MULTILINE | re.DOTALL)
link = soup.find("script", text=pattern)
print(pattern.search(link.text).group(1))
</code></pre>
<p>Note that I've improved the ... | regex|python-3.x|beautifulsoup|python-requests | 1 |
2,797 | 37,174,237 | pandas_datareader.data not returning all stock values from start to end date | <p>I am trying to get stock data from yahoo using <code>pandas_datareader.data</code> and i keep getting missing sections of data. here is what i have coded. all i want to do right now is return all the data for the dates between the start and end dates </p>
<pre><code>import pandas as pd
import pandas_datareader.da... | <p>This is how <code>pandas</code> displays the result <a href="http://pandas.pydata.org/pandas-docs/stable/options.html#overview" rel="nofollow">(as explained here)</a>. <code>pandas</code> omits rows that exceed the <code>pd.set_option('max_rows', X)</code> setting (<code>default</code> is 50 I believe). You can see ... | python|pandas|datareader|yahoo-finance|stocks | 1 |
2,798 | 7,157,550 | double loop in psp/python/html from a mysql query | <p>I'm trying to program a script that will take in a user input of a place they want to go, starting with the country. Then take the user's input and update my list of which state is in the country then, which city is in the state AND country. </p>
<p>I'm using python/psp for my backend and html for my front end. I'm... | <p>I have never heard of Python Server Pages, wow. Anyway, in <a href="http://diveintopython.net/getting_to_know_python/indenting_code.html" rel="nofollow">Python indentation matters</a>, you can think of indentation as the replacement for curly braces in C-style languages. </p>
<pre><code>for record in result:
cu... | python|html|mysql-python | 0 |
2,799 | 72,640,100 | Take indices of non zero elements of matrix | <p>I create matrix "adjacency_matrix" with following code:</p>
<pre><code>n = int(input())
# Initialize matrix
adjacency_matrix = []
# For user input
for i in range(ROWS):
a =[]
for j in range(COLUMNS):
a.append(int(input()))
adjacency_matrix.append(a)
</code></pre>
<p>I ... | <p>Try this list comprehension. It returns a list of positions (x,y) and you can iterate over each one and insert them into g.addEdge()</p>
<pre><code>adjacency_matrix =[[2,3,0],[0,0,1],[1,5,0]]
pos = [(count1, count2) for count1, lst in enumerate(adjacency_matrix) for count2, num in enumerate(lst) if num != 0]
</code... | python|matrix | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.