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 |
|---|---|---|---|---|---|---|
3,500 | 68,051,008 | How to convert a date to a hours and minute in a variable in python 3? | <p>I have a dataset with has the date format as follows <code>2021-06-18 23:30:00</code> which is read by python as a character.
I want to create a variable that only contains the hour and minutes of the dates.
This is what I tried with no useful results:</p>
<pre><code>from datetime import datetime
df["hours"... | <p>You've passed the whole Series as the parameter to <code>.strptime</code>.</p>
<p>This is a minimal, reproducible example that applies a function to each member of the series:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.DataFrame(['2021-06-18 23:30:00','2021-06-19 01:02:03'],colum... | python|datetime | 1 |
3,501 | 59,159,154 | splitting JSON file using python | <p>I have below big json file</p>
<pre><code> {
"sections": [
{
"facts": [
{
"name": "Server",
"value": "<https://xxxxxxx:18443/collector/pipeline/v1_allagents>"
},
{... | <p>You can load the big file json into dictionary using <code>json</code> module. Then treat the loaded data as classical Python dict.</p>
<p>If your file contains the string in question, then this example:</p>
<pre><code>import json
with open('YOUR_JSON_FILE.json', 'r') as f_in:
data = json.load(f_in)
for ... | json|python-3.x | 2 |
3,502 | 73,150,207 | Why does the num.is_integer() function returns false | <pre><code>class Item:
pay_rate = 0.8 # The pay after %20 discount
all = []
def __init__(self, name: str, price: float, quantity=0):
#Run validations to the recieved arguments
assert price >= 0, f"Price {price} is not greater than or equal tozero!"
assert quantity >= ... | <p>I am taking the same tutorial and I actually came here to understand the same thing. From what I have looked up, there is some confusion here because of the way its written in the tutorial. To beginners like us, this looks like a recursive function and the whole thing seems to be in a loop when it actually isn't and... | python|python-3.x|function|oop | 0 |
3,503 | 73,126,924 | Create pandas dataframe on column name conditions | <p>Python newbie attempting a complex pandas dataframe logic</p>
<p>I have multiple dataframes I need to join but I'll show two below for the example. The dataframe have duplicate columns labelled with suffix '_duplicate'. I need to replicate the row instead of having the duplicate column as seen below.</p>
<p>My first... | <p>This is a very silly way of doing it and I am hoping someone comes up with a better way... but it does work:</p>
<pre class="lang-py prettyprint-override"><code>##################### Recreate OP's dataframe ###########################
data1 = {"a":1, "b":2, "a_duplicate":3,"b_dupli... | python|pandas|dataframe|duplicates | 2 |
3,504 | 73,144,052 | Pygame OGG and audio issues | <p>I have been recently working on a new game and I am finally finished with it and I was adding some music as some last touches but then I realized that the sounds were very poor quality and so I tried to make it into different extensions and wav, mp3 don't work and I was trying OGG and it says it 'failed to load'. I ... | <p>There is very little code provided in the question for analysis.</p>
<p>You describe the sound as "echoing over and over", this makes me believe your code is repeatedly asking the <code>pygame.mixer.Sound</code> object to <a href="https://www.pygame.org/docs/ref/mixer.html#pygame.mixer.Sound.play" rel="nof... | python|audio|pygame|pygame-mixer | 0 |
3,505 | 72,971,295 | Downloading blat to M1 mac | <p>I am trying to download the blat package so that I can use the GAMMA program to analyze mutations in some sequences. I have bioconda install and I am using one-liner code to download blat described here: <a href="https://shanguangyu.com/articles/install-blat-on-mac-with-one-liner-command/" rel="nofollow noreferrer">... | <p>You got to the root of the issue. M1 Macs use an ARM64-based architecture as opposed to x64. The <a href="https://anaconda.org/bioconda/blat" rel="nofollow noreferrer">website for blat</a> does not list ARM compatibility, and, addressing the M1 specifically, a quick examination of the last update to the <a href="htt... | python|macos|anaconda|conda|apple-m1 | 1 |
3,506 | 62,200,044 | Scrapy CrawlSpider and rules | <p>I'm begining with Scrapy and I made a couple of spiders attacking to the same site succesfully.</p>
<p>The first one gets the products listed in the entire site except their prices (because prices are hidden for not logged users) and the second one do login in the website.</p>
<p>My problem looks a bit weird, when... | <p>I think you're bypassing the rules by overwriting the start_requests. The parse-method is never called, so the rules aren't processed.
If you want to process the rules for page <a href="https://gsmoled.com/index.php?route=product/category&path=33_61" rel="nofollow noreferrer">https://gsmoled.com/index.php?route=... | python|python-3.x|scrapy | 2 |
3,507 | 62,445,511 | sklearn.feature_selection chi2 identifies same unigrams and bigrams for different labels | <p>I have been using a code that i found online on multi-classification using scikit: <a href="https://towardsdatascience.com/multi-class-text-classification-with-scikit-learn-12f1e60e0a9f" rel="nofollow noreferrer">https://towardsdatascience.com/multi-class-text-classification-with-scikit-learn-12f1e60e0a9f</a>. Ive b... | <p>With just two classes, these <em>should</em> be the same. The chi-squared test is finding the features that are most discriminative (in some sense) between the two classes. Your reference is different, because the target used (<code>labels == category_id</code>) is a one-vs-rest discrimination. A unigram/bigram t... | python|machine-learning|scikit-learn | 0 |
3,508 | 62,069,588 | Is there a pandas functionality to get an None instead of an index error? | <p>I have a pandas (version 0.25) DataFrame with some indexes. When I'm looking for an index not present in the DataFrame, I (of course) get an KeyError.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'age': [50, 40]}, index = ['alice', 'bob'])
# works, returns age 50:
df.loc['alice']
# does not work, gives Key... | <p>You can use <code>DataFrame.get</code> which behaves same as the vanilla Python <code>dict.get</code> method. So it will return <code>None</code> when the key does not exist. We use <code>Transpose</code> because its an column index method.</p>
<pre><code>df.T.get('charlie')
# returns None
</code></pre>
<pre><cod... | pandas|dataframe|indexing | 2 |
3,509 | 62,423,922 | regex filter for list of words until nth occurence of character | <p>I have a Dataframe with urls. I have a blacklist with words to filter these urls.
No I want to filter these urls until the third occurence of <code>/</code>.
So for example:</p>
<p><a href="http://example.com/abc/def/" rel="nofollow noreferrer">http://example.com/abc/def/</a></p>
<p>Here I would like to filter o... | <p>Use, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>Series.str.contains</code></a> with the given regex pattern:</p>
<pre><code>pattern = '|'.join(rf'(?://[^/]*?{b}[^/]+)' for b in blacklist)
m = df['url'].str.contains(pattern, ca... | python|regex|pandas|list|filter | 1 |
3,510 | 59,041,218 | Create Queue dynamically with different exchange types | <p>I'm trying to write a method that creates new queues with arguments of an existing exchange name, new queue name and routing key. The exchange might be in different types (direct, fanout, topic).</p>
<p>Is there a way to make and bind the queue without knowing the exchange type?</p>
<pre><code>def my_queue(self, e... | <p>Considering that Celery typically automatically creates queue for you, all you have to do is to call <a href="https://docs.celeryproject.org/en/latest/userguide/workers.html#std:control-add_consumer" rel="nofollow noreferrer">add_consumer()</a> to subscribe (during runtime) one or more workers to the particular queu... | python|rabbitmq|celery|amqp|kombu | 0 |
3,511 | 58,675,168 | Is it possible to turn a pandas df that has duplicate named columns into json/dictionary? | <p><a href="https://i.stack.imgur.com/rtuZz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rtuZz.png" alt="enter image description here"></a></p>
<p>I attempted to call .to_dict() but it only returns the last column</p> | <p>It's not possible to export multiple columns with identical names using <code>to_dict</code>. The only possible way is using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_json.html#pandas.DataFrame.to_json" rel="nofollow noreferrer"><code>to_json</code></a> with <code>'split... | python|pandas | 2 |
3,512 | 58,816,853 | efficient way of writing a python function | <pre><code>def getObj(self, x,y,z):
sheet = self.sheet
is_flag = sheet[FLAGTYPE]
if is_flag:
lines = adlines.objects.filter(
key="",
msc_cd=adlines.op,
tid=x,
svc_beg_dt__gte=datera.start,
svc_beg_dt__lte=datera.end
).exclude(ind=... | <p>I'm assuming you're looking to remove the duplication of the filter, you can configure them as a dictionary first before</p>
<pre><code>filter_args = {
'key': "",
'msc_cd': adlines.op,
'svc_beg_dt__gte': datera.start,
'svc_beg_dt__lte': datera.end
}
if is_flag:
filter_args['tid'] = x
else:
... | python|django|django-models | 0 |
3,513 | 58,872,453 | TypeError: 'Response' object is not iterable for BytesIO() stream | <p>I am trying to return a response to a user can download the CSV from the browser. Even though I am successfully making a CSV for some response when I return the response I get the error <code>TypeError: 'Response' object is not iterable</code></p>
<pre><code> from flask import make_response
import csv
fr... | <p><code>make_response</code> doesn't support <code>BytesIO</code> type object. It takes the <code>Response</code> type and some other args like status code and headers. Modified code with <code>jsonify</code> for creating <code>Response</code> object.</p>
<pre class="lang-py prettyprint-override"><code> from flask... | python|flask | -1 |
3,514 | 73,385,348 | Comparing lists in python gets weird | <p>The following piece of code removes an element of a list and than compares the two lists and should print the element that was removed (item#1)</p>
<pre class="lang-py prettyprint-override"><code>old = generateList() #same list
new = old.copy() #same list
old.remove("item#1") #remove one of the ite... | <p>My guess: the item you are removing is duplicated.</p>
<p><code>list.remove</code> removes only the first found item.</p>
<p>Example:</p>
<pre><code>old = ['A', 'B', 'C', 'A']
new = old.copy()
old.remove('A')
# ['B', 'C', 'A']
'A' in old
# True
</code></pre> | python|list | 0 |
3,515 | 59,578,835 | convert cupy to numpy is very slow | <h1>Condition</h1>
<ul>
<li>CuPy version
7.0.0</li>
<li>OS/Platform
Ubuntu 18.04</li>
<li>CUDA version
10.1</li>
</ul>
<h1>Code to reproduce</h1>
<pre class="lang-py prettyprint-override"><code>import cupy as np
import time
size = 60000000
tag = np.zeros(size)
#np.random.shuffle(tag)
value = np.random.random(size)
s... | <p>Converting from CuPy to NumPy involves doing a copy from the GPU memory to the CPU.
This operation is expensive and is expected to be slow. Ideally, you want your data to live in the GPU as long as possible and only move it to the CPU when it is strictly necessary.</p> | numpy|cupy | 1 |
3,516 | 49,102,410 | Django URLField doesn't accept hostname-only URLs | <p>I'm currently using Django with Docker. I have main dispatcher Django project, and several other microservices that are running on different Docker containers.</p>
<p>When I start up a new microservice, I want to add new Django model which has <code>URLField</code> pointing that microservice. But <code>URLField</co... | <p>Unfortunaly Django <code>URLField</code> doesn't accept URLs as <code>http://foo-service/</code>. You have actually answered your own question by posting the source code for <code>URLValidator</code>.</p>
<p>If you want to have a field that supports URLs outside of the scope supported by <code>URLField</code>, you ... | python|django|docker | 3 |
3,517 | 24,961,882 | Pass variable into Batch file | <p>I have a script that works that requires me to pass variable to batch file, test.bat</p>
<p><strong>script</strong> </p>
<pre><code>pst = subprocess.Popen(
["test.bat", userIP],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
</code></pre>
<p><strong>batch file</strong></p>
<pre... | <p>Since this is a Windows batch file, not a POSIX.2-compatible shell,</p>
<pre><code>D:\pstools\psloggedon.exe -l -x $1
</code></pre>
<p>should be</p>
<pre><code>D:\pstools\psloggedon.exe -l -x %1
</code></pre>
<p>(By the way, if it <em>were</em> a POSIX-compatible shell, you'd need to quote, as in <code>-x "$1"</... | python|windows|batch-file | 1 |
3,518 | 25,419,567 | Replace `\n` in html page with space in python LXML | <p>I have an unclear xml and process it with python lxml module. I want replace all <code>\n</code> in content with <code>space</code> before any processing, how can I do this work for text of all elements.</p>
<p><strong>edit</strong>
my xml example:</p>
<pre><code><root>
<a> dsdfs\n dsf\n sdf\n</... | <p>Below code will parse the xml into a string, then replace <code>\n</code> with <code>space</code> and then write to a new xml file. You can do other processing in between, depending what exactly you want to do.</p>
<pre><code>from lxml import etree
tree = etree.parse('some.xml')
root = tree.getroot()
# Get the wh... | python|lxml | 1 |
3,519 | 71,069,120 | Can I send a Whatsapp message in python when a condition == True without defining a specific time? | <pre><code>import pywhatkit as pwk
pwk.sendwhatmsg("phone_number", "Automated message", 10, 0)
</code></pre>
<p>I have this code but I want to send a message without setting a specific time.</p> | <p>Didn't find any way to do this using <strong>pywhatkit</strong>.</p>
<p>A solution I found is to use <strong>pyautogui</strong> on <strong>WhatsApp Web</strong>, selecting the message input box.</p>
<p>The program types the message and presses enter:</p>
<pre><code>import pyautogui
import time
def send_msg(msg):
... | python|selenium | 0 |
3,520 | 2,464,844 | Rewriting An URL With Regular Expression Substitution in Routes | <p>In my Pylons app, some content is located at URLs that look like <a href="http://mysite/data/31415" rel="nofollow noreferrer">http://mysite/data/31415</a>. Users can go to that URL directly, or search for "31415" via the search page. My constraints, however, mean that <a href="http://mysite/data/000031415" rel="no... | <p>You can actually do that via <a href="http://routes.groovie.org/manual.html#conditions" rel="nofollow">conditional functions</a>, since they let you modify the variables from the URL in place. </p> | python|routes|pylons | 1 |
3,521 | 6,101,902 | TypeError in python while trying to plot a sum | <p>Since I got the advice to make another question here it goes... I want to plot the sum, and I have a code:</p>
<pre><code>from scitools.std import *
from math import factorial, cos, e, sqrt
from scipy import *
import numpy as np
def f1(t):
return 0.5*(1 + sum( (a**(2*n)*cos(2*sqrt(1 + n)*t))/(e**a**2*factoria... | <p>I don't understand what that generator expression is doing at the end of the return statement in <code>f1</code>, but this:</p>
<pre><code>a=4
t = linspace(0, 35, 1000)
y1 = numpy.array([f1(t_i) for t_i in t])
</code></pre>
<p>should get you somewhere. What it does is create a new <code>numpy.array</code> by loopi... | python|plot|sum | 1 |
3,522 | 63,936,046 | 'pip2' is not recognized as an internal or external command | <p>I am trying to run a python script on my windows 10 computer using Python 2.7.</p>
<p>I run the ff command:</p>
<pre><code>python boxtool.py
</code></pre>
<p>Then I got the ff errors:</p>
<pre><code>'pip2' is not recognized as an internal or external command,
operable program or batch file.
'pip2' is not recognized ... | <p>Download the <code>get-pip.py</code> file: get-pip.py on <a href="https://bootstrap.pypa.io/get-pip.py" rel="nofollow noreferrer">pypa.io</a></p>
<p>Then install it using python</p>
<pre><code>python get-pip.py
</code></pre> | python | 1 |
3,523 | 64,164,326 | Taking multiple orders on a Cafe program, along with a loop | <p>I am currently trying to work on this python school assignment, and I'm lost at how to add a loop to continue ordering, and how to take orders of both coffee and tea. My program only lets you take an order of one, tea or coffee. My except ValueError also causes the order of adding vanilla syrup to the medium and lar... | <p>Leaving this as an answer as its too big for a comment.</p>
<p>With the structure of your data you will be much more suited to use a <code>dictionary</code>. This will make your code much easier to read, structure your data better and better support the addition of new drinks and new drink sizes in the future.</p>
<... | python | 0 |
3,524 | 43,024,145 | spaCy needs a file that is not there: strings.json | <p>I am running pytextrank were in its second stage, I get this error from spaCy:</p>
<pre><code>File "C:\Anaconda3\lib\pathlib.py", line 371, in wrapped return strfunc(str(pathobj), *args)
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Anaconda3\\lib\\site-packages\\spacy\\data\\en\\vocab\\strings.json... | <p>Finallly, I can answer question in stackoverflow. I occurred same problem but solved it eventually. Here is my suggestion:</p>
<h2>1. Download spaCy model from python -m spacy or github</h2>
<p>both way are very convenient. </p>
<p>1). from python spacy:</p>
<pre><code>python3 -m spacy download en
</code></pre>
... | python|spacy|pytextrank | 9 |
3,525 | 72,439,887 | Remove specific tick markers of a matplotlib plot, how? | <p>I have the following problem: I am creating a plot, in which I want to hide only certain x-axis ticks labels which satisfy a condition (supposing <code>ax</code> is defined above):</p>
<pre><code>xticks = ax.xaxis.get_major_ticks()
for x_tick, y_tick in ax.get_lines()[0].get_xydata():
if y_tick > -0.5:
... | <p>You could manually set which x_ticks should be in the plot by explicitly saving the location and the text as following:</p>
<pre><code>xticks = ax.xaxis.get_major_ticks()
visible_xticks_locs = []
visible_xticks_labels = []
for x_tick, y_tick in ax.get_lines()[0].get_xydata():
if y_tick > -0.5:
visible... | python|python-3.x|matplotlib|data-analysis | 1 |
3,526 | 65,532,752 | Why does the exception handler work when the zero division error is inside the else clause but not in the commented out line below | <p>Working on exception handling in python, in the code below the <code>print(n/0)</code> line currently executes the <code>except</code> <code>ZeroDivisionError</code> print statement. But if I were to delete <code>print(n/0)</code> and uncomment out <code>print(5/0)</code> it doesn't, just returns the standard zerodi... | <p>I don't completely understand your question but I am assuming you are asking why doesn't print(5/0) throws the exception that you defined? If so, it is because that exception handler is declared to work when the function call to factorial() throws an error. The statement print(5/0) is not the part of factorial().</p... | python|exception | 0 |
3,527 | 26,497,846 | Python MySQL parameter queries for dynamic table names | <p>I want to query MySQL tables using my python program. However, the tables that I want to query are the ones whose names are passed in as variables (parameters).</p>
<p>I tried something like this:</p>
<pre><code>readTable_query = """SELECT * FROM %s"""
readTable_cursor.execute(readTable_query, (table_name))
</code... | <p>According to <a href="http://dev.mysql.com/doc/refman/5.0/en/identifiers.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.0/en/identifiers.html</a> , valid table names consist of the following characters. [0-9a-zA-Z_$] So, it shouldn't be hard to write your own validator:</p>
<pre><code>import re
table_name_... | python|mysql|mysql-python | 3 |
3,528 | 45,155,117 | How to import CSV to an existing table on BigQuery using columns names from first row? | <p>I have a python script that execute a gbq job to import a csv file from Google cloud storage to an existing table on BigQuery.
How can I set the job properties to import to the right columns provided in the first row of the csv file?
I set parameter 'allowJaggedRows' to TRUE, but it import columns in order regardle... | <p>When you import a CSV into BigQuery the columns will be mapped in the order the CSV presents them - the first row (titles) won't have any effect in the order the subsequent rows are read. </p>
<p>To be noted, if you were importing JSON files, then BigQuery would use the name of each column, ignoring the order.</p> | python|google-bigquery|import-from-csv | 2 |
3,529 | 45,225,361 | Python: Stretch 2D array into 3D based on corresponding array with 3rd-dimension index | <p>Lets say I have some 2D array <code>a = np.ones((3,3))</code></p>
<p>I want to stretch this array into 3 dimensions. I have array <code>b</code>, the same size as <code>a</code>, that provides the index in the 3rd dimension that each corresponding element in <code>a</code> needs to go too.</p>
<p>I also have 3D ar... | <p>You can use fancy indexing as this, assuming the largest value in <code>b</code> is always less than <code>c.shape[2]</code>:</p>
<pre><code>n1, n2 = a.shape
c[np.arange(n1)[:,None], np.arange(n2), b] = a
c
#array([[[ nan, nan, 1.],
# [ nan, nan, 1.],
# [ nan, nan, 1.]],
# [[ nan, 1... | python|arrays|numpy | 7 |
3,530 | 45,018,902 | Specifics regarding Python, Tweepy, and config parser | <p>Alright, so basically what I'm trying to accomplish, is inputting twitter API values into an an EXE that was made from a python script. I've been trying to figure out how to input the strings AFTER the executable is made. So that I don't need to edit and modify the code EVERY time before making it into a standalone.... | <p>Apparently it came down to syntax why everything wasn't working. Due to running on on Python3 everything was lowercase.</p>
<p>P2 = ConfigParser
P3 = configparser</p>
<p>Just had to fix a few things. Thanks guys.</p> | python|windows|executable|py2exe|tweepy | 0 |
3,531 | 61,582,635 | How do I resolve RuntimeWarning: 'nltk.downloader' found in sys.modules after import of package 'nltk', but prior to execution of 'nltk.downloader'? | <pre><code>-----> Python app detected
-----> No change in requirements detected, installing from cache
-----> Installing SQLite3
-----> Installing requirements with pip
-----> Downloading NLTK corpora…
-----> Downloading NLTK packages: wordnet
/app/.heroku/python/lib/python3.6/runpy.py:125: RuntimeWar... | <p>The problem that failed the deploy process may be not the warnings that you mentioned above. To see exactly what are the failed steps encountered during the deploy process you must investigate the log file by tapping <code>$ heroku logs --tail</code> on your terminal.
About the nltk package, if you used windows to e... | python|heroku|runtime-error|nltk|dashboard | 0 |
3,532 | 60,716,314 | how to read json file without using json libarary or without any other libarary in to dictionary or list? | <p>I have a JSON file and i need to read it into dictionary or list without using and library.This is my file content.</p>
<pre><code>{
"101":"Break and Enter Commercial",
"102":"Break and Enter Residential/Other",
"103":"Vehicle Collision or Pedestrian Struck (with Fatality)",
"104":"Vehicle Collision or ... | <p>What about such way:</p>
<pre><code>with open(file) as f:
your_dict = eval(f.read().replace('\n', ''))
</code></pre> | python|json | 3 |
3,533 | 57,813,196 | Python.h not found while building sample application with cmake and pybind11 | <p>I want to build simple app with pybind11, pybind is already installed in my Ubuntu system with cmake (and make install). I use this simple cmake file:</p>
<pre><code>cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(trt_cpp_loader )
find_package(pybind11 REQUIRED)
add_executable(trt_cpp_loader main.cpp)
set_p... | <p>You'll want to use the <code>pybind11_add_module</code> command (see <a href="https://pybind11.readthedocs.io/en/stable/compiling.html#building-with-cmake" rel="noreferrer">https://pybind11.readthedocs.io/en/stable/compiling.html#building-with-cmake</a>) for the default case of creating an extension module.</p>
<p>... | python|c++|ubuntu|cmake|pybind11 | 5 |
3,534 | 56,337,778 | How to send an email template to multiple users (email addresses) in Odoo 12 | <p>I want to send an email to multiple users in Odoo 12 when a scheduler runs with custom data in email. I created my email template in the XML file. Also, I have a method which returns all my email addresses as a list. How can I loop over this list in email template in <strong><em>"email_to"</em></strong> field and ge... | <p>You can use the mass_mailing (Email Marketing
By Odoo S.A) module to do that. </p> | python|python-3.x|jinja2|odoo|odoo-12 | 2 |
3,535 | 56,404,606 | Why does pdf of arange function have normal distribution? | <p><code>arange</code> works on stepwise incrementing values and is not random function then why does it give a random distribution?</p>
<pre><code>from scipy.stats import norm
import matplotlib.pyplot as plt
x = np.arange(-3, 3, 0.001)
plt.plot(x, norm.pdf(x))
</code></pre>
<p>I expect a uniform distribution</p> | <p>The library <code>scipy.stats.norm</code> provides functionality of Normal Distribution, not Uniform distribution. Meaning when you apply the probability density function (pdf), you are not applying a constant function, but something else entirely (also knowns as the Bell curve):</p>
<p><a href="https://en.wikipedi... | python | 0 |
3,536 | 71,574,917 | Loop through every file with specific format in a directory using sys argv | <p>I'd like to loop through every file in a directory given by the user and apply a specific transformation for every file that ends with ".fastq".</p>
<p>Basically this would be the pipeline:</p>
<ol>
<li>User puts the directory of where those files are (in command line)</li>
<li>Script loops through every f... | <p>Your problem is with this line:</p>
<pre><code>with open(glob_path, "rU") as input_fq:
</code></pre>
<p>Remember that <code>glob_path</code> is a list containing all of the files in the user-supplied directory. You want to open <code>file_path</code>, which represents each element of the list you are itera... | python|biopython | 1 |
3,537 | 69,542,990 | Problem with Locators after Firefox and geckodriver update | <p>We have a Website with Vaadin technologie.</p>
<pre><code>Test environment:
firefox-56.0.1
geckodriver: 0.20.0
Robotframework 4.1.1
selenium 3.141.0
Python 3.7.3
</code></pre>
<p>This Python script are working, robot can click on this locator.</p>
<pre><code>GetElement.py
def Get_Element_hmenu():
... | <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot" rel="nofollow noreferrer">Shadow DOM</a> support was added in Firefox 63. In your previous setup with Firefox 56 the shadydom polyfill was used and as there was no shadow root encapsulation and that made the vaadin-context-menu-item findable in th... | python|html|selenium-webdriver|xpath|vaadin | 2 |
3,538 | 69,653,320 | python - best way to add a long text below plots and save this into a pdf | <p>I have a large set of photos, in which I detected several objects in every photo. I want to create a pdf including all photos and the name of the identified object, written below (not within) each photo. As there are many photos which have many objects I cannot write it within the photo or use a legend / axis name t... | <p>@Entropie_13, just addressing here your comment with an example. You can use the <code>text</code>function from matplotlib to put the text of any length wherever you want on the figure. Below is an example with text on each side of the figure.</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyp... | python|matplotlib|plot|computer-vision | 1 |
3,539 | 55,180,204 | How to find duplicates and its indexes in a list? | <p>I have a list </p>
<pre><code>l=['a','b','c','c','a','d']
</code></pre>
<p>The output should return all the duplicate elements and their indices in the list</p>
<p>Output:</p>
<pre><code>out = {a:['0','4'],c:['2','3']}
</code></pre>
<p>I have tried</p>
<pre><code>def nextDuplicates(c):
dupl_c = dict()
... | <p>A <code>dict</code> comprehension coupled with a <code>list</code> comprehension would work (even for more than 2 occurences) :</p>
<pre><code>l = ["a", "b", "c", "c", "a", "d"]
out = {el: [i for i, x in enumerate(l) if x == el] for el in l if l.count(el) > 1}
</code></pre>
<p>I saw in your expected output that... | python|python-3.x | 1 |
3,540 | 55,562,078 | Tensorflow 2.0 : frozen graph support | <p>Will the support for frozen graph continue in tensorflow 2.0 or deprecated?
I mean the scripts and APIs to create/optimize frozen graph from saved_model. Also the APIs to run the inference for the same. </p>
<p>Assuming it will be supported in future, what is the recommended method to run the inference on frozen gr... | <p>The freeze graph APIs - <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py" rel="noreferrer"><code>freeze_graph.py</code></a> and <a href="https://www.tensorflow.org/api_docs/python/tf/graph_util/convert_variables_to_constants" rel="noreferrer"><code>converter_varia... | tensorflow2.0 | 8 |
3,541 | 57,499,832 | Joining DNA sequences from two files under the same species name | <p>I have two FASTA file with DNA sequences coding for two different proteins. I want to join the sequences for the different proteins and same species into one long sequence.</p>
<p>for example, I have:</p>
<pre><code>Protein 1
>sce
AGTAGATGACAGCT
>act
GCTAGCTAGCT
</code></pre>
<pre><code>Protein 2
>sce
GC... | <p>Since you tagged Biopython, here is a compact solution. Note it puts the whole file into memory (as most simple approaches will):</p>
<pre><code>from Bio.Seq import Seq
from Bio import SeqIO
d = SeqIO.to_dict(SeqIO.parse('1.fasta', 'fasta'))
for r in SeqIO.parse('2.fasta', 'fasta'):
d[r.id] = d.setdefault(r.i... | python|bioinformatics|biopython|fasta | 1 |
3,542 | 42,153,354 | Map physical path of a file to serve path for download | <p>In my AngularJS/Python app, I uploaded a file using <code>dropzone</code> which has a physical path of something like this:</p>
<p><code>D:\uploadedFiles\tmpmj02zkex___5526310795850751687_n.jpg'</code></p>
<p>Now I want to create a link for this file for display and download on the front end. A link that looks som... | <p>You can simply add a url pattern in eg. <code>urls.py</code>:</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
...,
url(r'^uploadedFiles/(?P<file_name>.+)/$', views.download, name='download')
]
</code></pre>
<p>and a <code>download</code> method in the controller i... | python|angularjs|django | 0 |
3,543 | 54,036,747 | Not able to create boto ses client on AWS Lambda for sending mail | <p>my python code is not working on Lambda which actully works well when I run it from my local python environment. Whenever I try to create SES object on Lambda function, I get this error:</p>
<pre><code>Response:
{
"errorMessage": "Unable to import module 'lambda_function'"
}
</code></pre>
<p>Here's my code:</p>
... | <p>These days, it is highly recommended to use <code>boto3</code>.</p>
<p>The syntax is:</p>
<pre><code>import boto3
connection = boto3.client('ses', region_name='us-east-1')
response = client.send_email(
Source='string',
Destination={
'ToAddresses': [
'string',
],
'CcAdd... | python|aws-lambda|amazon-ses | 1 |
3,544 | 53,983,295 | python speed difference between regex vs slicing? | <p>I'm not asking about how to regex the table but why the speed difference is happening</p>
<p>I had a 10gb CSV file and I wanted to find specific value like this.</p>
<p>origin CSV table.</p>
<p>id | value | date | num</p>
<p>1 |"12first"| "dummy val+ 18-10-20" | "92dummy"</p>
<p>to this.... | <p>Performing a regex search first compiles a finite state machine, and then runs through it as it looks through the string character by character to see what matches. If it found a partial match and then came across something that invalidated that match, it has to back up and start again. Of course, if your regex is... | python|regex | 0 |
3,545 | 65,346,614 | Django create a models.ManyToMany and models.ForeignKey to the same table | <p>All,
I'm trying to configure my Django models.py file to include 2 tables with a ManyToMany and a ForeignKey link between the 2. The current configuration with only one entry works fine:</p>
<pre><code>Current models.py file:
from django.db import models
class CustTeamMembers(models.Model):
member_first_name ... | <p>Django offers the ManyToMany <code>through</code> property, allowing extra data on the relation.</p>
<pre><code>from django.db import models
class CustTeamMember(models.Model):
member_first_name = models.CharField(max_length = 100)
member_last_name = models.CharField(max_length = 100)
member_email ... | python|django | 0 |
3,546 | 22,562,864 | Inefficient Python Scipy Matrix Addition in Multi-threaded Program | <p>I want to process a huge text corpus, i have written two classes which a main class is calling.I have removed some fields and methods in order to be more readable.</p>
<pre><code>import queue
import threading
class Vectorizer():
def __init__(self, numThread=10):
self.docQueue = Queue.Queue(self.queueMaxSize)
... | <p>Since you're having each thread use the lock, every thread likely has to wait on the previous thread anyways. You may consider breaking it out into processes rather than threads if you have the memory to handle it. At the moment I can't figure out what your locks are holding up behind because it's all in that one li... | python|multithreading|scipy|producer-consumer | 1 |
3,547 | 22,565,136 | Python to search a string for the first occurrence of any item in a list | <p>I have to parse a few thousand txt documents using python, but right now I'm getting the code working for just one.</p>
<p>I am trying to find the first time any month (January, February, March, etc) appears in the document, and return the position of that first month. Every document has at least one month in it, ... | <p>I think this would do what you want:</p>
<pre><code>months = ["January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"]
indices = [s.find(month) for month in months]
first = min(index for index in indices if index > -1)
</code>... | python|string | 2 |
3,548 | 22,822,655 | Python: Plots not saving data in images | <p>I'm plotting for the sensors and saving the images as png... the files save but they're blank and when I run the file, only the first plot is populated with information. and i need to separate these into their own arrays without hardcoding</p>
<pre><code>import sys
import numpy as np
import matplotlib.pyplot as plt... | <p>I bet the problem is the plt.show() command. I think for this code to run properly you would need to close each figure before continuing on to the next one. Try commenting out all plt.show() commands. So your plots wont pop up when you run the script but I think they will save correctly.</p> | python|arrays|matplotlib|cfdata | 1 |
3,549 | 22,752,486 | Array for Large Data | <p>I need to form a 2D matrix with total size 2,886 X 2,003,817. I try to use numpy.zeros to make a 2D zero element matrix and then calculate and assign each element of Matrix (most of them are zero son I need to replace few of them).</p>
<p>but when I try numpy.zero to initialize my matrix I get the following memory ... | <p>If your data has a lot of zeros in it, you should use <a href="http://docs.scipy.org/doc/scipy/reference/sparse.html" rel="nofollow">scipy.sparse</a> matrix.</p>
<p>It is a special data structure designed to save memory for matrices that have a lot of zeros. However, if your matrix is not that sparse, sparse matric... | python|numpy|matrix|large-data | 2 |
3,550 | 45,470,908 | How to customize django admin search results in many to many fields | <p>I trying to filter the list shown when I use the lupe in many to many fields (image bellow).
Maybe a text search would be interesting too.</p>
<p>Any help?</p>
<p><a href="https://i.stack.imgur.com/w3Sjn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w3Sjn.png" alt="django lupe search result ex... | <p><code>self.model</code> is not <code>QuerySet</code> or a model, use the model directly:</p>
<pre><code>class PresentialModuleCourseInline(NestedStackedInline):
model = Course.modules.through
raw_id_fields = ('module_course',)
extra = 1
def get_queryset(self, request):
return Course.obj... | python|django|admin | 1 |
3,551 | 45,706,856 | Multi-level defaultdict with variable depth and with list and int type | <p>I am trying to create a multi-level dict with variable depth and with list and int type.</p>
<p>Data structure is like below</p>
<pre><code>A
--B1
-----C1=1
-----C2=[1]
--B2=[3]
D
--E
----F
------G=4
</code></pre>
<p>In the case of above data structure, the last value can be an <code>int</code> or <code>list</cod... | <p>There's no way you can use your current <code>defaultdict</code>-based structure to make <code>d['A']['B1']['C2'].append(1)</code> work properly if the <code>'C2'</code> key doesn't already exist, since the data structure can't tell that the unknown key should correspond to a list rather than another layer of dictio... | python|dictionary|defaultdict | 0 |
3,552 | 28,521,611 | How to evaluate data type (i.e. str, int, double... etc.) when reading text file | <p>I am reading in information from a text file which has been ripped from a pdf, so everything is a mess.</p>
<p>Some example variables (columns) that I'm trying to separate include date, action type and summary.</p>
<p>For date, the format is DD/MM/YY, so I know that the first index will always be an int. However, ... | <p>Short answer: use regular expressions and recast the string sections.</p>
<p>Long answer: it's because all of this is coming from a text file, so everything <em>is</em> a string. The date 23/10/90 isn't represented in a .txt as a numerical value, it's a collection of character codes. Depending on exactly what you ... | python|parsing|pdf|text | 0 |
3,553 | 28,697,773 | Free up numbers from string | <p>I have a very annoying output format from a program for my x,y,r values, namely:</p>
<pre><code>circle(201.5508,387.68505,2.298685) # text={1}
circle(226.21442,367.48613,1.457215) # text={2}
circle(269.8067,347.73605,1.303065) # text={3}
circle(343.29599,287.43024,6.5938) # text={4}
</code></pre>
<p>is there a way... | <p>if you mean that the circle(...) construct is the output you want to parse. Try something like this:</p>
<pre><code>import re
a = """circle(201.5508,387.68505,2.298685) # text={1}
circle(226.21442,367.48613,1.457215) # text={2}
circle(269.8067,347.73605,1.303065) # text={3}
circle(343.29599,287.43024,6.5938) # te... | python|numpy | 1 |
3,554 | 14,505,687 | Generate chart/graph for WHO baby percentile/z-scores | <p>I don't have a lot of programming (web or otherwise) experience. So coming from that perspective, I'm trying to tackle a little self-imposed project, wherein I am going to attempt, a very basic, minimal, but attractive (think bootstrap or helium) website, where you can enter your baby's sex, age, weight, length, hea... | <p>You could do all of that on the client side with javascript / JQuery. For charts, I would also look intp d3, it makes beautiful charts in Javascript. Doing it on the client side would be much easier than dealing with posts to a python layer. You could however use something lightweight like Flask if you want to learn... | python|graph|charts | 0 |
3,555 | 41,400,914 | Ambiguous foreign key in self-referencing table [SQLAlchemy/Alembic] | <p>I have a model classes defined like this. The idea is that that <code>Person</code> will hold general information about people as well as reference to it's "sub-classes": Woman and Men as parents. Woman and Men will hold information specific for that gender.</p>
<p>I'm using Alembic to generate the migration but I'... | <p>What I see as issue here is that you are referencing foreign key to foreign key.</p>
<pre><code>mother_id -> foreign_key(woman.id)
woman.id -> foreign_key(person.id)
</code></pre>
<p>And you create circular dependancy. You cannot create that dependency in any single creation statement in any SQL dialect. You... | python|mysql|python-3.x|sqlalchemy|alembic | 0 |
3,556 | 41,571,776 | python csv | If row = x, print column containing x | <p>I am new to python programming, pardon me if I make any mistakes. I am writing a python script to read a csv file and print out the required cell of the column if it contains the information in the row.</p>
<pre><code> | A | B | C
---|----|---|---
1 | Re | Mg| 23
---|----|---|---
2 | Ra | Fe| 90
</code></pre>... | <p>You should use a csv reader. It's built into python so there's no dependencies to install. Then you need to tell python that the third column is an integer. Something like this will do it:</p>
<pre><code>import csv
with open('data.csv', 'rb') as f:
for line in csv.reader(f):
if 20 <= int(line[2]) <... | python|python-3.x|csv | 2 |
3,557 | 41,570,417 | Why does pandas attempt to import a module when reading from a pickled file? | <p>I have collected some data via the Instagram API, which I've stored into a pandas DataFrame, which in turn has been saved via pandas <code>.to_pickle()</code> method.</p>
<p>When attempting to load the DataFrame on another computer using the `read_pickle()' method, the following error is returned:</p>
<pre><code>T... | <p>Pickle simply doesn't know how to recreate the classes. The information how a class is unpickled and restored is stored inside the class: <code>__new__</code>, <code>__init__</code>, <code>__setstate__</code> and more.</p>
<blockquote>
<p><strong>Similarly, when class instances are pickled, their class’s code and... | python|pandas|pickle|instagram-api | 6 |
3,558 | 41,526,206 | Listing input values separately in Python | <p>I am using Python 3.4 and I've written the Python code below. What I want is to save a user's name and age to a text file when they enter it. I want to see the input comma-separated line-by-line.</p>
<p>I tried <code>.split()</code> but it did not work. I would be happy for any help, thank you.</p>
<pre><code>ages... | <p>This would write a file with guests and ages</p>
<pre><code>with open(fileName, mode = WRITE) as inpt:
for i in range(len(guests)):
inpt.write(guests[i] + ", " + ages[i] + "\n")
</code></pre>
<p>demo.txt</p>
<pre><code>Andi, 12
Bertha, 34
Claus, 99
</code></pre>
<p>Or this way:</p>
<pre><code>with ... | python|split | 0 |
3,559 | 41,532,738 | Publish WordPress Post with Python Requests and REST API | <p>I try to publish post to WordPress blog with python requests and rest api by following code:</p>
<pre><code>auth = 'Basic ' + str(base64.b64encode(b'admin:123456'), 'utf-8')
headers = {'Authorization': auth}
body = {'title': 'Hello World'}
r = requests.post('wp-json/wp/v2/posts', headers=headers, data=body)
</code>... | <p>I was able to solve this</p>
<ol>
<li><p>I installed & activated this plugin on my wordpress
<a href="https://wordpress.org/plugins/application-passwords/" rel="nofollow noreferrer">https://wordpress.org/plugins/application-passwords/</a></p>
</li>
<li><p>follow the help text there and create your password strin... | python|wordpress|rest | 4 |
3,560 | 41,526,166 | Why Python 3x buffer is larger than bash dd? | <p>I want to copy a big file (>=1GB) to memory:</p>
<pre><code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from subprocess import check_output
from shlex import split
zeroes = open('/dev/zero')
SCALE = 1024
B = 1
KB = B * SCALE
MB = KB * SCALE
GB = MB * SCALE
def ck(str):
print('{}:\n{}\n'.format(str, chec... | <p>See <a href="https://stackoverflow.com/questions/26079392/how-is-unicode-represented-internally-in-python">How is unicode represented internally in Python?</a>.</p>
<p>Because you aren't specifying that your file is binary, you're reading unicode characters, which require 2-4 bytes per character to store in-memory,... | python|bash|python-3.x | 0 |
3,561 | 25,459,908 | Gene Network Topological Overlap Python | <p>In a complex gene network how can we find a topological overlap. </p>
<p>Input data as follows </p>
<pre><code>code code weight
3423 3455 3453
2344 2353 45
3432 3453 456
3235 4566 34532
2345 8687 356
2466 6467 3567
3423 2344 564
3455 2353 4564
3432 3423 456
</code></pre>
<p>The node columns ar... | <p>I must confess that I wasn't familiar with the term <em>topological overlap</em> so I had to look it up:</p>
<blockquote>
<p>A pair of nodes in a network is said to have high topological overlap if they are both strongly connected to the same group of nodes. (<a href="http://labs.genetics.ucla.edu/horvath/MTOM/" ... | python|networkx | 3 |
3,562 | 44,799,335 | Taking info from list in dictionary | <p>I have next code:</p>
<pre><code>ind=[{'id':123,'name'='Andrew','universities':[{'country'=123,'state'=123}], school=[{'name'=Beliech,'state'=...}],'type'=[{}] }]
</code></pre>
<p>I need to take name of the school in the school field, and state with country in universities field to add it into data base. I tried t... | <pre><code>import pandas
ind=[{'id':123,'name':'Andrew','universities':[{'country':123,'state':1234}], 'school':[{'name':"Beliech"}]}]
name_list = []
school_name_list = []
university_country_list = []
university_state_list = []
for i in range(len(ind)):
name_list.append(ind[i]['name'])
school_name_list.append(i... | python|list | 0 |
3,563 | 61,854,692 | pytorch model not updating | <p>I put my training code below. I am using torch.optim.SGD as optimizer. I thought optimizer.step() would be doing the update but the model accuracy seems to stay the same. My friend said he didn't use the optimizer.step() and his works fine.
I tried taking it out, still the same result. What can I be doing wrong?
I... | <p>I think this line should be under your for loop
<code>optimizer.zero_grad()</code>. You need to clear the parameter gradients after each loop. </p>
<p>try this</p>
<pre><code>def train(epoch, model, optimizer, trainloader):
model.train()
for batch_idx, (data, labels) in enumerate(trainloader):
opt... | python|pytorch|training-data | 1 |
3,564 | 23,951,063 | How to "select file" with a Python script in Google App Engine? | <p>I'm trying to create an online application for a Python function I have created. In my script, I input the path of my file for the computer (input_path = '/users/user/desktop/input.txt') but I'm not sure how to go about this using Google App Engine. </p>
<p>I have the choice between 3 templates: Flask, Django, and... | <p>This really has nothing whatsoever to do with "python scripts" or even frameworks.</p>
<p>You are writing a web application: you need to think about how the web works. The <em>only</em> way to give your web application access to a file on the user's computer is to upload it. To upload it, you need to create an HTML... | python|django|google-app-engine|interactive|bottle | 4 |
3,565 | 35,873,115 | How to create a new list for each line in a file? | <p>I am trying to create a soduko styled program.
A notepad/word document is uploaded into Python and I want Python to check:</p>
<p>Each line (row) has the same number of characters
Each column has the same number of characters
No characters are repeated twice in either a column or in a row
Every character is used on... | <p>You could <code>split</code> each line with its own comprehension:</p>
<pre><code>my_list = [[x for x in line.strip().split(' ')] for line in open(filename)]
</code></pre>
<p>Note that this oneliner, much like your original code, won't close the file handle it opened. A much safer approach would be to open it sepa... | python|list|file | 1 |
3,566 | 35,799,137 | Creating new instances with many to many relationship iterating over a dictionary DJANGO | <p>I am new to Django. I try to create several instances of my two models pizza and toppings from a dictionary:</p>
<pre><code>dictionary = dict()
dictionary[“Pizza1”] = (“A”,”B”,”C”)
dictionary[“Pizza2”] = ()
dictionary[“Pizza3”] = (“B”,”D”)
</code></pre>
<p>I want to relate them with a ManyToMany relationship s... | <p>Try this, works for me:</p>
<pre><code>for pizza in dictionary:
pizza_instance, created1 = Pizza.objects.get_or_create(name=pizza)
for topping in dictionary[pizza]:
topping_instance, created2 = Topping.objects.get_or_create(name=topping)
pizza_instance.has_toppings.add(topping_instance)
... | python|django|for-loop|dictionary | 1 |
3,567 | 29,778,903 | Using Scrapy to crawl a list of urls in a section of the start url | <p>I am trying to do realize a CrawlSpider with Scrapy with the following features.
Basically, my start url contains various list of urls which are divided up in sections. I want to scrape just the urls from a specific section and then crawl them.
In order to do this, I defined my link extractor using restrict_xpaths, ... | <p>You're defining a Set by using {} around the pair of rules. Try making it a tuple with ():</p>
<pre><code> rules = (Rule(LinkExtractor(restrict_xpaths=(".//*[@id='mw-content- text']/ul[19]"), ), callback='parse_items', follow=True),
Rule(LinkExtractor(deny_domains='...start url...'), callback='parse_items',follow... | python|scrapy | 0 |
3,568 | 29,612,576 | Importing Your Own Module Python Attribute Error | <p>so I am trying to import my own python module into a new script that I have written. I get the error: </p>
<p>AttributeError: 'module' object has no attribute 'getSessionIds'</p>
<p>In my main file, I am importing as such:</p>
<pre><code>import UnityAppSessionSummary
class ScheduledGenSummaries(DatabaseModule): ... | <p>You have a file <code>UnityAppSessionSummary.py</code> that is being imported when you run</p>
<pre><code>import UnityAppSessionSummary
</code></pre>
<p>However, inside that <code>.py</code> file you have a class named <code>UnityAppSessionSummary</code> as well, and inside <strong>that</strong> is your <code>getS... | python-2.7|module|python-import | 3 |
3,569 | 60,957,805 | Matching in regex all capital words between two words | <p>I am creating a parser of a text. The text contains two specific words that I do not want to match and between them I want to capture all the capital words that exist. </p>
<p>For example the text would be:</p>
<pre><code>Treatments: IBUPROFEN\n\xe2\x80\xa2 COLCHICINE .... Physical examination
</code></pre>
<p>I ... | <p>To capture only the words that are in capital letters and between words <code>begin</code> and <code>end</code>, use this regex:</p>
<pre><code>.*begin|end.*|[^e]*?\b([A-Z]{2,})\b
</code></pre>
<p><a href="https://regex101.com/r/zaODax/1/" rel="nofollow noreferrer">See online demo</a></p>
<p>When you replace <cod... | python|regex|word|uppercase | 1 |
3,570 | 70,203,284 | possible to cache a table in sqlalchemy to not query database in specific use case? | <p>I have a use case where I am running a python script constantly updating a specific column on a table in a database. The script is like the following:</p>
<pre><code>while True:
events = load_events()
for event in events:
team_1 = event.team_1
team_2 = event.team_2
dd = datetime.strp... | <p>So what you're experiencing here is the cost per round trip from your service to your database. Depending on how many records need to be returned there are some options.</p>
<blockquote>
<p>Note, without a deeper understanding of the data provided, these queries might not be optimal.</p>
</blockquote>
<p>The most ob... | python|sqlalchemy | 1 |
3,571 | 53,363,688 | Converting a list of tuples to a Pandas series | <p>I have a list of tuples which I want to convert to a Series. </p>
<pre><code>return array2
[(0, 0.07142857142857142),
(0, 0.07142857142857142),
(1, 0.08333333333333333),
(1, 0.3333333333333333),
(1, 0.3333333333333333),
(1, 0.08333333333333333),
(3, 0.058823529411764705),
(3, 0.058823529411764705)]
... | <p>Using <a href="https://docs.python.org/3/library/functions.html#zip" rel="noreferrer"><code>zip</code></a> and sequence unpacking:</p>
<pre><code>idx, values = zip(*L)
a = pd.Series(values, idx)
</code></pre>
<p>With duplicate indices, as in your data, <code>dict</code> will not help as duplicate dictionary keys ... | python|pandas|dictionary|tuples|series | 22 |
3,572 | 53,797,322 | Limit occurences of strings in a list based on prefix | <p>So the code that I am working on is for an IRC bot, and I want to implement a way to limit channels based on the <code>CHANLIMIT</code> server option. </p>
<p>The <code>CHANLIMIT</code> option is a list of limits with the prefix and limit seperated by <code>:</code>, but if there is nothing after the <code>:</code>... | <p>There are many ways to approach this problem. Doing some minimal simplifications you could have something like that:</p>
<p><strong>Solution 1</strong></p>
<pre><code>results = ['#+:2', '&:']
channels_to_test = ['#test1', '#test2', '+test3', '&test4',
'#test5', '!test5', '&test6', '... | python|python-3.x|irc | 1 |
3,573 | 46,159,343 | How does Cufflinks inject methods into Pandas even if imported before? | <p>Cufflinks provides an interface between Panda's <code>DataFrame</code> and plotly <code>iplot</code> in the form of <code>DataFrame.iplot</code>. The first two output examples below do not surprise me, but the third does. Each is run in a new instance of iPython3.</p>
<pre><code>import pandas as pd
pd.DataFrame.ipl... | <p>I'm fairly sure this is because python <a href="https://docs.python.org/3/library/sys.html#sys.modules" rel="nofollow noreferrer">caches</a> the modules it loads. For example, all of the below expressions are true:</p>
<pre><code>import sys.modules
import pandas as pd
import pandas as pds
print(pd is pds)
print(pd ... | python|pandas|plotly | 1 |
3,574 | 55,074,628 | Looping through, and updating, array values until a condition is met, or until 100 loops have been completed? | <p>Working in Python 3.7 on a Jupyter Notebook. I'm working on a project that will loop through a 2D Numpy Array ("board", if you will) check for all instances of the number 1. When it finds the number 1, I need it to check the values to the left, right, above it, and below it. If any of the values next to it is a 2, t... | <p><strong>In Python, Assignment statements do not copy objects, instead they create bindings between a target and an object</strong>. When we use = operator the user thinks that this creates a new object, Well, it doesn’t. It only creates a new variable that shares the reference of the original object.</p>
<p><strong... | python|arrays|for-loop|while-loop|agent-based-modeling | 1 |
3,575 | 73,696,611 | cannot bind function in tkinter (gives error "takes 1 positional argument but 2 were given") | <p>I'm trying to bind the textbox and function, but keep giving errors ("Application. main() takes 1 positional argument but 2 were given"). I searched on google and most of them answered that putting "self" would solve the problem, but it doesn't work for me.
Please teach me how to solve this probl... | <p>The <code>bind()</code> callback is called with an <code>Event</code> argument. Either change <code>main()</code> to take another argument, or use a lambda to ignore the argument.</p>
<pre><code>self.entry_1.bind('<Return>', lambda e: self.main())
</code></pre> | python|tkinter | 2 |
3,576 | 73,637,500 | Executing the auth token once per run - Locust | <p>Ideally I want to grab the token one time (1 request) and then pass that token into the other 2 requests as they execute. When I run this code through Locust though...</p>
<pre><code>from locust import HttpUser, constant, task
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
clas... | <p>In your case it runs once <strong>per user</strong> so my expectation is that you spawned 24 users and the number of <code>Labware</code> and <code>Instruments</code> is at least 2x times higher so it seems to work exactly according to the <a href="https://docs.locust.io/en/latest/writing-a-locustfile.html#on-start-... | python|load-testing|locust | 2 |
3,577 | 12,874,756 | Parallel optimizations in SciPy | <p>I have a simple function</p>
<pre><code>def square(x, a=1):
return [x**2 + a, 2*x]
</code></pre>
<p>I want to minimize it over <code>x</code>, for several parameters <code>a</code>. I currently have loops that, in spirit, do something like this:</p>
<pre><code>In [89]: from scipy import optimize
In [90]: res... | <p>Here's another try, based on <a href="https://stackoverflow.com/a/12874964/1015178">my original answer</a> and the discussion that followed.</p>
<p>As far as I know, the <a href="http://docs.scipy.org/doc/scipy/reference/optimize.html" rel="noreferrer">scipy.optimize</a> module is for functions with scalar or vect... | python|optimization|scipy | 22 |
3,578 | 12,987,624 | Confusion between numpy, scipy, matplotlib and pylab | <p>Numpy, scipy, matplotlib, and pylab are common terms among they who use python for scientific computation.</p>
<p>I just learn a bit about pylab, and I got confused.
Whenever I want to import numpy, I can always do:</p>
<pre><code>import numpy as np
</code></pre>
<p>I just consider, that once I do</p>
<pre><code... | <ol>
<li><p>No, <code>pylab</code> is part of <code>matplotlib</code> (in <code>matplotlib.pylab</code>) and tries to give you a MatLab like environment. <code>matplotlib</code> has a number of dependencies, among them <code>numpy</code> which it imports under the common alias <code>np</code>. <code>scipy</code> is not... | python|numpy|matplotlib|scipy | 135 |
3,579 | 24,465,748 | Yowsup Authentication don't work | <p>I'm trying to make some test with this nice library.</p>
<p>I have made successfully tests with yowsup-cli but now I'd like to create a small python script to manage in a smart ways events (with listener/callback).</p>
<p>I'm trying the code explained here <a href="https://github.com/tgalal/yowsup/wiki/Yowsup-Libr... | <p>Just incase someone has the same problem that authentication isn't working though you're passing the right username and password as argument, You have to base 64 encode the password like is done in the Command Line client.</p>
<p>You have to get the password by registering using Yowsup or WART OR from your phone ... | python|whatsapp|yowsup | 2 |
3,580 | 24,860,747 | numpy.random.permutation lose a column | <p>First of all sorry but I haven't great programming skills, I'm learning Python for my master thesis in Natural Sciences.</p>
<p>In my script there's this piece of code:</p>
<pre><code>self._dumpArrayToFile(movers, 'movers_'+str(y)+'_'+str(r)+'.csv')
moversCats = numpy.random.permutation(movers['cat'])
self._dumpAr... | <p>You are only passing a single column to <code>permutation</code>, so that is all that gets shuffled. Per <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.permutation.html" rel="nofollow">the documentation</a>:</p>
<blockquote>
<p>If <code>x</code> is a multi-dimensional array, it is only ... | python|numpy|permutation | 1 |
3,581 | 24,523,818 | Using Labels in HAVING() Clause in SQLAlchemy | <p>I'm attempting to implement the following query for handling nested sets (see <a href="http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/" rel="noreferrer">here</a>) within SQLAlchemy. What I'm struggling with is how to use the labeled <code>depth</code> calculation in the main <code>SELECT</code>... | <p>Your SQL query uses implicit joins, in SQLAlchemy you need to define them explicitly. Other than that your second try is almost correct:</p>
<pre class="lang-py prettyprint-override"><code>node = aliased(Category)
parent = aliased(Category)
sub_parent = aliased(Category)
sub_tree = DBSession.query(node.name,
... | python|mysql|sql|orm|sqlalchemy | 13 |
3,582 | 38,126,273 | SyntaxError when parsing dict with single and double quotes? | <p>So, I'm retrieving a blog post from Tumblr using the pytumblr API. I want to retrieve a post and extract only the post content. <em>Technically</em> Tumblr sends it to me in a <code>dict</code>, but the format is very, very confusing. In addition to that, it uses both single and double quotes! Here's my code:</p>
<... | <p>The syntax error is caused by your removal of the brackets. Somewhere inside the dictionary there's a list of tags, and the string you have goes:</p>
<pre><code>... u'title': None, u'tags': u'queued', u'suggestion', u'suggestion blog', ...
</code></pre>
<p>That is, it switches from dictionary notation to list nota... | python|dictionary|abstract-syntax-tree|pytumblr | 1 |
3,583 | 31,025,980 | Lua-like dict in Python | <p>In Lua you can address keys of the dictionary like attributes:</p>
<pre><code>d = {a = 1, b = 1}
d['a'] == d.a -- this returns true
</code></pre>
<p>Is there something like that in Python? I've noticed that sklearn bunch objects have similar properties.</p> | <p>No, the only valid ways to access a <code>dict</code> using a key are <code>d['a']</code> or <code>d.get('a')</code></p>
<p>The former may raise a <code>KeyError</code> if that key is not in the <code>dict</code>, and the latter takes a second optional argument that it will return if the key is not found.</p> | python|dictionary | 4 |
3,584 | 28,934,409 | how to parse csv file in python | <p>I am new to python. I have the following code to read from a csv file, yet I am confused at certain points. </p>
<pre><code>with open(sys.argv[1], "rU") as csvfile:
f = csv.reader(csvfile, delimiter=',')
# f.next() #if an input file a headed
for row in f: params.append(row)
... | <p>The <code>i</code> in <code>params[::i]</code> is called the <a href="https://docs.python.org/2/reference/expressions.html?highlight=slicings#slicings" rel="nofollow"><em>stride</em></a> of the slice. Since the <code>::</code> part means the whole sequence, it has the effect of selecting every <code>i</code><sup>th<... | python | 0 |
3,585 | 8,680,733 | Twisted share a variable between tcp/udp protocols | <p>I have the following tcpserver simple example. I'm looking to share the factor counter var with a udp server so on each connect it will inc the value for both tcp and udp. So if i connect first with tcp it will be 2 then if I connect to the port on udp.. it will be 3</p>
<pre><code>#!/usr/bin/env python
from twist... | <p>The argument to <code>reactor.listenUDP</code> should be a <code>DatagramProtocol</code> instance, as shown in the UDP example: <a href="http://twistedmatrix.com/documents/current/core/howto/udp.html" rel="nofollow">http://twistedmatrix.com/documents/current/core/howto/udp.html</a>. You can't use your <code>QOTDFac... | python|twisted | 3 |
3,586 | 8,480,316 | True multithreading with boost.python | <p>I'm trying to test a multi-threaded C++ DLL. This DLL is supposed to be thread-safe. I have it wrapped with boost.python, and I'd like to create multiple python threads to exercise the DLL through the boost.python wrapper. I'm actually <em>trying</em> to cause threading problems. </p>
<p>What I can't seem to fi... | <p>How to release GIL when calling a C++ function from Python via Boost.Pyhton:</p>
<p><a href="http://wiki.python.org/moin/boost.python/HowTo#Multithreading_Support_for_my_function" rel="nofollow">http://wiki.python.org/moin/boost.python/HowTo#Multithreading_Support_for_my_function</a></p> | python|multithreading|boost-python | 4 |
3,587 | 52,402,745 | Matplotlib savefig with eps doesn't draw grid lines in a projection plane on a 3d plot | <p>In Matplotlib, I want to draw grid lines in all projection planes on a 3d plot in a EPS file. <br/>
I wrote the below code.
The code works as desired on the figure window and the PNG file, but not on the EPS file. <br/>
In the EPS file, grid lines aren't drawn into one of three projection planes.
I pasted the crea... | <p>Well the EPS <strong>does</strong> draw the grid line. The problem is that it draws them the same colour as the flat fill for the plane.</p>
<p>If you open the EPS file with a text editor, and go to line 261 you will see:</p>
<pre><code>0.900 setgray
gsave
288.863762 206.238981 m
165.545964 132.223634 l
158.321608... | python|matplotlib|3d|eps | 3 |
3,588 | 51,987,955 | Connecting docker port and ip from another docker | <p>I have one running docker which is for postgres running as below.</p>
<pre><code>$ sudo docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
505ab3ffc4b1 postgres "docker-entrypoint..." 26 minu... | <p>The recommended approach to make containers interact with each other on one machine (not clustered) is by using a user defined bridge network.
Here you can read about the <a href="https://docs.docker.com/network/#network-drivers" rel="nofollow noreferrer">possible network drivers</a>. Here you can read about the <a ... | python|docker|dockerfile | 1 |
3,589 | 18,972,579 | How can I get a facebook post vs a facebook status from the facebook python sdk | <p>I'm trying to access a user's posts from their wall using the <a href="https://github.com/pythonforfacebook/facebook-sdk/blob/master/facebook.py" rel="nofollow">python sdk</a>. I want the <a href="https://developers.facebook.com/docs/reference/api/post/" rel="nofollow">POST</a> object not the <a href="https://develo... | <p>Apparently if you append the userid and the postid, it returns the post instead of the status objects.</p>
<p>So for example: <code>get_object("100006765630328_1380118238890351")</code> will return a POST object, whereas <code>get_object("1380118238890351")</code>will return a STATUS object.</p>
<p>I posted a full... | python|facebook|facebook-graph-api | 0 |
3,590 | 19,149,840 | Unit test in aptana studio 3 | <p>How do you run a Unit test on your class creation in aptana studio 3 on a python format class.
I am wondering if I am supposed to add something to my code or is there a function in aptana studio that does it for you.</p> | <p>Aptana Studio does not have a special test mode like PyCharm does, if you want to run unit-tests, you will simply need to create a <code>unittest</code> using Python's <code>unittest</code> module. So, for example:</p>
<pre><code>import unittest
class MyTestCase(unittest.TestCase):
def test_something(self):
... | python|class|unit-testing|testing|aptana | 0 |
3,591 | 67,504,836 | Python(PyTorch): TypeError: string indices must be integers | <p>I have written the following code to train a <code>bert</code> model on my dataset but when I execute it I get an error at the part where I implement <code>tqdm</code>. I have written the entire training code below with full description of the error. How to fix this?</p>
<h1>Code</h1>
<h3>Model</h3>
<pre><code>TRANS... | <p>Your code is designed for an older version of the transformers library:</p>
<p><a href="https://stackoverflow.com/questions/65079318/attributeerror-str-object-has-no-attribute-dim-in-pytorch">AttributeError: 'str' object has no attribute 'dim' in pytorch</a></p>
<p>As such you will need to either dow... | python|python-3.x|deep-learning|pytorch|tqdm | 1 |
3,592 | 36,427,800 | Download Google Spreadsheet and save as xls | <p>Am trying to write python procedure to download a spreadsheet from google spreedsheets and save it as .xls.
here is my code</p>
<pre><code>import os
import sys
from getpass import getpass
import gdata.docs.service
import gdata.spreadsheet.service
'''
get user information from the command line argument and
... | <p><strong>(Feb 2017)</strong> Most answers (including the code in the OP) are now out-of-date as <a href="https://developers.googleblog.com/2012/04/changes-to-deprecation-policies-and-api.html" rel="nofollow noreferrer">ClientLogin authentication was deprecated</a> back in 2012(!), and <a href="http://developers.googl... | python|google-sheets|gdata | 2 |
3,593 | 19,351,908 | Python, Flask, Twitter and UnicodeEncodeError | <p>I am working with Python and Flask utilizing the Twitter API. I request some data from Twitter that comes with special characters like 'ñ' and so on, for example a list with the trending topics.</p>
<p>The problem comes when trying to display correctly those characters. I thought the universal solution for these ki... | <p>try:</p>
<pre><code>new_string = urllib.unquote(unicode(old_string))
</code></pre> | python|encoding|character-encoding|flask | 0 |
3,594 | 13,505,349 | Python mechanize doesn't work when HTTPS and Proxy Authentication required | <p>I use Python 2.7.2 and Mechanize 0.2.5.<br>
When I access the Internet, I have to go through a proxy server. I wrote the following codes, but an URLError occurred at the last line.. Does anyone have any solution about this?</p>
<pre><code>import mechanize
br = mechanize.Browser()
br.set_debug_http(True)
br.set_han... | <p>I don't recommend you to use Mechanize, it's outdated. Take a look at <a href="http://docs.python-requests.org/en/latest/" rel="nofollow">requests</a> it will
make your life a lot easier. Using proxies with requests it's just this:</p>
<pre><code>import requests
proxies = {
"http": "10.10.1.10:3128",
"https":... | python|https|proxy|mechanize | 3 |
3,595 | 39,383,554 | Is this python pattern for a singleton safe? | <p>I have a module R that handles gets and sets to a redis cluster. It is imported all over a flask api's endpoints. My first thought was to use a Singleton class in R so that we maintain one single connection to the redis cluster, but I'm not entirely I should putting a singleton class pattern into a code base that is... | <p>It is safe but there are two things I don't think are good practices.</p>
<ol>
<li>Initializations or class definitions etc should not be there in
init.py Init file is use to hide internal structure of the package.
A simple <strong>init</strong>.py is a good <strong>init</strong>.py </li>
<li>Creating objects in gl... | python|singleton|python-module | 1 |
3,596 | 55,142,456 | Is it possible to self-reference type in Python attr | <p>I am looking to do something like this:</p>
<pre><code>@attr.s
class A(object):
a_dict = attr.ib(factory=Dict, type=Dict[str, A], validator=optional(instance_of(Dict)))
</code></pre>
<p>It is possible to type it just as <code>type=Dict</code> but I wonder if you can self-reference like <code>type=Dict[str, cls... | <p>The issue is that <code>class A(object): A</code> results in <code>NameError: name 'A' is not defined</code>. What this means is that one can not reference a class by its name during its creation in its defining block. </p>
<p>I think that to get around this in typing, one can use a string instead: <code>type=Dict[... | python|python-2.7|python-attrs | 2 |
3,597 | 52,527,270 | Pandas dates not showing on plot | <p>My dataframe is from a cvs as follow:</p>
<pre><code> Date Open High Low Close Adj Close Volume
0 1996-01-01 4.06250 4.12500 3.8750 3.90625 3.093209 7048800
1 1996-02-01 3.84375 3.96875 3.5000 3.62500 2.870497 12864000
2 1996-03-01 3.50000 4.25000 3.5000 4.12500 3.... | <p>Your date is a string, so <code>matplotlib</code> so it wont automatically plot the labels. Change it to a <code>datetime</code> first and then plot.</p>
<pre><code>import pandas as pd
df['Date'] = pd.to_datetime(df.Date)
</code></pre>
<hr>
<p>Your plot:</p>
<pre><code>df2 = df.loc[0:12]
df2.set_index('Date', in... | python|pandas | 3 |
3,598 | 37,346,006 | Pandas: Return a new Dataframe with specific non continuous column selection | <p>I have a dataframe with 85 columns and something like 10.000 rows.<br>
The first column is <code>Shrt_Desc</code> and the last <code>Refuse_Pct</code><br>
The new data frame that I want has to have <code>Shrt_Desc</code>, then leave some columns out and then include in series <code>Fiber_TD_(g)</code> to <code>Refus... | <p>Borrowing the main idea from <a href="https://stackoverflow.com/a/10677896/5276797">this answer</a>:</p>
<pre><code>pd.concat([food_info['Shrt_Desc'], food_info.ix[:, 'Fiber_TD_(g)':]], axis=1)
</code></pre> | python|pandas|dataframe | 0 |
3,599 | 34,263,848 | How can I upload an image on an textfield from django admin panel like we do in wordpress | <p>Is there any way I can uplaod an image in django textfield from admin panel like we do on wordpress where we get to choose to upload image. I have used ckeditor as my textfield editor which lets me insert links and make text bolds, there is an upload image option available but it ask me for image url instead of aski... | <p>You can use <strong>RichTextUploadingField</strong> of django-ckeditor.
you need to import it first in your <strong>models.py</strong></p>
<pre><code>from ckeditor.fields import RichTextUploadingField
</code></pre>
<p>now in your model you can do like this</p>
<pre><code>content = RichTextUploadingField()
</code>... | python|django|ckeditor | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.