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 |
|---|---|---|---|---|---|---|---|---|---|
Modifying python colormaps to single value beyond a specific point | 39,024,331 | <p>How do I change a colormap color scheme to show the same color beyond a point.</p>
<p>E.g. here's my colormap:</p>
<pre><code>import palettable
cmap = palettable.colorbrewer.sequential.YlGn_9.mpl_colormap
</code></pre>
<p>If I use this colormap to plot a range from 0 to 100, how can I modify the color map such th... | 2 | 2016-08-18T17:35:54Z | 39,025,686 | <p><code>cmap.set_over("red")</code></p>
<p>And you may wanna use one of the <a href="http://matplotlib.org/api/colors_api.html" rel="nofollow">norm functions</a> to set your specific bounds. If using imshow, you can also set the parameter vmin=50 to make that your top value. </p>
| 2 | 2016-08-18T19:01:00Z | [
"python",
"matplotlib",
"seaborn"
] |
Modifying python colormaps to single value beyond a specific point | 39,024,331 | <p>How do I change a colormap color scheme to show the same color beyond a point.</p>
<p>E.g. here's my colormap:</p>
<pre><code>import palettable
cmap = palettable.colorbrewer.sequential.YlGn_9.mpl_colormap
</code></pre>
<p>If I use this colormap to plot a range from 0 to 100, how can I modify the color map such th... | 2 | 2016-08-18T17:35:54Z | 39,124,326 | <p>You can access the colors with:</p>
<pre><code>cmap_dict = cmap._segmentdata
</code></pre>
<p>which yields a dictionary. By indexing it with:</p>
<pre><code>red = cmap_dict["red"]
green= cmap_dict["green"]
blue = cmap_dict["blue"]
alpha = cmap_dict["alpha"]
</code></pre>
<p>Now you can add a color from the list ... | 1 | 2016-08-24T13:12:06Z | [
"python",
"matplotlib",
"seaborn"
] |
Modifying python colormaps to single value beyond a specific point | 39,024,331 | <p>How do I change a colormap color scheme to show the same color beyond a point.</p>
<p>E.g. here's my colormap:</p>
<pre><code>import palettable
cmap = palettable.colorbrewer.sequential.YlGn_9.mpl_colormap
</code></pre>
<p>If I use this colormap to plot a range from 0 to 100, how can I modify the color map such th... | 2 | 2016-08-18T17:35:54Z | 39,154,679 | <p>You could create the colormap for the given range (0 â100) by stacking two different colormaps on top of each other as shown:</p>
<p><strong>Illustration:</strong></p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import palettable
import matplotlib.colors as mcolors
# Set random seed
np.random.... | 2 | 2016-08-25T21:02:17Z | [
"python",
"matplotlib",
"seaborn"
] |
Modifying python colormaps to single value beyond a specific point | 39,024,331 | <p>How do I change a colormap color scheme to show the same color beyond a point.</p>
<p>E.g. here's my colormap:</p>
<pre><code>import palettable
cmap = palettable.colorbrewer.sequential.YlGn_9.mpl_colormap
</code></pre>
<p>If I use this colormap to plot a range from 0 to 100, how can I modify the color map such th... | 2 | 2016-08-18T17:35:54Z | 39,184,812 | <p>You can create a new colormap from an existing colormap using:</p>
<p><code>newcmap = cmap.from_list('newcmap',list(map(cmap,range(50))), N=50)</code></p>
<p>This new map uses the last value from the colormap for colors over 50. To make the last color red, we can just append red to the last color in the list that... | 1 | 2016-08-27T19:15:14Z | [
"python",
"matplotlib",
"seaborn"
] |
Modifying python colormaps to single value beyond a specific point | 39,024,331 | <p>How do I change a colormap color scheme to show the same color beyond a point.</p>
<p>E.g. here's my colormap:</p>
<pre><code>import palettable
cmap = palettable.colorbrewer.sequential.YlGn_9.mpl_colormap
</code></pre>
<p>If I use this colormap to plot a range from 0 to 100, how can I modify the color map such th... | 2 | 2016-08-18T17:35:54Z | 39,185,270 | <p>I don't think you should change the colormap, but rather the <em>object</em> using the colormap. I asked a similar question not so long ago: <a href="http://stackoverflow.com/questions/38918306/change-color-for-first-level-of-contourf">change color for first level of contourf</a>, and I took the answer from here: <a... | 1 | 2016-08-27T20:05:29Z | [
"python",
"matplotlib",
"seaborn"
] |
Python mechanize navigation using __doPostBack functions | 39,024,386 | <p>How can I use mechanize to navigate through a table on a web-page if the table uses __doPostBack functions? </p>
<p>My code is:</p>
<pre><code>import mechanize
br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 ... | 0 | 2016-08-18T17:39:52Z | 39,297,042 | <p>Mechanize can be used to navigate a table which uses __doPostBack. I used BeautifulSoup to parse the HTML for the required parameters and followed useful <a href="http://stackoverflow.com/questions/39254333/python-re-escape-coincidental-parentheses-in-regex-pattern/" title="guidance with the regex">guidance with the... | 0 | 2016-09-02T16:30:01Z | [
"python",
"python-2.7",
"mechanize",
"dopostback"
] |
How do I log into Google through python requests? | 39,024,406 | <p>I'm making an API using Python requests, and HTTP GET is working fine, but I'm having a little bit of trouble with HTTP POST. So, as with a lot of websites, you can read information, but in order to make a post request (such as following a user, or writing a post), you need to have an authenticated session. THIS web... | -1 | 2016-08-18T17:41:04Z | 39,027,207 | <p>I do not know about python requests but to send an email its as easy as this</p>
<pre><code>import yagmail
yagmail.SMTP(emailh).send(email, subject, body)
#emailh = your email (just username no @gmail.com)
#email = send to (full email including domain ***@gmail.com or ***@outlook.com)
#subject = subject of the mes... | -1 | 2016-08-18T20:46:28Z | [
"python",
"http",
"post",
"get",
"python-requests"
] |
modprobe: FATAL: Module nvidia-uvm not found in directory /lib/modules/ | 39,024,542 | <p>I had an issue recently after successfully installing and testing Tensorflow compiled with GPU support.</p>
<p>After rebooting the machine, I got the following error Message when I tried to run a Tensorflow program:</p>
<pre><code>...
('Extracting', 'MNIST_data/t10k-labels-idx1-ubyte.gz')
modprobe: FATAL: Module... | 0 | 2016-08-18T17:48:21Z | 39,024,591 | <p>I actually solved my own problem and wanted to share the solution which worked for me.</p>
<p>The magic Google search was:
"modprobe: FATAL: Module nvidia-uvm not found in directory /lib/modules/"</p>
<p>Which led me to the following answer on askubuntu:
<a href="http://askubuntu.com/a/496146">http://askubuntu.com... | 1 | 2016-08-18T17:50:43Z | [
"python",
"tensorflow",
"gpu",
"nvidia"
] |
Error 401 and API V1.1 Python | 39,024,600 | <p>Good morning,
I am trying to download the people that is twitting certain words in an area by this python code:</p>
<pre><code>import sys
import tweepy
consumer_key="LMhbj3fywfKPNgjaPhOwQuFTY"
consumer_secret=" LqMw9x9MTkYxc5oXKpfzvfbgF9vx3bleQHroih8wsMrIUX13nd"
access_key="3128235413-OVL6wctnsx1SWMYAGa5vVZwDH5u... | 0 | 2016-08-18T17:51:14Z | 39,038,396 | <p>If it says that your credentials are incorrect, you might want to check your credentials: you need to remove the whitespaces in your consumer secret for your code to work.</p>
<p>Also, I just tested your credentials (without whitespaces) and they are working. I can do whatever I want on behalf of your application. ... | 0 | 2016-08-19T11:50:16Z | [
"python",
"api",
"authentication",
"tweepy"
] |
Long tail distribution of random numbers in Python | 39,024,785 | <p>I need to make a randomizing function in Python returning values using long tail distribution. Unfortunately, my math skills are nowhere near my programming skills so I'm stuck.</p>
<p>This is the kind of distribution I'm looking for:
<img src="http://www.danvk.org/wp/wp-content/uploads/2007/02/scores.png" alt="">.... | 0 | 2016-08-18T18:04:41Z | 39,024,861 | <p>There are quite a few distributions with single peak value and some tail, <a href="https://en.wikipedia.org/wiki/Log-normal_distribution" rel="nofollow">log-normal</a>, <a href="https://en.wikipedia.org/wiki/Gamma_distribution" rel="nofollow">Gamma</a>, <a href="https://en.wikipedia.org/wiki/Chi-squared_distribution... | 1 | 2016-08-18T18:10:05Z | [
"python",
"random",
"distribution"
] |
Long tail distribution of random numbers in Python | 39,024,785 | <p>I need to make a randomizing function in Python returning values using long tail distribution. Unfortunately, my math skills are nowhere near my programming skills so I'm stuck.</p>
<p>This is the kind of distribution I'm looking for:
<img src="http://www.danvk.org/wp/wp-content/uploads/2007/02/scores.png" alt="">.... | 0 | 2016-08-18T18:04:41Z | 39,024,927 | <p>You might look into Numpy's <a href="http://docs.scipy.org/doc/numpy/reference/routines.random.html" rel="nofollow">random sampling</a> options. See which ones are included in the list of <a href="https://en.wikipedia.org/wiki/Heavy-tailed_distribution#Common_heavy-tailed_distributions" rel="nofollow">common heavy-t... | 0 | 2016-08-18T18:15:15Z | [
"python",
"random",
"distribution"
] |
Python Numpy nanmax() returning nan when there are non nan values in the array | 39,024,791 | <p>I tried to use Numpy's nanmax function to get the max of all non-nan values in a matrix's column, for some it works, for some it returns nan as the maximum. However, there are non-nan values in every column and just to be sure I tried the same thing in R with max(x, na.rm = T) and everything is fine there. </p>
<p>... | 0 | 2016-08-18T18:05:04Z | 39,025,455 | <p>Your array is an <code>object</code> array, meaning the elements in the array are arbitrary python objects. Pandas uses object arrays, so it is likely that when you converted your Pandas DataFrame to a numpy array, the result was an object array. <code>nanmax()</code> doesn't handle object arrays correctly.</p>
<... | 1 | 2016-08-18T18:47:04Z | [
"python",
"numpy"
] |
Unloading audio samples in kivy | 39,024,813 | <p>Audio unload does not seem to actually release memory, at least as far as top on linux is concerned. Repeatedly loading and unloading causes memory usage to creep upward. Did I miss something obvious?</p>
<pre><code>from __future__ import print_function
import kivy
kivy.require('1.9.0') # replace with your current ... | 0 | 2016-08-18T18:06:30Z | 39,025,461 | <pre><code>del an_obj
</code></pre>
<p>Try to delete the actual object, maybe? I am not exactly sure what you are doing.</p>
| -1 | 2016-08-18T18:47:24Z | [
"python",
"audio",
"kivy"
] |
Unloading audio samples in kivy | 39,024,813 | <p>Audio unload does not seem to actually release memory, at least as far as top on linux is concerned. Repeatedly loading and unloading causes memory usage to creep upward. Did I miss something obvious?</p>
<pre><code>from __future__ import print_function
import kivy
kivy.require('1.9.0') # replace with your current ... | 0 | 2016-08-18T18:06:30Z | 39,041,429 | <p>Actually, the memory does not appear to creep upward indefinitely, so while SoundGstplayer seems to allocate itself much more than the SDL2 backend, this probably as intended.</p>
| 0 | 2016-08-19T14:23:13Z | [
"python",
"audio",
"kivy"
] |
How to Create a port scanner TCP SYN using the method (TCP SYN )? | 39,024,816 | <pre><code>#####################################
# Portscan TCP #
# #
#####################################
# -*- coding: utf-8 -*-
#!/usr/bin/python3
import socket
ip = input("Digite o IP ou endereco: ")
ports = []
count = 0
while count < 10:
ports.append(int(input("Digite a porta: ")))
count += ... | -2 | 2016-08-18T18:06:42Z | 39,091,110 | <p>First, you will have to generate your own SYN packets using RAW sockets. You can find an example <a href="http://www.binarytides.com/raw-socket-programming-in-python-linux/" rel="nofollow">here</a></p>
<p>Second, you will need to listen for SYN-ACKs from the scanned host in order to determine which ports actually t... | 3 | 2016-08-23T01:46:50Z | [
"python",
"python-3.x"
] |
How to Create a port scanner TCP SYN using the method (TCP SYN )? | 39,024,816 | <pre><code>#####################################
# Portscan TCP #
# #
#####################################
# -*- coding: utf-8 -*-
#!/usr/bin/python3
import socket
ip = input("Digite o IP ou endereco: ")
ports = []
count = 0
while count < 10:
ports.append(int(input("Digite a porta: ")))
count += ... | -2 | 2016-08-18T18:06:42Z | 39,094,232 | <p>As @Upsampled mentioned, you might use raw sockets (<a href="https://en.wikipedia.org/" rel="nofollow">https://en.wikipedia.org/</a>) as you only need a subset of TCP protocol (send <strong>SYN</strong> and recieve <strong>RST-ACK</strong> or <strong>SYN-ACK</strong>
).</p>
<p>As coding something like <a href="http... | 3 | 2016-08-23T06:53:47Z | [
"python",
"python-3.x"
] |
Ignore string data that does not match a certain format when calculating "min" with Pandas | 39,024,852 | <p>I have a DataFrame column 'datetime' with the values in this format:</p>
<p><code>'2016-08-01 13:43:35'</code></p>
<p>I would like to find the min and max values. The problem is that some of the rows are missing time values so they look like this:</p>
<p><code>'2016-07-29 '</code></p>
<p>How can I exclude the r... | 0 | 2016-08-18T18:09:41Z | 39,024,985 | <p>You can convert values that have a specific format to datetime, and the remaining ones will be NaT. If you take the minimum on the resulting series, it will ignore NaTs.</p>
<pre><code>df['datetime'] = ['2016-08-01 13:43:35', '2016-06-01 13:43:35', '2013-08-01 13:43:35',
'2016-07-29 ']
df
Out:
... | 1 | 2016-08-18T18:19:12Z | [
"python",
"pandas"
] |
Ignore string data that does not match a certain format when calculating "min" with Pandas | 39,024,852 | <p>I have a DataFrame column 'datetime' with the values in this format:</p>
<p><code>'2016-08-01 13:43:35'</code></p>
<p>I would like to find the min and max values. The problem is that some of the rows are missing time values so they look like this:</p>
<p><code>'2016-07-29 '</code></p>
<p>How can I exclude the r... | 0 | 2016-08-18T18:09:41Z | 39,025,146 | <p>Since your date strings have a decreasing order of magnitude (i.e. year --> month --> ...), there is actually no need to convert toe datetime objects.</p>
<p>Also, since your date strings should all be fixed-width, all you really need to do is drop the rows with missing values and then compare the date strings dire... | 0 | 2016-08-18T18:28:24Z | [
"python",
"pandas"
] |
SQLalchemy trying to connect to postgresql using oop | 39,024,897 | <p>I'm trying to teach myself a bit of OOP and as a test i'm trying to create a class that will connect to an existing postgresql database i've created.</p>
<p>I can connect to the database fine using sqlalchemy if I use this code </p>
<pre><code>engine = create_engine('postgresql://user@localhost/dbname')
conn = eng... | 0 | 2016-08-18T18:12:57Z | 39,025,629 | <p>I always use Pajlada's <a href="https://github.com/pajlada/pajbot/blob/master/pajbot/managers/db.py" rel="nofollow">Database Manager Singleton Class</a>. It's pretty easy to get going. All you need to do is initialize the class with your URL.</p>
<pre><code>DBManager.init('psqlurlhere')
</code></pre>
<p>and then w... | 0 | 2016-08-18T18:58:07Z | [
"python",
"postgresql",
"oop",
"sqlalchemy"
] |
How to write out to compressed file with pyscopg2.copy_to or copy_expert? | 39,025,204 | <p>All of the examples I've seen have used <code>psql</code> with something like <code>COPY COMMAND | gzip > 'filename'</code>. I'd prefer to use a solution with <code>psycopg2</code> if possible, and I was thinking that it might be nice to write it out to a string buffer type object which processes the data and th... | -1 | 2016-08-18T18:31:22Z | 39,025,336 | <p>The documentation for psycopg says that <a href="http://initd.org/psycopg/docs/cursor.html#cursor.copy_to" rel="nofollow"><code>copy_to</code></a> accepts any file-like object. Thus you could simply use the <a href="https://docs.python.org/3/library/gzip.html" rel="nofollow"><code>gzip.open</code></a> to open a writ... | 1 | 2016-08-18T18:39:40Z | [
"python",
"postgresql",
"psycopg2"
] |
Trigger event when Bokeh DataTable Selection | 39,025,264 | <p>Is it possible to trigger a callback event when I select a row (or rows) of a Bokeh <code>DataTable</code>?</p>
<pre><code>def update(rows):
...
dt = DataTable(...)
dt.on_select(update)
</code></pre>
<p>I see that there is an <code>.on_change</code> method that can trigger on a particular property, however I c... | 0 | 2016-08-18T18:35:05Z | 39,025,584 | <p>I believe that selecting a row of a data table is the same as making a selection a data source. So, if you attach a callback to the datasource powering the table then the callback should work.</p>
<pre><code>source = ColumnDataSource(mpg)
columns = [....]
data_table = DataTable(source=source, columns=columns)
sourc... | 1 | 2016-08-18T18:54:51Z | [
"python",
"bokeh"
] |
Access partial results of a Celery task | 39,025,270 | <p>I'm not a Python expert, however I'm trying to develop some long-running Celery-based tasks which I'm able to access their partial results instead of waiting for the tasks to finish. </p>
<p>As you can see in the code below, given a multiplier, an initial and final range, the <em>worker</em> creates a list of size ... | 0 | 2016-08-18T18:35:31Z | 39,031,088 | <p>You absolutely need to use an external storage such as SQL or Redis/Memcached because different tasks can be executed on different servers in common case.</p>
<p>So in your example you should store list_values in some DB and update it during the loop.</p>
| 0 | 2016-08-19T04:23:48Z | [
"python",
"celery",
"jobs"
] |
Get length of CSV to show progress | 39,025,315 | <p>I am working with a large number of CSV files, each of which contain a large amount of rows. My goal is to take the data line by line and write it to a database using Python. However because there is a large amount of data I would like tot keep track of how much data has been written. For this I have counted the amo... | 0 | 2016-08-18T18:38:32Z | 39,025,933 | <p>You can't count the lines in a file without opening it and counting the lines.</p>
<p>If your files are so large that counting lines with <code>row_count = sum(1 for row in file_handle)</code> is not practical, and reading the whole file into memory is a non-starter, a different approach may be needed.</p>
<p>It i... | 1 | 2016-08-18T19:17:10Z | [
"python",
"csv"
] |
Get length of CSV to show progress | 39,025,315 | <p>I am working with a large number of CSV files, each of which contain a large amount of rows. My goal is to take the data line by line and write it to a database using Python. However because there is a large amount of data I would like tot keep track of how much data has been written. For this I have counted the amo... | 0 | 2016-08-18T18:38:32Z | 39,025,972 | <p>If you just want to show some progress, you could try using <a href="https://pypi.python.org/pypi/tqdm" rel="nofollow">tqdm</a>. </p>
<pre><code>from tqdm import tqdm
with zipArchive.open(fileName[:-4] + '.csv', 'r') as csvFile:
lines = [line.decode('ascii') for line in csvFile]
currentRow = 1
for row... | 3 | 2016-08-18T19:19:19Z | [
"python",
"csv"
] |
Python+kivy+SQLite: How to set label initial value and how to update label text? | 39,025,320 | <p>everyone,</p>
<p>I want to use <code>kivy+Python</code> to display items from a <code>db</code> file. </p>
<p>To this purpose I have asked a question before: <a href="http://stackoverflow.com/questions/38939416/pythonkivysqlite-how-to-use-them-together">Python+kivy+SQLite: How to use them together</a> </p>
<p>The... | 0 | 2016-08-18T18:38:44Z | 39,025,438 | <pre><code>from kivy.app import App
from kivy.lang import Builder
from kivy.properties import StringProperty
from kivy.uix.widget import Widget
Builder.load_string("""
<ScreenX>
BoxLayout:
orientation: 'vertical'
Label:
text: root.label_text
Button:
text: 'Clic... | 1 | 2016-08-18T18:45:39Z | [
"android",
"python",
"kivy",
"kivy-language"
] |
How can I release memory after using csv.writer in python? | 39,025,431 | <p>I've got 1.6GB available to use in a python process. I'm writing a large csv file which data is coming from a database. The problem is: After the file is written, the memory (>1.5GB) is not released immediately which causes an error in the next bit of code (allocating memory fails because the OS cannot find enough m... | 0 | 2016-08-18T18:45:15Z | 39,025,587 | <p>I am thinking the issue is that you never closed the file. Give this a shot.</p>
<pre><code>size_to_read = 20000
sqlData = rs_cursor.fetchmany(size_to_read)
with open(fname_location, "wb")) as f:
c = csv.writer(f)
c.writerow(headers)
print("- Generating file %s ..." % out_fname)
while sqlData:
with o... | 1 | 2016-08-18T18:54:53Z | [
"python",
"csv"
] |
No module named owslib.wmts | 39,025,502 | <p>I installed owslib through command line by:</p>
<pre><code>pip install owslib
</code></pre>
<p>and it worked. But for some reason I am getting an error saying: No module named owslib.wmts . What do you think would be causing this? I tried installing Anaconda, I've rebooted a few times, and when I run this script:<... | 0 | 2016-08-18T18:49:10Z | 39,027,073 | <p>You can try
pip install owslib.wmts
Otherwise there might be a problem within the module. Look at this website it has the documentation for owslib <a href="https://geopython.github.io/OWSLib/" rel="nofollow">documentation</a></p>
| 0 | 2016-08-18T20:36:10Z | [
"python"
] |
No module named owslib.wmts | 39,025,502 | <p>I installed owslib through command line by:</p>
<pre><code>pip install owslib
</code></pre>
<p>and it worked. But for some reason I am getting an error saying: No module named owslib.wmts . What do you think would be causing this? I tried installing Anaconda, I've rebooted a few times, and when I run this script:<... | 0 | 2016-08-18T18:49:10Z | 39,038,952 | <p>So I am 99% sure this is a problem on my work machine. I have found a workaround by using the Anaconda terminal instead of windows cmd line.</p>
| 0 | 2016-08-19T12:22:02Z | [
"python"
] |
how to call a method and make it run in background in python 3.4? | 39,025,511 | <p>I have implemented the Google Cloud Messaging server in python and I want that method to be Asynchronous. I do not expect any return values from that method. Is there a simple way to do this?
I have tried using <code>async</code> from <code>asyncio</code> package:</p>
<pre><code>...
loop = asyncio.get_event_loop()
... | 1 | 2016-08-18T18:49:40Z | 39,035,031 | <p>You could use a <a href="https://docs.python.org/dev/library/concurrent.futures.html#threadpoolexecutor" rel="nofollow">ThreadPoolExecutor</a>:</p>
<pre><code>from concurrent.futures import ThreadPoolExecutor
executor = ThreadPoolExecutor()
...
future = executor.submit(send_notification, module_name, module_status)... | 1 | 2016-08-19T09:01:15Z | [
"python",
"python-3.x",
"google-cloud-messaging",
"python-asyncio"
] |
how to call a method and make it run in background in python 3.4? | 39,025,511 | <p>I have implemented the Google Cloud Messaging server in python and I want that method to be Asynchronous. I do not expect any return values from that method. Is there a simple way to do this?
I have tried using <code>async</code> from <code>asyncio</code> package:</p>
<pre><code>...
loop = asyncio.get_event_loop()
... | 1 | 2016-08-18T18:49:40Z | 39,037,495 | <p>Since GCM is not async library compatible need to use an external event loop. </p>
<p>There are a few, simplest one IMO is probably <a href="http://www.gevent.org/" rel="nofollow">gevent</a>.</p>
<p>Note that gevent monkey patching may introduce dead locks if the underlying libraries used rely on blocking behaviou... | 0 | 2016-08-19T11:06:26Z | [
"python",
"python-3.x",
"google-cloud-messaging",
"python-asyncio"
] |
how to call a method and make it run in background in python 3.4? | 39,025,511 | <p>I have implemented the Google Cloud Messaging server in python and I want that method to be Asynchronous. I do not expect any return values from that method. Is there a simple way to do this?
I have tried using <code>async</code> from <code>asyncio</code> package:</p>
<pre><code>...
loop = asyncio.get_event_loop()
... | 1 | 2016-08-18T18:49:40Z | 39,294,376 | <p>You can use asyncio's api: <code>loop.run_in_executor(None, callable)</code></p>
<p>This will run the code using an executor (by default a <a href="https://docs.python.org/dev/library/concurrent.futures.html#threadpoolexecutor" rel="nofollow">ThreadPoolExecutor</a>)</p>
<p>See the <a href="https://docs.python.org/... | 0 | 2016-09-02T14:06:39Z | [
"python",
"python-3.x",
"google-cloud-messaging",
"python-asyncio"
] |
Python Regex: dealing with 4 patterns using re.search() and if statement once | 39,025,551 | <p>For example, below are the 4 patterns existing in a list of strings and results to be returned:</p>
<p>Pattern 1: <code>'A: 45'</code> --> 45 (45 - 0)</p>
<p>Pattern 2: <code>'B: 34'</code> --> -34 (0 - 34)</p>
<p>Pattern 3: <code>'A: 45, B: 34'</code> --> 11 (45 - 34)</p>
<p>Pattern 4: <code>'B: 34, A: 45'</cod... | 0 | 2016-08-18T18:52:13Z | 39,026,122 | <p>Here you go (with a combination of a regex and tuple unpacking):</p>
<pre><code>import re
strings = ['A: 45', 'B: 34', 'A: 45, B: 34', 'B: 34, A: 45']
rx = re.compile(r'([AB]): (\d+)')
for string in strings:
groups = [m.groups() for m in rx.finditer(string)]
sum = 0
for group in groups:
(lette... | 0 | 2016-08-18T19:29:40Z | [
"python",
"regex"
] |
Swapping in a sorted TreeView | 39,025,554 | <p>Let's say I have following code (the important stuff of a bigger class):</p>
<pre><code> self.store = Gtk.ListStore(int)
for i in range(10):
self.store.append(i)
sw = Gtk.ScrolledWindow()
sw.set_shadow_type(Gtk.ShadowType.IN)
sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATI... | 0 | 2016-08-18T18:52:28Z | 39,039,330 | <p>Something like this:</p>
<pre><code>store.set_sort_column_id (Gtk.TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID,
Gtk.SORT_ASCENDING);
</code></pre>
| 1 | 2016-08-19T12:41:45Z | [
"python",
"sorting",
"treeview",
"gtk",
"pygtk"
] |
Why is python list storing each character in BeautifulSoup tags? | 39,025,597 | <pre><code>from bs4 import BeautifulSoup
from urllib.request import urlopen
def getLinks(pathUrl):
a=[]
html = urlopen(xiny+pathUrl)
soup = BeautifulSoup(html,"html.parser")
nameList = soup.findAll("td",{"class":"name"})
for name in nameList:
aLink = name.find("a").attrs["href"]
pri... | 1 | 2016-08-18T18:55:56Z | 39,025,889 | <p>Use <code>a.append(aLink)</code> to add items to your list. Tested, works for me. I would avoid using <code>+=</code> for concatenating a list, it's a bit hackey :)</p>
| 1 | 2016-08-18T19:14:19Z | [
"python",
"beautifulsoup"
] |
Why is python list storing each character in BeautifulSoup tags? | 39,025,597 | <pre><code>from bs4 import BeautifulSoup
from urllib.request import urlopen
def getLinks(pathUrl):
a=[]
html = urlopen(xiny+pathUrl)
soup = BeautifulSoup(html,"html.parser")
nameList = soup.findAll("td",{"class":"name"})
for name in nameList:
aLink = name.find("a").attrs["href"]
pri... | 1 | 2016-08-18T18:55:56Z | 39,026,034 | <p><code>+=</code> is the same as <code>list.extend</code> which takes an <em>iterable</em> and extends the list with the contents of the iterable, what you want is to <em>append:</em></p>
<pre><code>In [45]: l = []
In [46]: s = "foobar"
In [47]: l.append(s)
In [48]: l
Out[48]: ['foobar']
In [49]: l += s
In [50]... | 3 | 2016-08-18T19:23:11Z | [
"python",
"beautifulsoup"
] |
Python - kill hung process started using subprocess.Popen | 39,025,635 | <p>I've started a subprocess using:</p>
<pre><code>proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
output = proc.communicate()[0]
</code></pre>
<p>Sometimes the command <code>cmd</code> hangs so my Python script also hangs at this point. </p>
<p>I'd like to let this run for a time (10 seconds?) and if I don't g... | 2 | 2016-08-18T18:58:19Z | 39,025,698 | <p>From <a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow">subprocess documentation</a> <code>proc.terminate()</code> is what you 're looking for</p>
| 0 | 2016-08-18T19:01:26Z | [
"python",
"subprocess",
"popen",
"kill",
"hang"
] |
Python - kill hung process started using subprocess.Popen | 39,025,635 | <p>I've started a subprocess using:</p>
<pre><code>proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
output = proc.communicate()[0]
</code></pre>
<p>Sometimes the command <code>cmd</code> hangs so my Python script also hangs at this point. </p>
<p>I'd like to let this run for a time (10 seconds?) and if I don't g... | 2 | 2016-08-18T18:58:19Z | 39,026,168 | <p>If you're using python 3, <code>Popen.communicate</code> has a timeout kwarg:</p>
<pre><code>proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
output = proc.communicate(timeout=10)[0]
</code></pre>
| 2 | 2016-08-18T19:32:29Z | [
"python",
"subprocess",
"popen",
"kill",
"hang"
] |
Tkinter changing image live after a given time | 39,025,637 | <p>I currently have a listbox with the paths of dozens of images, when an element in the listbox is selected the image will be displayed in the middle of the gui.</p>
<p>My third image has 2 different looks to it so i wrote: </p>
<pre><code> #Third image
elif (self.index==3):
start = clock(... | 0 | 2016-08-18T18:58:24Z | 39,025,874 | <p>This is a common pattern. You should use <code>Tk.after</code> to run a function that changes the image then schedules the next change.</p>
<pre><code>def change_image(label, imagelist, nextindex):
label.configure(image=imagelist[nextindex])
root.after(2000, lambda: change_image(label, imagelist, (nextindex... | 2 | 2016-08-18T19:12:49Z | [
"python",
"tkinter"
] |
How to combine two DStreams(pyspark)? | 39,025,640 | <p>I have a kafka stream coming in with some input topic.
This is the code i wrote for accepting kafka stream. </p>
<pre><code>conf = SparkConf().setAppName(appname)
sc = SparkContext(conf=conf)
ssc = StreamingContext(sc)
kvs = KafkaUtils.createDirectStream(ssc, topics,\
{"metadata.broker.list": broke... | 0 | 2016-08-18T18:58:39Z | 39,026,779 | <p>You can just use the <code>join</code> operator on the 2 DStreams to merge them.
When you do map, you are essentially creating another stream. So, join will help you merge them together.</p>
<p>Eg:</p>
<pre><code>Joined_Stream = keys.join(values).(any operation like map, flatmap...)
</code></pre>
| 0 | 2016-08-18T20:16:35Z | [
"python",
"apache-kafka",
"pyspark",
"python-kafka"
] |
Python: Find mean of points within radius of a an element in 2D array | 39,025,644 | <p>I am looking for an efficient way to find the mean of of values with a certain radius of an element in a 2D NumPy array, excluding the center point and values < 0.</p>
<p>My current method is to create a disc shaped mask (using the method <a href="http://stackoverflow.com/questions/8647024/how-to-apply-a-disc-sh... | 1 | 2016-08-18T18:58:47Z | 39,027,626 | <p>is this helpful? This takes only a couple of seconds on my laptop for ~ 18000 points:</p>
<pre><code>import numpy as np
#generate a random 300x300 matrix for testing
inputMat = np.random.random((300,300))
radius=50
def radMask(index,radius,array):
a,b = index
nx,ny = array.shape
y,x = np.ogrid[-a:nx-a,-b:ny... | 1 | 2016-08-18T21:13:40Z | [
"python",
"arrays",
"numpy",
"mean"
] |
Trouble creating pandas dataframe from lists | 39,025,674 | <p>I am having some trouble creating a pandas df from lists I generate while scraping data from the web. Here I am using beautifulsoup to pull a few pieces of information about local farms from localharvest.org (farm name, city, and description). I am able to scrape the data effectively, creating a list of objects on e... | 0 | 2016-08-18T19:00:22Z | 39,026,408 | <p>It works for me:</p>
<pre><code># Taking a few slices of each substring of a given string after stripping off whitespaces
df['fname'] = df['fname'].str.strip().str.slice(start=0, stop=20)
df['fdesc'] = df['fdesc'].str.strip().str.slice(start=0, stop=20)
df.to_csv('farmdata.csv')
df
fcity ... | 1 | 2016-08-18T19:48:05Z | [
"python",
"python-3.x",
"csv",
"pandas",
"dataframe"
] |
Trouble creating pandas dataframe from lists | 39,025,674 | <p>I am having some trouble creating a pandas df from lists I generate while scraping data from the web. Here I am using beautifulsoup to pull a few pieces of information about local farms from localharvest.org (farm name, city, and description). I am able to scrape the data effectively, creating a list of objects on e... | 0 | 2016-08-18T19:00:22Z | 39,026,439 | <p>Consider, instead of using lists of the information for each farm entity that you scrape, to use a list of dictionaries, or a dict of dicts. eg:</p>
<pre><code>[{name:farm1, city: San Jose... etc},
{name: farm2, city: Oakland...etc}]
</code></pre>
<p>Now you can call <code>Pandas.DataFrame.from_dict()</code> on t... | 0 | 2016-08-18T19:50:01Z | [
"python",
"python-3.x",
"csv",
"pandas",
"dataframe"
] |
Trouble creating pandas dataframe from lists | 39,025,674 | <p>I am having some trouble creating a pandas df from lists I generate while scraping data from the web. Here I am using beautifulsoup to pull a few pieces of information about local farms from localharvest.org (farm name, city, and description). I am able to scrape the data effectively, creating a list of objects on e... | 0 | 2016-08-18T19:00:22Z | 39,026,460 | <p>Try stripping out the newline and space characters:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import pandas
url = "http://www.localharvest.org/search.jsp?jmp&lat=44.80798&lon=-69.22736&scale=8&ty=6"
r = requests.get(url)
soup = BeautifulSoup(r.content)
data = soup.find_all("div... | 0 | 2016-08-18T19:51:29Z | [
"python",
"python-3.x",
"csv",
"pandas",
"dataframe"
] |
Does data attributes override method attributes in a class in Python? | 39,025,680 | <p>According to the <a href="https://docs.python.org/3/tutorial/classes.html#random-remarks" rel="nofollow">official documentation</a>, "data attributes override method attributes with the same name". However, I found that to be incorrect.</p>
<pre><code>class C:
x = 111
def x(self):
print('I am x')
c ... | 1 | 2016-08-18T19:00:44Z | 39,025,770 | <p>Attributes override methods and vise-versa. A rule of thumb is, the latter overrides the former. So if you do</p>
<pre><code>class C:
x = 111
def x(self):
print('I am x')
x = 112
c = C()
print(c.x)
</code></pre>
<p>You will get </p>
<pre><code>112
</code></pre>
| 3 | 2016-08-18T19:06:12Z | [
"python"
] |
Does data attributes override method attributes in a class in Python? | 39,025,680 | <p>According to the <a href="https://docs.python.org/3/tutorial/classes.html#random-remarks" rel="nofollow">official documentation</a>, "data attributes override method attributes with the same name". However, I found that to be incorrect.</p>
<pre><code>class C:
x = 111
def x(self):
print('I am x')
c ... | 1 | 2016-08-18T19:00:44Z | 39,025,814 | <p>You were missing the second definition of x, that is why it seemed like the official documentation was wrong.</p>
| -1 | 2016-08-18T19:09:25Z | [
"python"
] |
Does data attributes override method attributes in a class in Python? | 39,025,680 | <p>According to the <a href="https://docs.python.org/3/tutorial/classes.html#random-remarks" rel="nofollow">official documentation</a>, "data attributes override method attributes with the same name". However, I found that to be incorrect.</p>
<pre><code>class C:
x = 111
def x(self):
print('I am x')
c ... | 1 | 2016-08-18T19:00:44Z | 39,026,385 | <p>I guess the tutorial is unfortunately (because ambiguously) phrased and by</p>
<blockquote>
<p>[d]ata attributes override method attributes with the same name</p>
</blockquote>
<p>it actually means "Data attributes override previously assigned/defined method attributes of the same name and vice versa: method att... | 3 | 2016-08-18T19:46:41Z | [
"python"
] |
Django app urls not working properly | 39,025,697 | <p>I have the following base urls file:</p>
<pre><code>urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^agenda/', include('planner.urls', namespace='planner', app_name='planner'))
]
</code></pre>
<p>And my planner app contains the following urls:</p>
<pre><code>urlpatterns = patterns('',
... | 0 | 2016-08-18T19:01:26Z | 39,025,781 | <p>The regex <code>r'^'</code> matches any string. It just says the string needs to have a start. Every string has a start, so...</p>
<p>You need to include an end anchor as well:</p>
<pre><code>url(r'^$', ...)
</code></pre>
<p>This regex looks for the start of the string, followed immediately by the end, i.e. an em... | 3 | 2016-08-18T19:06:48Z | [
"python",
"django",
"url",
"django-urls"
] |
How to convert ArrayType to DenseVector in PySpark DataFrame? | 39,025,707 | <p>I'm getting the following error trying to build a ML <code>Pipeline</code>:</p>
<pre><code>pyspark.sql.utils.IllegalArgumentException: 'requirement failed: Column features must be of type org.apache.spark.ml.linalg.VectorUDT@3bfc3ba7 but was actually ArrayType(DoubleType,true).'
</code></pre>
<p>My <code>features<... | 0 | 2016-08-18T19:02:22Z | 39,026,265 | <p>You can use UDF:</p>
<pre><code>udf(lambda vs: Vectors.dense(vs), VectorUDT())
</code></pre>
<p>In Spark < 2.0 import:</p>
<pre><code>from pyspark.mllib.linalg import Vectors, VectorUDT
</code></pre>
<p>In Spark 2.0+ import:</p>
<pre><code>from pyspark.ml.linalg import Vectors, VectorUDT
</code></pre>
<p>Pl... | 0 | 2016-08-18T19:38:47Z | [
"python",
"apache-spark",
"pyspark",
"apache-spark-mllib",
"apache-spark-ml"
] |
How to split digits and text | 39,025,782 | <p>I have a dataset like this</p>
<pre><code>data = pd.DataFrame({ 'a' : [5, 5, '2 bad']})
</code></pre>
<p>I want to convert this to </p>
<pre><code>{ 'a.digits' : [5, 5, 2], 'a.text' : [nan, nan, 'bad']}
</code></pre>
<p>I can get 'a.digits' as bellow</p>
<pre><code>data['a.digits'] = data['a'].replace('[^0-9]',... | 0 | 2016-08-18T19:06:49Z | 39,026,211 | <p>Something like this would suffice?</p>
<pre><code>In [8]: import numpy as np
In [9]: import re
In [10]: data['a.digits'] = data['a'].apply(lambda x: int(re.sub(r'[\D]', '', str(x))))
In [12]: data['a.text'] = data['a'].apply(lambda x: re.sub(r'[\d]', '', str(x)))
In [13]: data.replace('', np.nan, regex=True)
Ou... | 2 | 2016-08-18T19:35:18Z | [
"python",
"replace"
] |
How to split digits and text | 39,025,782 | <p>I have a dataset like this</p>
<pre><code>data = pd.DataFrame({ 'a' : [5, 5, '2 bad']})
</code></pre>
<p>I want to convert this to </p>
<pre><code>{ 'a.digits' : [5, 5, 2], 'a.text' : [nan, nan, 'bad']}
</code></pre>
<p>I can get 'a.digits' as bellow</p>
<pre><code>data['a.digits'] = data['a'].replace('[^0-9]',... | 0 | 2016-08-18T19:06:49Z | 39,026,225 | <p>Assuming there is a space between 2 and the word bad, you can do this:</p>
<p><code>data['Text'] = data['a'].str.split(' ').str[1]</code></p>
| 0 | 2016-08-18T19:36:04Z | [
"python",
"replace"
] |
extracting values from json file using ijson | 39,025,988 | <p>I have a large JSON file which looks like this :</p>
<pre><code>{"details":{
"1000":[
["10","Thursday","1","19.89"],
["12","Monday","3","20.90"],
...
]
"1001":[
["30","Sunday","11","80.22"],
["88","Wednesday","22","8.29"],
...
]
}
}
</code></pr... | 0 | 2016-08-18T19:20:42Z | 39,036,837 | <p>Ok as it turns out because of <em>large size</em> of <strong>JSON</strong> file which is > <strong>800MB</strong> with about more than a million records the parsing takes time to complete so it </p>
<p>The loop terminates eventually but takes some time to complete. On a pc with normal specs it definitely takes some... | 0 | 2016-08-19T10:33:58Z | [
"python",
"json",
"yajl",
"ijson"
] |
Django: login failed error when trying to connect to Azure database | 39,026,068 | <p>I tried to connect django to Azure database using django-pyodbc-azure and made sure that my settings in setting.py are correct. But still got this problem. I heard that this could be caused by some authentication problem but not sure how to solve this.</p>
<blockquote>
<p>django.db.utils.Error: ('28000', "[28000]... | 0 | 2016-08-18T19:26:10Z | 39,032,497 | <p>@HansongLi, The connection string of Azure SQL Database is in this format <code>Server=<ServerName>,<ServerPort>;Database=<DatabaseName>;UiD=<UserName>;Password={your_password_here};Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;</code>.</p>
<p>Correspondingly, the database ... | 0 | 2016-08-19T06:33:23Z | [
"python",
"django",
"azure"
] |
Adding element to list of dictionaries | 39,026,090 | <p>Normally, I wouldnt post this, but it's been driving me crazy for the past 10 hours...</p>
<p>I have 2 list of dictionaries. But they have either none, 1 or 2 things in common. If while iterating the elements on the second list I match a key-value pair from the first list, then I have to add these elements to the f... | 1 | 2016-08-18T19:27:43Z | 39,026,355 | <p>I think I've got the question right, you want to find the union of the two corresponding dictionaries in 2 lists? The code below should accomplish that. Remember that in case the values of the corresponding keys are different, y(list2 dictionaries) will take precedence over x.</p>
<pre><code>list3 = []
for x,y in z... | 0 | 2016-08-18T19:44:41Z | [
"python",
"list",
"dictionary"
] |
Adding element to list of dictionaries | 39,026,090 | <p>Normally, I wouldnt post this, but it's been driving me crazy for the past 10 hours...</p>
<p>I have 2 list of dictionaries. But they have either none, 1 or 2 things in common. If while iterating the elements on the second list I match a key-value pair from the first list, then I have to add these elements to the f... | 1 | 2016-08-18T19:27:43Z | 39,026,895 | <p>Maybe I got it right and you want to add all values of dictionaries in list2 to first dictionary in list1 which has 'key12' in it? Following code should do.</p>
<pre><code>first_dict = next(d for d in list1 if 'key12' in d)
for d in list2:
first_dict.update(d)
</code></pre>
<p>If you want to add them to first ... | -1 | 2016-08-18T20:24:31Z | [
"python",
"list",
"dictionary"
] |
How can I remove text within multi layer of parentheses python | 39,026,120 | <p>I have a python string that I need to remove parentheses. The standard way is to use <code>text = re.sub(r'\([^)]*\)', '', text)</code>, so the content within the parentheses will be removed.</p>
<p>However, I just found a string that looks like <code>(Data with in (Boo) And good luck)</code>. With the regex I use,... | 0 | 2016-08-18T19:29:35Z | 39,026,523 | <p>First I split the line into tokens that do not contain the parenthesis, for later on joining them into a new line:</p>
<pre><code>line = "(Data with in (Boo) And good luck)"
new_line = "".join(re.split(r'(?:[()])',line))
print ( new_line )
# 'Data with in Boo And good luck'
</code></pre>
| 1 | 2016-08-18T19:55:41Z | [
"python",
"regex",
"text"
] |
How can I remove text within multi layer of parentheses python | 39,026,120 | <p>I have a python string that I need to remove parentheses. The standard way is to use <code>text = re.sub(r'\([^)]*\)', '', text)</code>, so the content within the parentheses will be removed.</p>
<p>However, I just found a string that looks like <code>(Data with in (Boo) And good luck)</code>. With the regex I use,... | 0 | 2016-08-18T19:29:35Z | 39,026,664 | <p>With the re module (replace the innermost parenthesis until there's no more replacement to do):</p>
<pre><code>import re
s = r'Sainte Anne -(Data with in (Boo) And good luck) Charenton'
nb_rep = 1
while (nb_rep):
(s, nb_rep) = re.subn(r'\([^()]*\)', '', s)
print(s)
</code></pre>
<p>With the <a href="https:... | 2 | 2016-08-18T20:06:56Z | [
"python",
"regex",
"text"
] |
How can I remove text within multi layer of parentheses python | 39,026,120 | <p>I have a python string that I need to remove parentheses. The standard way is to use <code>text = re.sub(r'\([^)]*\)', '', text)</code>, so the content within the parentheses will be removed.</p>
<p>However, I just found a string that looks like <code>(Data with in (Boo) And good luck)</code>. With the regex I use,... | 0 | 2016-08-18T19:29:35Z | 39,027,283 | <p>No regex...</p>
<pre><code>>>> a = 'Hi this is a test ( a b ( c d) e) sentence'
>>> o = ['(' == t or t == ')' for t in a]
>>> o
[False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, True, False, False,
False, Fals... | 1 | 2016-08-18T20:51:51Z | [
"python",
"regex",
"text"
] |
How can I remove text within multi layer of parentheses python | 39,026,120 | <p>I have a python string that I need to remove parentheses. The standard way is to use <code>text = re.sub(r'\([^)]*\)', '', text)</code>, so the content within the parentheses will be removed.</p>
<p>However, I just found a string that looks like <code>(Data with in (Boo) And good luck)</code>. With the regex I use,... | 0 | 2016-08-18T19:29:35Z | 39,032,992 | <p>Assuming (1) there are always matching parentheses and (2) we only remove the parentheses and everything in between them (ie. surrounding spaces around the parentheses are untouched), the following should work.</p>
<p>It's basically a state machine that maintains the current depth of nested parentheses. We keep the... | 1 | 2016-08-19T07:05:20Z | [
"python",
"regex",
"text"
] |
pandas find count between dates for list of month ends | 39,026,131 | <p>I have a list of customers with a "start date" and and "end date". For any given time period, my goal is to find how many customers I have active. A customer is active if their start date is before x and their end date is after x. I've written a brute force version of this:</p>
<pre><code>from datetime import datet... | 0 | 2016-08-18T19:30:06Z | 39,026,474 | <p>One way would be:</p>
<pre><code>In [142]: tf = pd.DataFrame({'dates': dates})
In [143]: tf['active_count'] = tf['dates'].apply(lambda x: df[(df['startDate']<= x) & (df['endDate']>= x)].count())
In [144]: tf
Out[144]:
dates active_count
0 2016-01-31 1
1 2016-02-29 3
2 2016... | 1 | 2016-08-18T19:52:19Z | [
"python",
"pandas"
] |
Numpy multiplying different shapes | 39,026,173 | <p>have two arrays that are like this</p>
<pre><code>x = [a,b]
y = [p,q,r]
</code></pre>
<p>I need to multiply this together to a product <code>c</code> which should be like this,</p>
<pre><code>c = [a*p, a*q, a*r, b*p, b*q, b*r]
</code></pre>
<p>However <code>x*y</code> gives the following error,</p>
<pre><code>V... | 0 | 2016-08-18T19:32:53Z | 39,026,226 | <p>You can use <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a> for pairwise elementwise multiplication between <code>x</code> and <code>y</code> and then flatten with <code>.ravel()</code>, like so -</p>
<pre><code>(x[:,None]*y).ravel()
</code>... | 4 | 2016-08-18T19:36:05Z | [
"python",
"numpy"
] |
Numpy multiplying different shapes | 39,026,173 | <p>have two arrays that are like this</p>
<pre><code>x = [a,b]
y = [p,q,r]
</code></pre>
<p>I need to multiply this together to a product <code>c</code> which should be like this,</p>
<pre><code>c = [a*p, a*q, a*r, b*p, b*q, b*r]
</code></pre>
<p>However <code>x*y</code> gives the following error,</p>
<pre><code>V... | 0 | 2016-08-18T19:32:53Z | 39,026,864 | <p>Use Numpy dot...</p>
<pre><code>>>> import numpy as np
>>> a=np.arange(1,3)# [1,2]
>>> b=np.arange(1,4)# [1,2,3]
>>> np.dot(a[:,None],b[None])
array([[1, 2, 3],
[2, 4, 6]])
>>> np.dot(a[:,None],b[None]).ravel()
array([1, 2, 3, 2, 4, 6])
>>>
</code></pre>
| 0 | 2016-08-18T20:23:04Z | [
"python",
"numpy"
] |
Get the first and last times for each day with Python datetime | 39,026,297 | <p>I have a list of timestamps in this format: '2016-08-01 13:02:57' or "%Y-%m-%d-%H-%M-%S-%f"</p>
<p>I would like to get the first and last time for each day. So for if there were two days 8/1 and 7/29 the function would return 4 values. For example:</p>
<pre><code>8/1
first: '2016-08-01 13:02:57'
last: '2016-08-01 ... | 2 | 2016-08-18T19:40:46Z | 39,026,419 | <p>To sensibly group your data I would probably use a dictionary in the following fashion by first splitting your string into the date half and time half.</p>
<pre><code>d = dict()
for item in L:
if item in d:
d[item] = [time]
else:
d[item].append(time)
</code></pre>
<p>Then you have dict mapp... | -1 | 2016-08-18T19:48:40Z | [
"python",
"datetime"
] |
Get the first and last times for each day with Python datetime | 39,026,297 | <p>I have a list of timestamps in this format: '2016-08-01 13:02:57' or "%Y-%m-%d-%H-%M-%S-%f"</p>
<p>I would like to get the first and last time for each day. So for if there were two days 8/1 and 7/29 the function would return 4 values. For example:</p>
<pre><code>8/1
first: '2016-08-01 13:02:57'
last: '2016-08-01 ... | 2 | 2016-08-18T19:40:46Z | 39,026,515 | <p>Group by year-month-day then get the min and max:</p>
<pre><code>from collections import defaultdict
d = defaultdict(list)
dates = ['2016-08-01 13:02:54',............]
for dte in dates:
key, _ = dte.split()
d[key].append(dte)
for k,v in d.items():
print(min(v), max(v))
</code></pre>
<p>Because of the ... | 1 | 2016-08-18T19:54:56Z | [
"python",
"datetime"
] |
Get the first and last times for each day with Python datetime | 39,026,297 | <p>I have a list of timestamps in this format: '2016-08-01 13:02:57' or "%Y-%m-%d-%H-%M-%S-%f"</p>
<p>I would like to get the first and last time for each day. So for if there were two days 8/1 and 7/29 the function would return 4 values. For example:</p>
<pre><code>8/1
first: '2016-08-01 13:02:57'
last: '2016-08-01 ... | 2 | 2016-08-18T19:40:46Z | 39,026,552 | <p>A lexical compare is with your datetime format gives min and max dates. So you simply have to group all datetimes with the same date in one list each:</p>
<pre><code>from collections import defaultdict
dates = ['2016-08-01 13:02:57', '2016-08-01 13:08:44', ...]
dates_and_times = defaultdict(list)
for date in dates:... | 1 | 2016-08-18T19:58:03Z | [
"python",
"datetime"
] |
How to merge rows in the array Python3, csv | 39,026,322 | <p>sample data:</p>
<pre>
id, Name, mail, data1, data2, data3
1, Name1, mail@com, abc, 14, de
1, Name1, mail@com, fgh, 25, kl
1, Name1, mail@com, mno, 38, pq
2, Name2, mail@com, abc, 14, d
</pre>
<p>I wrote a script that selects the first field is a unique string to clear the duplicates. However, since the data i... | 0 | 2016-08-18T19:42:14Z | 39,028,000 | <p>This should do the trick.</p>
<pre><code>from collections import defaultdict
import pandas as pd
# recreate your example
df = pd.DataFrame([[1, 'Name1', 'mail@com', 'abc', 14, 'de'],
[1, 'Name1', 'mail@com', 'fgh', 25, 'kl'],
[1, 'Name1', 'mail@com', 'mno', 38, 'pq'],
... | 0 | 2016-08-18T21:47:13Z | [
"python",
"arrays",
"csv"
] |
How to merge rows in the array Python3, csv | 39,026,322 | <p>sample data:</p>
<pre>
id, Name, mail, data1, data2, data3
1, Name1, mail@com, abc, 14, de
1, Name1, mail@com, fgh, 25, kl
1, Name1, mail@com, mno, 38, pq
2, Name2, mail@com, abc, 14, d
</pre>
<p>I wrote a script that selects the first field is a unique string to clear the duplicates. However, since the data i... | 0 | 2016-08-18T19:42:14Z | 39,028,833 | <p>My own version is very close to the beter:</p>
<p>Now all work!</p>
<pre><code>#!/usr/bin/env python3
import csv, re
import os, sys
in_fln = sys.argv[1]
# You can replace here and choose any delimiter:
#csv.register_dialect('dlm', delimiter=',')
dm = ','
seen = []
# if this .csv file do:
if (in_fln[-3:]) == "csv":... | 0 | 2016-08-18T23:09:53Z | [
"python",
"arrays",
"csv"
] |
Setting variables in a function (subfunction) from a file with a variable filename | 39,026,413 | <p>I have a function that has a subfunction and I would like to initialize variables inside of the subfunction. Simply,</p>
<pre><code>file = "foo"
def outerFunction():
def innerFunction():
var1 = 0
var2 = 1
var3 = 2
print file, var1, var2, var3
file = "bar"
innerFunction()
... | 1 | 2016-08-18T19:48:18Z | 39,027,992 | <p>From a maintainability perspective, importing the module and then referencing the variables of the module is the best option. It's easy to see where the variables have come from. </p>
<p><code>from module import *</code> is frowned upon because it makes it hard to trace where variables have come from, especially if... | 0 | 2016-08-18T21:46:38Z | [
"python",
"python-2.7",
"import",
"python-import"
] |
Python Eclipse Code Analysis ignore doesn't seem to work | 39,026,418 | <p>I use Eclipse with PyDev. I have some tweaks that need to be made to Pep8. I have monkeyed around with this and thought I made some progress, but I really don't know how this works. </p>
<p>Current problem is that I would like to get PyDev warnings to stop coming up when I don't match pep8 indents. I use 2 spac... | 1 | 2016-08-18T19:48:39Z | 39,032,174 | <p>I have configured pep8 using a <strong>setup.cfg</strong> file in my projects. It resides in parallel to the src folder and contains this:</p>
<pre><code>[pep8]
max-line-length=100
# pep8 1.6.2 wants all includes at the top:
ignore=E402
</code></pre>
<p>This way, I get the intended results even if I use pep8 on th... | 0 | 2016-08-19T06:10:30Z | [
"python",
"eclipse",
"pydev"
] |
Creating combination of value list with existing key - Pyspark | 39,026,480 | <p>So my rdd consists of data looking like: </p>
<pre><code>(k, [v1,v2,v3...])
</code></pre>
<p>I want to create a combination of all sets of two for the value part.</p>
<p>So the end map should look like:</p>
<pre><code>(k1, (v1,v2))
(k1, (v1,v3))
(k1, (v2,v3))
</code></pre>
<p>I know to get the value part, I wou... | 1 | 2016-08-18T19:52:45Z | 39,026,852 | <p>Use <code>itertools</code> to create the combinations. Here is a demo:</p>
<pre><code>import itertools
k, v1, v2, v3 = 'k1 v1 v2 v3'.split()
a = (k, [v1,v2,v3])
b = itertools.combinations(a[1], 2)
data = [(k, pair) for pair in b]
</code></pre>
<p><code>data</code> will be:</p>
<pre><code>[('k1', ('v1', 'v2')),... | 1 | 2016-08-18T20:22:13Z | [
"python",
"apache-spark",
"mapreduce",
"pyspark"
] |
Creating combination of value list with existing key - Pyspark | 39,026,480 | <p>So my rdd consists of data looking like: </p>
<pre><code>(k, [v1,v2,v3...])
</code></pre>
<p>I want to create a combination of all sets of two for the value part.</p>
<p>So the end map should look like:</p>
<pre><code>(k1, (v1,v2))
(k1, (v1,v3))
(k1, (v2,v3))
</code></pre>
<p>I know to get the value part, I wou... | 1 | 2016-08-18T19:52:45Z | 39,028,398 | <p>I think Israel's answer is a incomplete, so I go a step further. </p>
<pre><code>import itertools
a = sc.parallelize([
(1, [1,2,3,4]),
(2, [3,4,5,6]),
(3, [-1,2,3,4])
])
def combinations(row):
l = row[1]
k = row[0]
return [(k, v) for v in itertools.combinations(l, 2)]
a.map(combinations).flat... | 1 | 2016-08-18T22:22:32Z | [
"python",
"apache-spark",
"mapreduce",
"pyspark"
] |
What does this strange format string "{[[[]}" do? | 39,026,630 | <p>I come across the below in some code from an ex employee. </p>
<p>the code is not called, from anywhere, but my question is can it actually do something useful as it is?</p>
<pre><code>def xshow(x):
print("{[[[[]}".format(x))
</code></pre>
| 5 | 2016-08-18T20:04:20Z | 39,026,662 | <p>That is a format string with an empty argument name and an element index (the part between <code>[</code> and <code>]</code> for a key <code>[[[</code> (those indices don't have to be integers). It will print the value for that key.</p>
<p>Calling:</p>
<pre><code>xshow({'[[[': 1})
</code></pre>
<p>will print <cod... | 4 | 2016-08-18T20:06:49Z | [
"python",
"string-formatting"
] |
What does this strange format string "{[[[]}" do? | 39,026,630 | <p>I come across the below in some code from an ex employee. </p>
<p>the code is not called, from anywhere, but my question is can it actually do something useful as it is?</p>
<pre><code>def xshow(x):
print("{[[[[]}".format(x))
</code></pre>
| 5 | 2016-08-18T20:04:20Z | 39,058,456 | <p>One can use the interactive interpreter to investigate something like this experimentally.</p>
<pre><code>>>> xshow(None)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
xshow(None)
File "<pyshell#11>", line 1, in xshow
def xshow(x): print("{[[[[]}"... | 0 | 2016-08-20T20:30:24Z | [
"python",
"string-formatting"
] |
How do you add a custom column to a query in sqlalchemy if you are using the classical mapping? | 39,026,819 | <p>Some caveats:</p>
<ol>
<li>Our models are generated from yaml file, and we don't have a way to add a computed property via the yaml file at this time (we will eventually)</li>
<li>Given the above, we don't have models to add hybrid properties to.</li>
</ol>
<p>What is the proper way to add a computed column to a q... | 0 | 2016-08-18T20:19:31Z | 39,028,095 | <p>@univerio got me very close!</p>
<p>I had to set it as a column property, and then all was well.</p>
<pre><code>class Listing(db.model):
custom_function = column_property(func.custom_function(id))
</code></pre>
| 0 | 2016-08-18T21:54:27Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy"
] |
Tkinter window is blank when running | 39,026,823 | <p>When I run my tkinter code for measuring the temperature with Adafruit. When I run my code tkinter opens a window but nothing appears on the window. I have used tkinter a bit before and I have had what is supposed to appear appear but just not in this particular code.</p>
<pre><code>#!/usr/bin/python
# -*- coding: ... | 4 | 2016-08-18T20:19:40Z | 39,027,044 | <p>it is because you are not packing it in the window but you are printing it in the python shell.</p>
<p>you should replace that <code>print newtext</code> with:</p>
<pre><code>w = Label(root, text=newtext)
w.pack()
</code></pre>
<p>a working code should look like this:</p>
<pre><code>#!/usr/bin/python
# -*- codi... | 4 | 2016-08-18T20:34:46Z | [
"python",
"tkinter",
"raspberry-pi",
"adafruit"
] |
How to use Graphene GraphQL framework with Django REST Framework authentication | 39,026,831 | <p>I got some REST API endpoints in Django and I'd like to use <a href="http://www.django-rest-framework.org/api-guide/authentication/" rel="nofollow">the same authentication</a> for Graphene. The <a href="http://graphene-python.org/docs/django/tutorial/" rel="nofollow">documentation</a> does not provide any guidance.<... | 2 | 2016-08-18T20:19:56Z | 39,026,832 | <p>For example, if you are using <code>authentication_classes = (TokenAuthentication,)</code> in your API views, you should add an endpoint to a GraphQLView decorated in this way:</p>
<p><strong>urls.py:</strong></p>
<pre><code># ...
from rest_framework.authentication import TokenAuthentication
from rest_framework.pe... | 1 | 2016-08-18T20:19:56Z | [
"python",
"django",
"rest",
"authentication",
"graphql"
] |
How to configure Django to access remote MySQL db django.contrib.sites.RequestSite module missing | 39,026,950 | <p>I'm trying to set up a django app that connects to a remote MySQL db. I currently have Django==1.10 and MySQL-python==1.2.5 installed in my venv. In settings.py I have added the following to the DATABASES variable:</p>
<pre><code>'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db_name',
'USE... | 0 | 2016-08-18T20:28:18Z | 39,027,272 | <p>This is documentation you should look at this for connecting to databases and how django does it, from what you gave us, as long as your parameters are correct you should be connecting to the database but a good confirmation of this would be the inspectdb tool.</p>
<p><a href="https://docs.djangoproject.com/en/1.10... | 0 | 2016-08-18T20:51:07Z | [
"python",
"mysql",
"django"
] |
How to configure Django to access remote MySQL db django.contrib.sites.RequestSite module missing | 39,026,950 | <p>I'm trying to set up a django app that connects to a remote MySQL db. I currently have Django==1.10 and MySQL-python==1.2.5 installed in my venv. In settings.py I have added the following to the DATABASES variable:</p>
<pre><code>'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db_name',
'USE... | 0 | 2016-08-18T20:28:18Z | 39,027,295 | <p>The error you're seeing has nothing to do with your database settings (assuming your real code has the actual database name, username, and password) or connection. You are not importing the RequestSite from the correct spot.</p>
<p>Change (wherever you have this set) from:</p>
<pre><code>from django.contrib.sites.... | 1 | 2016-08-18T20:52:25Z | [
"python",
"mysql",
"django"
] |
How can I scale a pyplot colorbar so that contrast is seen in my scatter points? | 39,026,969 | <p>I'm making a scatter plot with <code>x</code> and <code>y</code> values, and a <code>z</code> array that I'm using to define point color as so:</p>
<p><code>plt.scatter(x, y, c = z)</code></p>
<p>However, <code>max(z) ~ 110</code>, but <code>mean(z) ~ 20</code>. So since most <code>z</code> values are around or be... | 2 | 2016-08-18T20:29:31Z | 39,027,202 | <p>Try this:</p>
<pre><code>plt.scatter(x, y, c = z, vmin=10, vmax=40)
</code></pre>
| 1 | 2016-08-18T20:46:03Z | [
"python",
"matplotlib",
"colorbar"
] |
How can I scale a pyplot colorbar so that contrast is seen in my scatter points? | 39,026,969 | <p>I'm making a scatter plot with <code>x</code> and <code>y</code> values, and a <code>z</code> array that I'm using to define point color as so:</p>
<p><code>plt.scatter(x, y, c = z)</code></p>
<p>However, <code>max(z) ~ 110</code>, but <code>mean(z) ~ 20</code>. So since most <code>z</code> values are around or be... | 2 | 2016-08-18T20:29:31Z | 39,027,348 | <p>You can use the <code>extend</code> argument on the matplotlib colorbar as</p>
<pre><code>plt.scatter(x, y, c = z, vmin=10, vmax=40)
plt.colorbar(extend="max")
</code></pre>
<p>For detailed examples, check <a href="http://matplotlib.org/examples/pylab_examples/contourf_demo.html" rel="nofollow">this link</a> out.<... | 1 | 2016-08-18T20:54:58Z | [
"python",
"matplotlib",
"colorbar"
] |
how to define a set of variables so the program responds in any of the items in a list is called, python3 | 39,027,038 | <p>I create a list so if someones inputs any item from the list it will print the same. </p>
<pre><code>lista = ["example", "example2"]
listb = ["exampleb", "example2b"]
choice = input()
if choice == lista[]:
print("outputa")
elif choice == listb[]:
print("outputb")
</code></pre>
<p>if the user types either e... | 1 | 2016-08-18T20:34:17Z | 39,027,085 | <p>Use:</p>
<pre><code>if choice in lista:
print("a")
elif choice in listb:
print("b")
</code></pre>
<p>`</p>
| 2 | 2016-08-18T20:36:55Z | [
"python",
"list",
"if-statement",
"input",
"set"
] |
how to define a set of variables so the program responds in any of the items in a list is called, python3 | 39,027,038 | <p>I create a list so if someones inputs any item from the list it will print the same. </p>
<pre><code>lista = ["example", "example2"]
listb = ["exampleb", "example2b"]
choice = input()
if choice == lista[]:
print("outputa")
elif choice == listb[]:
print("outputb")
</code></pre>
<p>if the user types either e... | 1 | 2016-08-18T20:34:17Z | 39,027,088 | <pre><code>lista = ["example", "example2"]
listb = ["exampleb", "example2b"]
choice = input()
if choice in lista:
print("outputa")
elif choice in listb:
print("outputb")
</code></pre>
| 4 | 2016-08-18T20:37:15Z | [
"python",
"list",
"if-statement",
"input",
"set"
] |
how to define a set of variables so the program responds in any of the items in a list is called, python3 | 39,027,038 | <p>I create a list so if someones inputs any item from the list it will print the same. </p>
<pre><code>lista = ["example", "example2"]
listb = ["exampleb", "example2b"]
choice = input()
if choice == lista[]:
print("outputa")
elif choice == listb[]:
print("outputb")
</code></pre>
<p>if the user types either e... | 1 | 2016-08-18T20:34:17Z | 39,027,149 | <p>Have you tried using the <code>in</code> operator <a href="https://docs.python.org/3/reference/datamodel.html#object.__contains__" rel="nofollow">in</a> Python? Such that you'd write:</p>
<pre><code>if choice in list_a:
print("Output A")
elif choice in list_b:
print("Output B")
</code></pre>
| 1 | 2016-08-18T20:42:25Z | [
"python",
"list",
"if-statement",
"input",
"set"
] |
pandas - Replace one letter in a string with its capital | 39,027,072 | <p>I have a columns with some names that need capitalizing in the middle of the word, like Mcgill to McGill, Mcneill to McNeill, O'donnell to O'Donnell, etc.</p>
<p>I know some text editors can do this by prepending the captured group with <code>\U</code> but this doesn't work in pandas.</p>
<p>Here's what I tried. I... | 3 | 2016-08-18T20:36:09Z | 39,027,310 | <p>You can use <code>apply()</code> in combination with <code>re.sub()</code>:</p>
<pre><code>import pandas as pd, re
names = pd.Series(["Mcgill", "Mcneill", "O'donnell", "Mctavish"])
def capitalize(name):
rx = re.compile(r'(?:(?<=Mc)|(?<=O\'))([a-z])')
def repl(m):
char = m.group(1)
re... | 3 | 2016-08-18T20:53:20Z | [
"python",
"regex",
"pandas"
] |
How can I optimize this python code - NO MEMORY? | 39,027,080 | <p>I wrote this python code:</p>
<pre><code>from itertools import product
combo_pack = product("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890!&+*-_.#@", repeat = 8)
myfile = open("lista_combinazioni.txt","w")
for combo in combo_pack:
combo = "".join(combo)
combo = "%s\n" % (combo)
myfile... | -2 | 2016-08-18T20:36:40Z | 39,027,141 | <p>What's probably happening is your file buffer is filling up and it isn't flushing to the file, thus using a lot of memory.</p>
<p>Try using this instead:</p>
<pre><code>myfile = open("lista_combinazioni.txt","w",1)
</code></pre>
| -3 | 2016-08-18T20:41:42Z | [
"python",
"optimization"
] |
Problems installing Python Pymqi package | 39,027,100 | <p>THis is my first post on this forum. If I am not complying with protocols, please just let me know.</p>
<pre><code>C:\>python --version
Python 2.7.11
</code></pre>
<p>OS: Windows version 7</p>
<p>WMQ: 8.2</p>
<p>I am trying to install Python <strong>pymqi</strong> package. After couple hours of trying and sea... | -1 | 2016-08-18T20:38:23Z | 39,027,176 | <p>You need to install <a href="https://www.microsoft.com/en-us/download/details.aspx?id=44266" rel="nofollow">Microsoft Visual C++ compiler for Python 2.7</a></p>
| 1 | 2016-08-18T20:44:40Z | [
"python",
"windows"
] |
Appending miniature lists to a larger list | 39,027,187 | <p>I'm creating a python application to play the game Perudo (or Liar's dice).</p>
<p>I am trying to create a function that calculates all the possible moves that the player (or AI) is allowed to make and returns a list of them so that it can reject illegal ones.</p>
<p>Turns are stored as a list of 2 numbers e.g. [1... | 3 | 2016-08-18T20:45:07Z | 39,027,358 | <p>you're appending the same object in your list which explains you get 6 times the last value.</p>
<p>replace</p>
<pre><code>self.possiblemoves.append(self.bid) # <- I think the problem is something to do with this line
</code></pre>
<p>by</p>
<pre><code>self.possiblemoves.append(list(self.bid)) # make a co... | 0 | 2016-08-18T20:55:40Z | [
"python",
"list"
] |
Appending miniature lists to a larger list | 39,027,187 | <p>I'm creating a python application to play the game Perudo (or Liar's dice).</p>
<p>I am trying to create a function that calculates all the possible moves that the player (or AI) is allowed to make and returns a list of them so that it can reject illegal ones.</p>
<p>Turns are stored as a list of 2 numbers e.g. [1... | 3 | 2016-08-18T20:45:07Z | 39,027,426 | <p>You're better off in thinking about a base 6 number here where you effectively have a range of numbers for 20 dice of 0 - 126 inclusive.</p>
<pre><code>current_bid = [19, 3]
offset = current_bid[0] * 6 + current_bid[1]
# 117 - and divmod(117, 6) == (19, 3)
</code></pre>
<p>So, to then get the valid bids that are l... | 0 | 2016-08-18T20:59:58Z | [
"python",
"list"
] |
Appending miniature lists to a larger list | 39,027,187 | <p>I'm creating a python application to play the game Perudo (or Liar's dice).</p>
<p>I am trying to create a function that calculates all the possible moves that the player (or AI) is allowed to make and returns a list of them so that it can reject illegal ones.</p>
<p>Turns are stored as a list of 2 numbers e.g. [1... | 3 | 2016-08-18T20:45:07Z | 39,027,452 | <p>The problem is that you are using <code>list</code>s, which are mutable objects, and you're creating references, rather than copies. You could fix it by copying the <code>self.bid</code> list each time, but the most "pythonic" solution is not to use <code>list</code>, but to use <code>tuple</code>s, instead:</p>
<... | 1 | 2016-08-18T21:01:42Z | [
"python",
"list"
] |
Appending miniature lists to a larger list | 39,027,187 | <p>I'm creating a python application to play the game Perudo (or Liar's dice).</p>
<p>I am trying to create a function that calculates all the possible moves that the player (or AI) is allowed to make and returns a list of them so that it can reject illegal ones.</p>
<p>Turns are stored as a list of 2 numbers e.g. [1... | 3 | 2016-08-18T20:45:07Z | 39,027,480 | <p>The problem is the reference to self.bid. It's the same variable over and over again in the list meaning when you update it in your loop, you are updating every instance (all the variables in the list in this case). I've rewritten what you are trying to do to work the way you want in case you want to keep this sam... | 0 | 2016-08-18T21:03:42Z | [
"python",
"list"
] |
Django Nose - Need to capture output while running tests | 39,027,258 | <p>I am running running django-nose tests in a management command using <code>call_command</code>. I need to capture output and do something with it, depending on if it failed or passed.
My current code in management command :</p>
<pre><code>content = StringIO()
try:
call_command('test', '--nologcapture', '-s', st... | 1 | 2016-08-18T20:50:17Z | 39,027,300 | <p>The likely cause of your problem is that inside the management code, they are using print statements which are going directly to <code>sys.stdout</code>, rather than using the <code>self.stdout</code> attribute of the management command instance. </p>
<p>Check the code inside the management command. The prints sh... | 0 | 2016-08-18T20:52:45Z | [
"python",
"django",
"django-nose"
] |
SQLite: how to search multiple columns without returning duplicate rows? | 39,027,277 | <p>trying to solve this with my limited knowledge of SQL and I'm stuck. :)</p>
<p>This is being done in <strong>SQLite 3</strong> and <strong>Python 3</strong>.</p>
<p>I've 'JOIN'ed 2 tables (<strong>names</strong> and <strong>data</strong>). </p>
<p>I'm trying to search 2 columns in the result for user supplied tex... | 0 | 2016-08-18T20:51:38Z | 39,027,724 | <p>Alright so I'm assuming you simply want the first record for each unique value in the <code>name_id</code> column. If that is the case then your query should look like this.</p>
<pre><code>SELECT
*
FROM
names n
JOIN data d ON d.name_id = n.name_id
WHERE
LCASE(n.name) LIKE '%john%' // Force lower so only 1 W... | 1 | 2016-08-18T21:23:31Z | [
"python",
"sqlite",
"python-3.x",
"search",
"sqlite3"
] |
SQLite: how to search multiple columns without returning duplicate rows? | 39,027,277 | <p>trying to solve this with my limited knowledge of SQL and I'm stuck. :)</p>
<p>This is being done in <strong>SQLite 3</strong> and <strong>Python 3</strong>.</p>
<p>I've 'JOIN'ed 2 tables (<strong>names</strong> and <strong>data</strong>). </p>
<p>I'm trying to search 2 columns in the result for user supplied tex... | 0 | 2016-08-18T20:51:38Z | 39,028,096 | <p>With the same assumptions as the previous answer (i.e. you're looking for the first record for the unique name), I'd suggest the following:</p>
<pre><code>select names.name_id
, <names_fields>
, group_concat(data,';')
from names
join (select name_id, data from data_table... | 0 | 2016-08-18T21:54:35Z | [
"python",
"sqlite",
"python-3.x",
"search",
"sqlite3"
] |
Iterating through rows to see which value comes first | 39,027,281 | <p>When working with Pandas I am able to check prior and following rows to see if certain conditions are met using .shift(). </p>
<p>What if I need to see if a condition is met which could be 100 rows or more after the row I am comparing with? I know looping through a dataframe is not the most efficient but can some... | 4 | 2016-08-18T20:51:49Z | 39,027,699 | <p>Make it nicer and cleaner, thought... </p>
<pre><code>import datetime,numpy as np,pandas as pd
nan = np.nan
a = pd.DataFrame({'move_start': {datetime.time(9, 0): nan, datetime.time(10, 0): nan, datetime.time(11, 0): nan, datetime.time(12, 0): nan, datetime.time(13, 0): nan, datetime.time(14, 0): datetime... | 1 | 2016-08-18T21:21:02Z | [
"python",
"pandas"
] |
Python script error with numbers 01 | 39,027,299 | <p>I have the following script and there seems to be an error:</p>
<pre><code>import random, time
from random import randint
while True:
part_1 = randint(1,31)
part_2 = randint(1,12)
part_3 = random.choice([81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,00,01,02,03,04])
if part_3 == 01 or p... | 0 | 2016-08-18T20:52:35Z | 39,027,417 | <p>Change your declaration of <code>full</code> to: </p>
<pre><code>full = "%02d %02d %02d" % (part_1, part_2, part_3)
</code></pre>
<p>You can read more about format strings <a href="https://docs.python.org/2/library/string.html#format-specification-mini-language" rel="nofollow">here</a>.</p>
| 2 | 2016-08-18T20:59:34Z | [
"python"
] |
Python script error with numbers 01 | 39,027,299 | <p>I have the following script and there seems to be an error:</p>
<pre><code>import random, time
from random import randint
while True:
part_1 = randint(1,31)
part_2 = randint(1,12)
part_3 = random.choice([81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,00,01,02,03,04])
if part_3 == 01 or p... | 0 | 2016-08-18T20:52:35Z | 39,027,679 | <p>Alternative answer using <a href="https://pyformat.info/" rel="nofollow"><code>str.format</code></a></p>
<pre><code>part_1 = randint(1,31)
part_2 = randint(1,12)
part_3 = random.choice([81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,00,01,02,03,04])
full = ('{:02d} '*3).format(part_1, part_2, part_3).rst... | 0 | 2016-08-18T21:18:52Z | [
"python"
] |
ValueError: The input contains nan values - from lmfit model despite the input not containing NaNs | 39,027,346 | <p>I'm trying to build a model using lmfit <a href="https://lmfit.github.io/lmfit-py/model.html#the-model-class" rel="nofollow">(link to docs)</a> and I can't seems to find out why I keep getting a <code>ValueError: The input contains nan values</code> when I try to fit the model.</p>
<pre><code>from lmfit import mini... | 1 | 2016-08-18T20:54:49Z | 39,043,951 | <p>I tried to fit my model using <code>scipy.optimize.curve_fit</code> and got the following error:</p>
<pre><code>/home/bprodz/.virtualenvs/phd_dev/lib/python3.4/site-packages/ipykernel/__main__.py:3: RuntimeWarning: invalid value encountered in sqrt
app.launch_new_instance()
</code></pre>
<p>Which suggests the pr... | 1 | 2016-08-19T16:37:33Z | [
"python",
"lmfit"
] |
Why there is a difference between 32 bit and 64 bit numpy/pandas | 39,027,484 | <p>I'm using numpy/pandas on a 64-bit fedora box, in production they pushed to a 32-bit Centos box and hit an error with <code>json.dumps</code>. It was throwing <code>repr(0) is not Serializable</code>. </p>
<p>I tried testing on 64-bit Centos and it runs absolutely fine. But on 32-bit (Centos 6.8 to be precise) it t... | 0 | 2016-08-18T21:04:03Z | 39,027,831 | <p>I believe this happens because the index is a <code>numpy.intNN</code> of different size as the Python <code>int</code> and these are not natively converted from one to another.</p>
<p>Like, on my 64-bit Python 2.7 and Numpy:</p>
<pre><code>>>> isinstance(numpy.int64(5), int)
True
>>> isinstance(... | 3 | 2016-08-18T21:32:00Z | [
"python",
"json",
"pandas",
"numpy",
"32bit-64bit"
] |
Distributed tensorflow replicated training example: grpc_tensorflow_server - No such file or directory | 39,027,488 | <p>I am trying to make a <code>distributed tensorflow</code> implementation by following the instructions in this blog: <a href="http://leotam.github.io/general/2016/03/13/DistributedTF.html" rel="nofollow">Distributed TensorFlow by Leo K. Tam</a>. My aim is to perform <code>replicated training</code> as mentioned in t... | 1 | 2016-08-18T21:04:13Z | 39,027,701 | <p>The <code>grpc_tensorflow_server</code> binary was a temporary measure used in the pre-released version of Distributed TensorFlow, and it is no longer built by default or included in the binary distributions. Its replacement is the <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html#Server"... | 1 | 2016-08-18T21:21:07Z | [
"python",
"tensorflow",
"gpu",
"distributed-computing",
"grpc"
] |
Convert data from an excel file into a python dictionary | 39,027,559 | <p>I'm trying to convert data from an excel file to a python dictionary. My excel file has has two columns and many rows. </p>
<pre><code>Name Age
Steve 11
Mike 10
John 11
</code></pre>
<p>How do I go about adding this into a dictionary with Age as the key and name as the value? Also, if many names have th... | 0 | 2016-08-18T21:09:24Z | 39,027,584 | <p>Just a simple indentation error and your code is incorrect</p>
<pre><code>#Problem seems to be in this general area
if not age in age_and_names:
age_and_names[age]=[]
age_and_names[age].append(name)
</code></pre>
<p>should be</p>
<pre><code>#Problem seems to be in this general area
if ... | 1 | 2016-08-18T21:11:03Z | [
"python",
"excel",
"dictionary"
] |
Convert data from an excel file into a python dictionary | 39,027,559 | <p>I'm trying to convert data from an excel file to a python dictionary. My excel file has has two columns and many rows. </p>
<pre><code>Name Age
Steve 11
Mike 10
John 11
</code></pre>
<p>How do I go about adding this into a dictionary with Age as the key and name as the value? Also, if many names have th... | 0 | 2016-08-18T21:09:24Z | 39,027,624 | <p>For this case, use <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>collections.defaultdict</code></a> instead of a plain dictionary <code>{}</code>); <code>collections.defaultdict</code> takes a factory function that is used to construct values for new keys. ... | 1 | 2016-08-18T21:13:35Z | [
"python",
"excel",
"dictionary"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.