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 |
|---|---|---|---|---|---|---|
5,000 | 59,122,245 | Python error - Can't redirect the url set up | <p>I have code as follow. The app should be redirected to <code>https://example.com?code={ cliient_id }</code> but it failed with the error.</p>
<p>The error is:</p>
<blockquote>
<p>redirect() takes 0 positional arguments but 1 was given</p>
</blockquote>
<p>The code is below. Error is on the last line of extracte... | <p>You are importing <code>redirect</code> from flask, but also defining your own function named <code>redirect</code>. Your new definition "wins", and your definition takes no arguments. Try naming your function <code>redirect_</code> instead (or any other name), e.g.</p>
<pre><code>client_id='XXXXXXXXXXXX'
@bp.rout... | python|flask | 1 |
5,001 | 59,472,583 | GCP GPU is not detected in Keras | <p>I'm running the UNet Keras model on a GCP instance with one NVIDIA Tesla P4GPU. But it does not detect the GPU. Instead it runs on the CPU. p.s. I installed drivers & tensorflow-gpu buy it wont work. How to fix this issue?</p>
<pre><code>I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver d... | <p>You need to first install the driver. <a href="https://cloud.google.com/compute/docs/gpus/install-grid-drivers" rel="nofollow noreferrer">Follow this instruction</a></p> | tensorflow|keras|deep-learning|google-compute-engine|nvidia | 1 |
5,002 | 63,256,852 | How can i solve the TypeError gotten while working with feature_engine | <p>I am working with feature_engine to fill missing values</p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# from feature-engine
from feature_engine import missing_data_imputers as mdi
#Working with House Data and Feature Engine__Practice
cols_to_use = [
'BsmtQual', 'Fireplace... | <p>By looking at the stack trace you provided, this seems to me like an incompatibility between <code>feature_engine</code> and an old version of scikit-learn. In older versions (e.g. <a href="https://scikit-learn.org/0.21/modules/generated/sklearn.utils.validation.check_is_fitted.html" rel="nofollow noreferrer">0.21</... | python|pandas|machine-learning|scikit-learn|feature-engineering | 1 |
5,003 | 73,458,209 | How do I keep this image in the center of the window? | <p>I'm making a hangman-like game; for that, I need all the different stages of the man to be visualized, hence images. I want the entire tkinter window to be an image, when I change the size it pushes the image right.</p>
<pre class="lang-py prettyprint-override"><code>from tkinter import *
root=Tk()
root.geometry(&q... | <p>If canvas is bigger than window then when you resize then it show more canvas but and it can looks like it moves image.</p>
<p>But if you use smaller canvas then <code>pack()</code> will try to keep centered horizontally. And if you add <code>pack(expand=True)</code> then it will try to keep it centered vertically.<... | python|image|tkinter|tkinter-canvas | 2 |
5,004 | 16,016,254 | Adding a click function to a button in Python | <p>I am very new to Python. I'm creating a simple 3D world using Vizard 4.0 and I want to add a stopwatch to the screen. I dont want an actual 3D stopwatch, just a simple text box in the corner of the screen which updates as the stopwatch counts. Heres what I ave so far and it doesnt work, any suggestions or help would... | <p>Cracked it :)</p>
<pre><code>#Add text fields to a dictionary.
text_dict = {}
for kind in ['score','instructions','time' ]:
text = viz.addText('', viz.SCREEN )
text.setScale( .5,.5)
text.alignment( viz.TEXT_CENTER_BASE )
text.alpha( 1 )
text_dict[ kind ] = text
text_dict['score'].setPosition( .1... | python|vizard | 0 |
5,005 | 59,861,580 | Pandas df reorder rows and columns according to integer index list | <p>I have the following structure for my data frame: </p>
<pre><code> col1 col2 col3
myindex
apple A B C
pear Ab Bb Cb
turtle A1 B1 C1
</code></pre>
<p>Now I get two lists, one with reordered column indices, one with reordered row indices, but as integers, for e... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="noreferrer"><code>DataFrame.iloc</code></a> and because python counts from <code>0</code> convert list to arrays and subtract <code>1</code>:</p>
<pre><code>rowindices = [3,1,2]
colindices = [1,3,2]
df = df.iloc... | python|pandas|dataframe | 6 |
5,006 | 59,778,248 | modifying an ssd net in tensorflow | <p>If I were using Keras, Modifying the architecture would be straight forward modification of the network layers:</p>
<pre><code> x = Conv2D(32, (3, 3), padding="same")(inputs)
x = Activation("relu")(x)
x = Conv2D(32, (3, 3), padding="same")(x)
x = Activation("relu")(x)
x = MaxP... | <p>It looks like the actual model has been abstracted away to<br>
<a href="https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet_v2.py" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet_v2.py</a></p>
<p>Though I would ima... | tensorflow|keras|neural-network|architecture|tensorflow-ssd | 0 |
5,007 | 48,951,622 | wrong output size after conv2d function | <p>the image size is [m,32,32,3] (m = no. of training examples) </p>
<p>the filter size is [3,3,3,10] </p>
<p>stride = 1</p>
<p>padding = None</p>
<p>if I convolve this using tensorflow.nn.conv2d then the output shape should be this, according to the formula</p>
<pre><code>out ={ ( 32 - 3 + 2*(0) ) / 1 }+ 1 = 30
<... | <p>padding = "SAME" means:</p>
<pre><code>input = [1, 2, 3, 4, 5, 6, 7, 8]
filter size = [1, 3]
stride = [2]
so input to filter will be [[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 0]]
</code></pre>
<p>padding = "VALID" means:</p>
<pre><code>input = [1, 2, 3, 4, 5, 6, 7, 8]
filter size = [1, 3]
stride ... | tensorflow|computer-vision|deep-learning | 3 |
5,008 | 25,360,270 | Python NLTK tokenize sentence with wrong syntax from human errors | <p>I am looking for a way to handle sentence tokenizing task well.</p>
<p>I have this text extracted from a human written review for a restaurant</p>
<pre><code>Nevertheless, the soup enhances the prawns well.In contrast, the fish offered is fresh and well prepared.
</code></pre>
<p>Note that, the period that is the... | <p>I decided to use regex for preprocessing of the text. The regex i use was.</p>
<pre><code>re.sub(r'(\w{2})([.!?]+)(\w+)', r'\1\2 \3', text)
</code></pre>
<p>It has 3 groups. Group 1 is before the punctuation <code>(\w{2})</code>. Group 2 is the punctuation which can be <code>[!?.]</code> and can repeat more than... | python|nltk | 0 |
5,009 | 71,081,404 | Disable pytest logging to original log file | <p>I am calling set_log_path() in a pytest fixture before each unit test, but the logs are now being sent to both the test log file and the original log file. When running unit tests, I would like to separate these logs so that they do not appear to come from actual execution of the code.</p>
<p>Here is the pytest fix... | <p>You should be add the following to your pytest.ini file which will only disable logging to your original directory.</p>
<pre><code>[pytest]
addopts = -p no:logging
</code></pre> | python|logging|import|pytest | 0 |
5,010 | 60,202,828 | Using Recursion to add to a trie | <p>I have been learning about the Trie structure through python. What is a little bit different about his trie compared to other tries is the fact that we are trying to implement a counter into every node of the trie in order to do an autocomplete (that is the final hope for the project). So far, I decided that having ... | <h2>The Trie itself containing the root node and insert/find functions</h2>
<pre><code>class Trie:
def __init__(self):
## Initialize this Trie (add a root node)
self.root = TrieNode()
def insert(self, word):
## Add a word to the Trie
current_node = self.root
for char... | python-3.x|autocomplete|trie | 0 |
5,011 | 59,987,700 | How to add names to layers of Keras sequential model | <p>I use Keras in Tensorflow 2.0 to create a sequential model:</p>
<pre><code>def create_model():
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28,28), name="bla"),
keras.layers.Dense(128, kernel_regularizer=keras.regularizers.l2(REGULARIZE), activation="relu",),
keras.layers... | <p>You're doing it the right way, straight from my jupyter :</p>
<pre class="lang-py prettyprint-override"><code>from tensorflow import keras
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28,28), name="bla"),
keras.layers.Dense(128, activation="relu",),
keras.layers.Dropout(0.5),
keras.... | keras|tensorflow2.0 | 1 |
5,012 | 60,026,948 | Adding a header row with values for each column to multiple CSV files | <p>I have multiple CSV files in one directory but with no headers.
I'm looking for a robust way to add same headers to all files in my directory at once.</p>
<p>Sample.csv:</p>
<pre><code> John Doe Guitar 4 units
</code></pre>
<p>Desired output after adding headers 'name', 'product', 'quantity':</p>
<pre><cod... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer">Read_csv</a>
has a names parameter that you can use for columns.</p>
<p>If you want to add the same header into every csv you read. You can just pass the columns into the names parameter when you rea... | python|shell|csv|terminal | 1 |
5,013 | 59,930,379 | Cloudbuild with Python 2.7 and Apache Beam | <p>I created a pipeline with Apache Beam on Python 2.7 that runs on Google Dataflow. This pipeline works well when I deploy it locally from my laptop. I now wish to deploy it via CloudBuild. This is my cloudbuild.yaml file:</p>
<pre><code>steps:
- name: "docker.io/library/python:2.7"
args: ["pip", "install", "-t... | <p>I was able to reproduce your issue with only another file named <code>tests.py</code> with one line:</p>
<pre class="lang-py prettyprint-override"><code>import apache_beam as beam
</code></pre>
<p>It seems that it is a <a href="https://github.com/tensorflow/tensorflow/issues/6341" rel="nofollow noreferrer">known i... | python-2.7|apache-beam|google-cloud-build | 0 |
5,014 | 60,287,262 | Python Flask - UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc4 in position 0: invalid continuation byte | <p>When I run a code here is an error
Python files are on the USB flash drive
It is an Error </p>
<pre><code>Traceback (most recent call last):
File "e:/1/test.py", line 15, in <module>
app.run(port=8080, host='127.0.0.1')
File "E:\python\lib\site-packages\flask\app.py", line 990, in run
run_simple(h... | <p>just need to rename the computer to the english symbols</p> | python|python-3.x|flask | 0 |
5,015 | 6,025,082 | Headless Browser for Python (Javascript support REQUIRED!) | <p>I need a headless browser which is fairly easy to use (I am still fairly new to Python and programming in general) which will allow me to navigate to a page, log into a form that requires Javascript, and then scrape the resulting web page by searching for results matching certain criteria, clicking check boxes, and ... | <p>I use webkit as a headless browser in Python via pyqt / pyside:<br>
<a href="http://www.riverbankcomputing.co.uk/software/pyqt/download">http://www.riverbankcomputing.co.uk/software/pyqt/download</a><br>
<a href="http://developer.qt.nokia.com/wiki/Category%3aLanguageBindings%3a%3aPySide%3a%3aDownloads">http://develo... | javascript|python|screen-scraping|headless-browser | 30 |
5,016 | 67,039,062 | Erlang echo server with python client is not echoing, python client not receiving response correctly | <p>So I'm trying to get an erlang server started, which will echo back from my python client. I can see the connection is made, however the echo doesn't actually happen. Can anybody point me to the right solution?</p>
<p>I'm using python3 as my client driver.</p>
<p>Here is my erlang server: I start it with echo:acce... | <p>One issue is that you have <code>{packet, line}</code> and the message does not include a new line, so the echo server keeps waiting for the message to be completed before sending it to the handler.</p>
<p>Also, you should be careful with the <code>active</code> option, as any data that is received during the <code>... | python|erlang|python-3.7|erlang-otp|erlang-ports | 1 |
5,017 | 66,760,283 | How can I make custom image path with static_url in Django? | <p>I have six images name as <strong>1.jpg</strong> to <strong>6.jpg</strong> of each side of dice and I want to display image defined by a random number I generate in runtime.</p>
<p>How can I make dynamic path including this random number? I tried some ways but getting <code>404 image not found</code> only.</p>
<p>se... | <p>One of possible solutions:</p>
<pre><code><img class="myImage" src='{% static "images" %}{{ myImage }}' />
</code></pre>
<p><code>static "images"</code> will prepend "images" with STATIC_URL, <code>myImage</code> was taken outside of <code>{% %}</code> and now double cur... | python|django|django-templates|django-staticfiles | 1 |
5,018 | 42,615,844 | A program for prime-factorizing any given number | <pre><code>n = 600851475143
i = 2
while i * i < n:
while n%i == 0:
n = n / i
i = i + 1
print (n)
</code></pre>
<p>This is a program in python that finds the largest prime factor of any given number. I was wondering if there is a way to modify it so that one can find all the prime factors instead ... | <p>Here is a simple program to factor integers:</p>
<pre><code>Python 2.7.5+ (default, Sep 17 2013, 15:31:50)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def factors(n):
... f, fs = 2, []
... while f * f <= n:
... if n % f == 0:
... ... | python|prime-factoring | 2 |
5,019 | 42,928,833 | Memory leak Python, lists inside for loop | <p>I wrote a simple snippet of code to process a text file that contains one phrase per line with PoS tagged words (e.g. I/noun am/verb) and I want to extract the word and the tags separately:</p>
<pre><code>splitted_sentences = []
splitted_pos = []
with open("my_path", "r") as tagged_sentences:
for sentence in t... | <p><code>splitted_sentences</code> is a list of lists of strings. Memory overhead for lists is ~70 bytes, and ~40 bytes for strings. Assuming average word/POS is 5 bytes and average sentence is 10 word/pos pairs, 100MB file is 1M sentences * 10 words * 1 string = (1M * 70) * (10 * 40) = 28Gb of memory if all strings we... | python|python-3.x|memory-leaks | 4 |
5,020 | 65,489,612 | Add normalization layer at the begining of a pre-trained model | <p>I have a pretrained UNet model with the following architecture</p>
<pre><code>UNet(
(encoder1): Sequential(
(enc1conv1): Conv2d(3, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(enc1norm1): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(enc1relu1):... | <p>You can wrap your pretrained model with a <code>nn.Module</code> that will use the <code>UNet</code> in its forward definition:</p>
<pre><code>class UNetWrapper(nn.Module):
def __init__(self, unet):
super(UNetWrapper, self).__init__()
self.norm = nn.BatchNorm2d(3)
self.unet = unet
de... | python|machine-learning|deep-learning|pytorch | 0 |
5,021 | 50,833,856 | Read Python data into C++ code | <p>I'm updating a python code and a c++ code so that the second can read data delivered from the first, use it to run before resending its updated data to the original python code.
More precisely:
- My python file makes a list data[2][5]: </p>
<pre><code>data = [[Cij[0, 0],Cij[0,1],Cij[0,2],Cij[2,2],Cij[3,3]],[50,50,... | <p>So consider the Python data array</p>
<pre class="lang-py prettyprint-override"><code>data = [[0.1, 0.2, 0.3, 0.4, 0.5], [50, 50, 100, 100, 0]]
</code></pre>
<p>A 2D array which you want to import in C++. The problem is already the data types:</p>
<pre class="lang-py prettyprint-override"><code>type(data[0][0])
O... | c++|python-3.x|types|bin | 0 |
5,022 | 3,826,867 | match two strings with letters in random order in python | <p>if I have 2 strings like:
<code></p>
<pre><code>a = "hello"
b = "olhel"
</code></pre>
<p></code>
I want to use a regular expression (or something else?) to see if the two strings contain the same letters. In my example a would = b because they have the same letters. How can this be achieved?</p> | <pre><code>a = "hello"
b = "olhel"
print sorted(a) == sorted(b)
</code></pre> | python|regex | 10 |
5,023 | 3,819,917 | single py file for convert rst to html | <p>I have a blog written in reStructuredText which I currently have to manually convert to HTML when I make a new post.</p>
<p>I'm writing a new blog system using Google App Engine and need a simple way of converting rst to HTML.</p>
<p>I don't want to use <code>docutils</code> because it is too big and complex. Is t... | <p>docutils is a library that you can install. It also installs front end tools to convert from rest to various formats including html.</p>
<ul>
<li><a href="http://docutils.sourceforge.net/docs/user/tools.html#rst2html-py" rel="noreferrer">http://docutils.sourceforge.net/docs/user/tools.html#rst2html-py</a></li>
</ul... | python|google-app-engine|restructuredtext | 28 |
5,024 | 50,249,166 | python s=input().count What does input().count function do in python? | <p>I saw this code on the internet:</p>
<pre><code>s=input().count
print( max( (s('6')+s('9')+1)//2, max([s(i) for i in "01234578"])))
</code></pre>
<p>but I don't get what this line does :</p>
<pre><code>s=input().count
</code></pre>
<p>I thought this function was to count how many letters are in the word. So I tr... | <p><code>s=input().count</code> is a function which you can call.</p>
<p>You could write</p>
<pre><code>input().count('6')
</code></pre>
<p>to count how many times you get 6 in the <code>input</code>.</p>
<p>Or,</p>
<pre><code>s('6')
</code></pre>
<p>is now a shorthand for this.</p> | python|input | 1 |
5,025 | 45,056,439 | How do write a unit test for my function that takes user inputs | <pre><code>"""A program to do FLAMES by accepting two names.
F-Friends, L-Lovers, A-Admirers, M-Married Couple, E-Enemies, S-Secret Lovers
Modified Version : Jan 11 2017
Programmer : Selikem v 0.1.0
"""
def Flames():
print("\nAre you READY FOR FLAMES????")
boyName = input("Enter the Guy's Name: ")
girlNa... | <p>Separate the UI code (asking user inputs, preinting outputs) from the domain model (the part of the code that computes something). Then you can unittest the domain model.</p> | python|unit-testing | 0 |
5,026 | 64,761,189 | Bot Blacklists Discord.py | <p>I'm trying to find out how to blacklist people using a json file and checking if the user id is in the file. So far, this is my code:</p>
<pre><code>import json
with open("ids.json", "r") as f:
ids = json.load(f)
@client.command()
async def test(ctx):
if ctx.message.author.id in ids:
... | <p>The problem is that your IDs in the json file are strings. <code>ctx.message.author.id</code> is an int.</p>
<p>To address this problem you could convert your IDs into integers instead:
<code>[713780345035817022, 701792352301350973]</code> inside of your json file.</p> | python|discord|discord.py | 0 |
5,027 | 61,246,269 | Problem with sorting with multiple criterias in Python | <p>I am trying to sort a list composed of names and grades:</p>
<p><code>[['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41.0], ['Harsh', 39.0]]</code></p>
<p>I want to sort them first according to the grades and then if the grades are the same, according to the alphabetical order of their names. I tr... | <p>THE PERFECT SOLUTION (1st answer from this <a href="https://stackoverflow.com/questions/6666748/python-sort-list-of-lists-ascending-and-then-decending">answer</a>)</p>
<pre><code>score_list = sorted(score_list,key = lambda x: (-x[1], x[0]))
</code></pre>
<p>or (my way):</p>
<pre><code>score_list = [j[::-1] for j... | python|list|sorting | 1 |
5,028 | 61,235,469 | Extracting date from a string in a multidimensional array | <p>I am having a hard time with a part of my homework. </p>
<p>Basically, I have user to input some data for x people in 2Darray (name, last name, id, salary).
ID is a string of 13 numbers being <strong>ddmmYYYY</strong>XXXXXX (x is not important for this part of the task). I need to extract the IDs from every array ... | <p>Slicing+formatting is a pretty easy way:</p>
<pre><code>worker_data = [
input("Name, Last name, ID and salary ").split()
for _ in range(int(input("How many? ")))
]
worker_dobs = [
f"{id[0:2]}.{id[2:4]}.{id[4:8]}"
for [_first, _last, id, _salary] in worker_data
]
</code></pre>
<p>This is assuming th... | python|arrays|string|date|multidimensional-array | 3 |
5,029 | 61,598,406 | Evaluate function in python problem assignment | <p>here I have the problem in line 68 of the code where I evaluate the string of code"snake_y=snake_y-14"
how can I evaluate a string with the assignment because I have not seen any questions regarding assignment operations being used in eval() function</p>
<pre><code>import pygame
import random
import time
import sys... | <p>For one, I don't really see why evaluating a string is necessary, instead of just directly executing that code. It would be better to not use <code>eval()</code> and instead just use the code instead.</p>
<p>However, what it looks like what you need is the <code>exec()</code> function. It's similar to <code>eval()<... | python|python-3.x|eval|variable-assignment|assignment-operator | 0 |
5,030 | 57,735,351 | Need help creating a code that instances an object along a surface evenly | <p>I'm pretty new to coding and I need to create a code that generates an object along the normal of a selected geo surface.</p>
<p>Anything to start me on the right path would be appreciated.</p>
<p>I initially tried to use duplicate, but I was told that command instancer is the better option.</p>
<pre><code>
def C... | <p>You might not actually need to query the UV direction of the target geometry.
Try looking into the commands for constraints like cmds.normalConstraint or cmds.geometryConstraint. As for the number of objects to make, consider using a for loop in a range of how many objects you want. If you want to apply a random r... | python|maya | 0 |
5,031 | 57,962,769 | Ignore . (dot) directories in os.walk | <p>Learning a python I'm working on a generic utility script to recurse any directories below and spit filenames and other properties into a file - on Windows right now. I keep getting errors as below and I don't care about these files which appear to be found in "dot directories" so far. Manually listing directories t... | <p>Filename patterns are not processed by the <code>in</code> operator or the <code>.remove()</code> method. You can use the <code>filter()</code> function to remove names that match a pattern.</p>
<pre><code>directories = filter(lambda name: not name.startswith("."), function)
</code></pre>
<p>But you never use <cod... | python|recursion|os.walk | 1 |
5,032 | 57,984,358 | NoneType object is not callable in nested function python | <p>I am beginner to Python, i am trying this follwing code but i cant understand the error </p>
<pre class="lang-py prettyprint-override"><code>def make(label):
def echo(message):
print(label+':'+message)
make('Message')('Hi')
</code></pre>
<p>I expect the output to be <code>Message:Hi</code> but it sh... | <p>you need to return the echo function</p>
<pre class="lang-py prettyprint-override"><code>def make(label):
def echo(message):
print(label+':'+message)
return echo
make('Message')('Hi')
</code></pre> | python-3.x | 1 |
5,033 | 56,119,894 | Is there a more efficient way to iterate over a list of dictionaries? | <p>I'm trying to iterate over a list of dictionaries and keeping only those with a year value in their <code>yearID</code> key. Essentially, the list (<code>statistics</code>) is baseball statistics and each row (dictionary) are the stats of a player during a year.</p>
<p>This code seems to work just fine (for VERY sm... | <p>Depends what you mean by "efficient." Your code should work fine for large amounts of dictionaries, so I'm gonna assume you mean efficient in terms of code written.</p>
<p>In that case, <code>nlist</code> can be simplified into a simple list comprehension:</p>
<pre><code>[dicts for dicts in statistics if str(dicts... | python|list|dictionary|iteration | 2 |
5,034 | 71,713,468 | Heroku config variables appear in console but are set to None when accessing with os.environ.get | <p>I'm trying to upload files to an S3 bucket and I'm using <a href="https://devcenter.heroku.com/articles/s3-upload-python" rel="nofollow noreferrer">this</a> tutorial. I'm setting config variables in the terminal using <code>heroku config:set</code> and when I enter <code>heroku config</code> in the terminal, my vari... | <p><code>heroku config:set</code> sets variables <em>on Heroku</em>. Like their name suggests, environment variables are specific to a particular environment. Settings set this way have no impact on your local machine.</p>
<p>There are several ways to set environment variables locally. One common method involves puttin... | python|heroku|environment-variables | 1 |
5,035 | 57,452,501 | FileNotFoundError: [Errno 2] in python 3 | <p>This script makes a github repo from command line
I have a file not found error. I cannot seem to solve it. any help is appreciated.</p>
<p>tried exception errors</p>
<p>Script:</p>
<pre><code>import sys, os, subprocess, os.path
class git_script:
def __init__(self, dir_path):
self.dir_path = dir_path... | <blockquote>
<p><code>os.mkdir(dir_path)</code> will create the given directory only, but it will
not create the intermediate directory in the given path. </p>
<p>For example: <code>dir_path = "~/Downloads/Project/repo_name"</code> this will
throw error.</p>
</blockquote>
<p>Solution:</p>
<p><code>os.maked... | python-3.x|python-3.7 | 0 |
5,036 | 42,331,848 | How to display dataframes? | <p>I am doing the Titanic problem in Kaggle and I have problems displaying the dataframe:</p>
<pre><code>import pandas as pd
import numpy as np
titanic = pd.read_csv("input/train.csv")
titanic.head()
</code></pre>
<p>This should display the <code>train.csv</code> but it doesn't. Do you know why?</p> | <p>Whether you are using the REPL in Sublime Text or just running the program, you can display a dataframe called <em>titanic</em> as:</p>
<pre><code># prints first 5 rows in dataframe format
print(titanic.head())
# prints all rows in dataframe format
print(titanic)
</code></pre>
<p>If you want to display the data f... | python|pandas|numpy|dataframe|kaggle | 1 |
5,037 | 42,163,926 | How to join multiple models and get the result in pythonic way? | <p>I have 4 models.</p>
<pre><code>class User(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField()
class Subscription(models.Model):
user_id = models.ForeignKey(User)
title = models.CharField()
class Address(models.Model):
user_id = models.ForeignKey(User)
street = models.... | <p>Have you tried to follow <a href="https://docs.djangoproject.com/en/1.10/topics/db/queries/#backwards-related-objects" rel="nofollow noreferrer">this snippet</a> from documentation?</p>
<p>Having a <code>User</code> object instance you can do something like this to access subscriptions:</p>
<pre><code>user.subscri... | python|django|django-models|orm|sqlite | 0 |
5,038 | 54,125,907 | Keras: How to create a sparsely connected layer? | <p>I want to have neural network where the nodes in the input layer just connected to some nodes in the hidden layer. In small it should look similar to this:
<img src="https://i.stack.imgur.com/tFGBJ.png" alt="example"></p>
<p>My original problem has 9180 input nodes and 230 hidden nodes (these numbers refer to the b... | <p>You can multiply the weights of the layer with the binary mask, that you have.
For example, let's suppose, you have 4 inputs and 3 outputs. Now you have weight matrix between these layer is of dim (4,3). And you also have mask matrix, which tell about connection. Now point-wise multiply both matrix, and you are goo... | tensorflow|keras|neural-network|keras-layer | 1 |
5,039 | 53,878,553 | Why multiprocessing.Pool cannot change global variable? | <p>I want to use <code>multiprocessing.Pool</code> to load a large dataset, here is the code I'm using:</p>
<pre><code>import os
from os import listdir
import pickle
from os.path import join
import multiprocessing as mp
db_path = db_path
the_files = listdir(db_path)
fp_dict = {}
def loader(the_hash):
global f... | <p>Because you are using <code>multiprocessing.Pool</code> your program runs in multiple processes. Each process has its own copy of the global variable, each process modifies its own copy of the global variable, and when the work is finished each process is terminated. The master process never modified its copy of t... | python|multiprocessing | 7 |
5,040 | 54,049,139 | Mask lower triangluar portion of pandas DataFrame | <p>This is a dataframe output I'm generating, which is a 5 x 5 correlation matrix.</p>
<pre><code> A B C D E
A 1.00000 -0.277360 0.653920 -0.479600 0.513890
B -0.27736 1.000000 -0.790648 0.885801 -0.482763
C 0.65392 -0.790648 1.000000 -0.876451 0.672148
... | <p>Check with <code>tril_indices</code></p>
<pre><code>df.values[np.tril_indices(len(df))]=np.nan
df
A B C D E
A NaN -0.27736 0.653920 -0.479600 0.513890
B NaN NaN -0.790648 0.885801 -0.482763
C NaN NaN NaN -0.876451 0.672148
D NaN NaN NaN NaN -0.... | python|pandas|dataframe | 2 |
5,041 | 58,457,353 | Simulate a mobile browser | <p>Faced a creative challenge. I ask for help with advice</p>
<p>The browser must be mobile, in an emulated android or pretend to be mobile</p>
<p>Found <a href="http://appium.io/" rel="nofollow noreferrer">http://appium.io/</a> and <a href="http://selendroid.io/" rel="nofollow noreferrer">http://selendroid.io/</a> p... | <p>Firstly- is this because of a swipe that is why you need to use the mobile </p>
<p>Or
Because the site is different from regular desktop site?</p>
<p>If it is a regular but you can do it in mobile size, you may do it using selenium. If the swipe is within the web and not native this can be done with selenium too.... | python|android|web-crawler|appium | 0 |
5,042 | 65,314,654 | Pandas reads almost every column in .txt as index - SOLVED | <p>I have a file named "sample name_TIC.txt". The first three columns in this file are useful - Scan, Time, and TIC. It also has 456 not useful columns after the first 3. To do other data processing, I need these not-useful columns to go away. So I wrote a bit of code to start:</p>
<pre><code>os.chdir(main_fo... | <p>Answering here to make sure the problem gets flagged as answered, in case someone else searches for it.</p>
<p>I made an error when calling the result from the code which included the <code>usecols=[0,1,2]</code> argument, and I was calling an older dataframe. The following line of code successfully generated the de... | python|pandas|txt | 0 |
5,043 | 65,365,315 | How to pass user input (string) that is already saved as a variable as a parameter? | <pre class="lang-py prettyprint-override"><code>import random
import time
from sports import sports
from states import states
def get_word():
while True:
user_input = input('Select a category (sports or states): ')
if user_input in ['sports', 'states']:
return random.choice([user_input]... | <p>If you have only a few possibilities, it's often easier to make a set of <code>if</code> statements:</p>
<pre><code>if user_input in ['sports', 'states']:
if user_input == 'sports':
return random.choice(sports)
elif user_input == 'states':
return random.choice(states)
</code></pre>
<p>If you ... | python|string|variables|parameters | 1 |
5,044 | 22,890,598 | Apply function to any two elements of a list - Python | <p>I have a function which calculates the jaccard index for two parse strings. The function is working OK and its code is below:</p>
<pre><code>def jack(a,b):
x=a.split()
y=b.split()
k=float(len(list(set(x)&set(y))))/float(len(list(set(x) | set(y))))
return k
</code></pre>
<p>However, when I want ... | <p>Since you have one element lists and you are passing the lists as the parameters whereas your function expects strings, I would recommend you to invoke your function like this</p>
<pre><code>jack(a[2][0], a[3][0])
</code></pre>
<p>Also, you dont have to convert the <code>set</code> to a <code>list</code> to find t... | python|string|list | 2 |
5,045 | 22,491,230 | Scraping a webpage for state name | <p>I am working on a little project that searches a set of web pages for some PII. In particular, I am having some difficulty in correctly scraping the page to extract the State the person lives in. The specific example that wreaks havoc is Indiana. My regex searches each page for the presence of a full state name or a... | <p>There is no perfect way to easily do this that I know of. What you should do depends on the ratio of false positives to false negatives you want.</p>
<p>Here are a few observations that may help:</p>
<ul>
<li>The state abbreviation IN is preceded or followed by <code>,</code>, <code>;</code>, or <code>.</code> mor... | python|regex|web-scraping | 0 |
5,046 | 45,610,364 | Storing and accessing URLs | <p>I have a list of URLs which I want to access with python. Which is the best way to store those? There are ~40 URLs and the list is quite constant, but I would like to be able to update the complete list (I have a scraper checking for those URLs from certain website. Currently URLs are stored like this:</p>
<pre><co... | <p>You can use a dictionary for that: </p>
<pre><code>urllist = {'A':'url1', 'B':'url2', 'C':'url3'}
</code></pre>
<p>if you want to access the url for A, you do: </p>
<pre><code>urllist["A"]
</code></pre>
<p>To get the list of all url names </p>
<pre><code>>>> urllist = {'A':'url1', 'B':'url2', 'C':'url... | python|web-scraping | 2 |
5,047 | 45,310,110 | greenthreads doesn't run just after the spawn call | <p>I'm creating a simple program that uses the eventlet greenthreads and I cannot understand their behavior. From the following example it seems to me that the thread only runs when I call the .wait() method. I read the documentation and I can't find any method similar to the "start" method provided by the threading mo... | <p>TL;DR: you need <code>eventlet.sleep()</code> or wait for something useful, usually network.</p>
<p>Observed behavior is expected for this synthetic test. Production code provides excessive opportunities for running other greenthreads. In other words: <em>it actually works similar to OS threads with real code</em>.... | python|multithreading|eventlet | 1 |
5,048 | 6,811,549 | How can I include a python package with Hadoop streaming job? | <p>I am trying include a python package (NLTK) with a Hadoop streaming job, but am not sure how to do this without including every file manually via the CLI argument, "-file". </p>
<p>Edit: One solution would be to install this package on all the slaves, but I don't have that option currently.</p> | <p>Just came across this gem of a solution: <a href="http://blog.cloudera.com/blog/2008/11/sending-files-to-remote-task-nodes-with-hadoop-mapreduce/" rel="nofollow noreferrer">http://blog.cloudera.com/blog/2008/11/sending-files-to-remote-task-nodes-with-hadoop-mapreduce/</a></p>
<p>first create zip w/ the libraries de... | python|hadoop | 29 |
5,049 | 56,873,213 | django.db.utils.OperationalError: (2013, "Lost connection to MySQL server at 'handshake: reading inital communication packet', system error: 0") | <p>I am developing an app in django to push it on Heroku, and while trying to migrate a database in mysql to heroku, I pip installed mysql-python and as I try to run the server, I got this error:</p>
<blockquote>
<p>django.db.utils.OperationalError: (2013, "Lost connection to MySQL
server at 'handshake: reading in... | <p>SOLVED</p>
<p>After fixing thing as I decribed in the question update,
I found out that Heroku has some problems to manage mysql database, even if connected with the add-on ClearDB.</p>
<p>So I changed the database from mysql to Postgresql, thus not needing the <code>mysql-python</code> modules anymore.
This made me... | python|mysql|django | 0 |
5,050 | 56,893,716 | How to configure the X label intervals in Line Graph in python | <p>Similar to <a href="https://stackoverflow.com/questions/56878072/ploting-time-series-data-with-all-the-time-stamp-labeled-in-python?noredirect=1#comment100318921_56878072">Ploting Time Series Data with all the time stamp labeled in python</a></p>
<p>The data set has Time Stamp to 30 Second Resolution, When Ploting,... | <p>Use <a href="https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.xticks.html" rel="nofollow noreferrer">xticks</a>.</p>
<pre><code>times = [0, 30, 60, 90, 120, ...]
filtered_times = times[::120] # Skip 60 minutes at a time
xticks(filtered_times, map(str, filtered_times))
</code></pre> | python|matplotlib|seaborn | -1 |
5,051 | 44,660,072 | Filter pandas DataFrame by string length within group | <p>Let's say I have the following data</p>
<pre><code>import pandas as pd
df = pd.DataFrame(data=[[1, 'a'], [1, 'aaa'], [1, 'aa'],
[2, 'bb'], [2, 'bbb'],
[3, 'cc']],
columns=['key', 'text'])
key text
0 1 a
1 1 aaa
2 1 aa
3 2 b... | <p>No need for the intermediate step. You can get a series with the string lengths like this:</p>
<pre><code>df['text'].str.len()
</code></pre>
<p>Now juut groupby key, and return the value indexed where the length of the string is largest using idxmax()</p>
<pre><code>In [33]: df.groupby('key').agg(lambda x: x.loc[... | python|pandas | 5 |
5,052 | 44,556,854 | Python: Append JSON objects to nested list | <p>I'm trying to iterate through a list of IP addresses, and extracting the JSON data from my url, and trying to put that JSON data into a nested list.</p>
<p>It seems as if my code is overwriting my list over and over, and will only show one JSON object, instead of the many I have specified.</p>
<p>Here's my code:</... | <p>Try breaking up your code into smaller, easier to digest parts. This will help you to diagnose what's going on.</p>
<pre><code>camera_details = []
for obj in json_obj['cameras']:
if 'name' in obj and 'serial' in obj:
camera_details.append([obj['name'], obj['serial']])
</code></pre> | json|python-2.7|list|nested | 1 |
5,053 | 35,892,032 | Remove elements from a list according to indexes list efficiently | <p>I have two very large lists of ints: <code>list1</code> and <code>list2</code>.</p>
<p>In <code>list1</code> I have indexes of <code>list2</code> (some are invalid), I need to remove the elements in these indexes from <code>list2</code>.</p>
<p>This is my code:</p>
<pre><code>for index in list1:
if index >... | <p><strong>Edit</strong>: I've just noticed that this answer actually does the <em>inverse</em> of what Andy is asking, it removes the items in <code>list2</code> whose indices are <em>not</em> in <code>list1</code>. I am going to leave it here in case someone attempting to do that comes across this question, but be aw... | python|arrays|algorithm | 4 |
5,054 | 15,163,365 | How do I store multiple integers in an array with a single line raw input? | <pre><code>FirstName = raw_input("Please enter your first name: ")
Scores = map(int, raw_input("Please enter your four golf scores: ").split())
print "Score analysis for %s:" % FirstName
print "Your golf scores are: " + Scores
print "The lowest score is " + min(Scores)
print "The highest score is" +max(Scores)
</code><... | <p>The error I see when I run your code is about string formatting of the output, not the reading of the input. One way to correct the code is shown below. I changed the string+list error to use the <code>print</code> statement's comma. I changed the two string+int errors to use string interpolation.</p>
<pre><code... | python|arrays|raw-input | 0 |
5,055 | 15,049,955 | String eval() but ignore leading zeros (octal) | <p>I have a dynamically changing string which is evaluated using eval(). Now for numbers staring with '0' it is represented using octal system.
Eg. eval('030') = 24</p>
<p>Now there's another thread with a similar issue (<a href="https://stackoverflow.com/questions/9843033/pythonic-way-to-eval-all-octal-values-in-a-s... | <p><em>Since feature requests to <a href="https://meta.stackexchange.com/questions/82099/answering-comment-answered-questions">mark a comment as an answer</a> remain declined, I copy the above solution here.</em></p>
<p>I've tried using negative lookbehind: <code>re.sub(r'(?<!\.)\b0+(?!\b)', '', a)</code> and it se... | python|regex | 0 |
5,056 | 29,463,477 | IOError: [Errno 13] Permission denied: 'sri.txt' | <p>I have been trying to create a simple file using the below code.But I get the error message again and again. I have the full control over the python directory.</p>
<pre><code>myfile = open('sri.txt','w')
myfile.write("My first line written in python \n")
myfile.write("Hello World")
myfile.close()
</code></pre>
<p>... | <p>Well, you don't have write permission for that file. If the file already exists, you might not be able to overwrite it. It might also be that you don't have permission to write in that directory,</p> | python|file | 4 |
5,057 | 29,788,047 | Keep TFIDF result for predicting new content using Scikit for Python | <p>I am using sklearn on Python to do some clustering. I've trained 200,000 data, and code below works well.</p>
<pre><code>corpus = open("token_from_xml.txt")
vectorizer = CountVectorizer(decode_error="replace")
transformer = TfidfTransformer()
tfidf = transformer.fit_transform(vectorizer.fit_transform(corpus))
km = ... | <p>I successfully saved the feature list by saving <code>vectorizer.vocabulary_</code>, and reuse by <code>CountVectorizer(decode_error="replace",vocabulary=vectorizer.vocabulary_)</code></p>
<p>Codes below:</p>
<pre><code>corpus = np.array(["aaa bbb ccc", "aaa bbb ddd"])
vectorizer = CountVectorizer(decode_error="re... | python|machine-learning|scikit-learn|tf-idf | 32 |
5,058 | 29,451,524 | Execute function only if a variable is True | <p>I would like to run a function only if a statement is True.
For example, i have:</p>
<pre><code>def foo():
# do something
</code></pre>
<p>And i want to run this only when</p>
<pre><code>var == True
</code></pre>
<p>And in key handler I <strong>don't</strong> want to do something like this:</p>
<pre><code>i... | <p>Like this?</p>
<pre><code> def foo():
print('foo')
>>> bool = True
>>> if bool: foo()
foo
>>> bool = False
>>> if bool: foo()
</code></pre>
<p>If the above isn't suitable, I don't think it's clear what you'd like to do or why something like this wouldn't work:</p>
<pre><c... | python|methods|idioms | 8 |
5,059 | 46,189,035 | Creating a list of sliced dataframes | <p>I am trying to create a list of dataframes where each dataframe is 3 rows of a larger dataframe.</p>
<pre><code> dframes = [df[0:3], df[3:6],...,df[2000:2003]]
</code></pre>
<p>I am still fairly new to programming, why does: </p>
<pre><code> x = 3
dframes = []
for i in range(0, len(df)):
df... | <p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html" rel="nofollow noreferrer"><strong><code>np.split</code></strong></a> </p>
<p><strong>Setup</strong><br>
Consider the dataframe <code>df</code></p>
<pre><code>df = pd.DataFrame(dict(A=range(15), B=list('abcdefghijklmno')))
</code><... | python|python-3.x|pandas | 4 |
5,060 | 46,583,735 | Python: How to find all matches in a multiline string but not proceeded by particular word? | <p>I have SQL codes and I would like to extract the table name after the "insert" keyword.</p>
<p>Basically, I would like to extract using the following rules:</p>
<ol>
<li>Contains the word "insert"</li>
<li>Followed by the word "into" which is optional</li>
<li>Exclude if the there's a "--" (which is single line co... | <p>In 2 steps with <code>re.sub()</code> and <code>re.findall()</code> functions:</p>
<pre><code># removing single line/multiline comments
stripped_lines = re.sub(r'/\*[\s\S]+\*/\s*|.*--.*(?=\binsert).*\n?', '', lines, re.S | re.I)
# extracting table names preceded by `insert` statement
tbl_names = re.findall(r'(?:\... | python|regex|findall | 1 |
5,061 | 49,653,392 | Unique constraints cause error when duplicating record in Odoo 11 | <p>I have an unique constraint for my <code>code</code> field. When I click on the 'duplicate' option in the dropdown action I'm getting the validate error.
Is there any way to use 'duplicate' even if the field <code>code</code> is unique?</p>
<pre><code> class sample(models.Model):
_name = 'sample'
code=fiel... | <p>Yes, it is. You have two ways to do this. When you duplicate a record, <code>copy</code> method is called, and it creates a new record with the values of the original record (it only copies the values of the fields whose argument <code>copy=True</code> -by default is <em>True</em>-). So you can change that argument ... | python-3.x|odoo|odoo-11 | 4 |
5,062 | 49,367,716 | cv2 ImportError: DLL load failed: The specified module could not be found | <p>I'm working with opencv in my last study's project. I have python 2.7 and opencv 3.4 already installed. I developed my python project in windows 8 64 bit and I converted my application from .py to .exe through Pyinstaller and it's working fine .</p>
<p>But when I move my application to the industrial machine which ... | <p>I had the same issue. I solved it by placing two dlls in the same folder as my .exe file. The dlls are "api-ms-win-downlevel-shlwapi-l1-1-0.dll" which can be downloaded from the internet and other one is "opencv_ffmpeg***_**.dll" which can be found in python site-packages if you have installed python-opencv via pip,... | python|opencv | 2 |
5,063 | 62,525,757 | Plotting Multiple Columns Across Rows in a DataFrame | <p>I have the following process stats that I have captured using Python's psutil (see attached <a href="http://www.sharecsv.com/s/ac97ffed30f5225769e543e99f77f173/process_stats.csv" rel="nofollow noreferrer">csv</a>). I am trying to use Pandas and Matplotlib to slice this dataframe such that I can plot all several proc... | <p>If you want to graph the time and memory usage separated by nucleus, you can use the following code</p>
<pre><code>process_data['create_time']=pd.to_datetime(process_data['create_time'], infer_datetime_format=True)
process_data.set_index('create_time', inplace=True)
for i in process_data['cores'].unique().tolist():... | pandas|matplotlib|indexing|numpy-slicing | 0 |
5,064 | 62,728,575 | ValueError: codes need to be array-like integers when extracting X and Y from dataframes | <p>I'm trying to learn more about dataframes by using a reproducible examples of arrays. What i'm doing is trying to extract from my reproducible example the values X and y from my dataframe with my classes enumerated where first 5 rows are features from class A and last 5 rows are features from class B.</p>
<p>My actu... | <p><strong>Orignal Answer:</strong></p>
<p>First you should refer to this <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Categorical.from_codes.html" rel="nofollow noreferrer">documentation</a>.</p>
<p>According to the documentation <code>class_A</code> can be called <code>0</code> and <code... | python|python-3.x|pandas|numpy|dataframe | 0 |
5,065 | 53,541,156 | How to remove all occurrences of an element from NumPy array? | <p>The title is pretty self-explanatory: I have an numpy array like (let's say ints)
<code>[ 1 2 10 2 12 2 ]</code> and I would like to remove all occurrences of <code>2</code>, so that the resulting array is <code>[ 1 10 12 ]</code>. Preferably I would like to do this as fastest as possible, because I am using relativ... | <p>You can use indexing:</p>
<pre><code>arr = np.array([1, 2, 10, 2, 12, 2])
print(arr[arr != 2])
# [ 1 10 12]
</code></pre>
<p>Timing is pretty good:</p>
<pre><code>from timeit import Timer
arr = np.array(range(5000))
print(min(Timer(lambda: arr[arr != 4999]).repeat(500, 500)))
# 0.004942436999999522
</code></pre> | arrays|python-3.x|numpy|scipy | 7 |
5,066 | 53,763,147 | How to write strings into a csv file | <p>I am trying to create a csv file with a single column of file paths. I need a second column filled with ones.</p>
<p>The result I want to get is as follows;</p>
<pre><code>./1/a_1.csv, 1
./1/a_2.csv, 1
./1/a_3.csv, 1
</code></pre>
<p>The code I tried is this;</p>
<pre><code>import numpy as np
data=np.chararray(... | <p>You don't need Numpy for this. Just do something like</p>
<pre><code>with open('a.csv', 'w') as outf:
for i in range(650):
print('./1/a_%s.csv, 1' % (i + 1), file=outf)
</code></pre>
<p>and you're golden.</p> | python|python-3.x|csv|numpy | 5 |
5,067 | 46,157,646 | Python sort multi dimensional dict | <pre><code>input={11: {'perc': 0, 'name': u'B test', 'cid': 11, 'total': 0, 'pending': 0, 'complete': 0}, 10: {'perc': 0, 'name': u'C test', 'cid': 10, 'total': 0, 'pending': 0,'complete': 0}, 3: {'perc': 9, 'name': u'Atest Pre-requisites', 'cid': 3, 'total': 11, 'pending': 10, 'complete': 1}}
</code></pre>
<p>I want ... | <p>First, you should avoid using reserved words (such as <code>input</code>) as variables (now <code>input</code> is redefined and no longer calls the function <code>input()</code>).</p>
<p>Also, a dictionary cannot be sorted. If you don't need the keys, you can transform the dictionary into a list, and then sort it. ... | python|python-2.7 | 0 |
5,068 | 54,993,747 | How to append every nth in a sequence? | <p>If I have a list:</p>
<pre><code>["a1", "b1", "c1", "a2", "b2", "c2", "a3", "b3", "c3"]
</code></pre>
<p>and I want to make a new list like:</p>
<pre><code>["a1", "a2", "a3", "b1", "b2", "b3", "c1", "c2", "c3"]
</code></pre>
<p>I am trying to do this in a for loop so that I'm appending to a new list in sequence:... | <p>You could stride though the sequence with desired offsets, the use <code>itertools</code> to flatten back into a 1D list.</p>
<pre><code>>>> import itertools
>>> d = ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'a3', 'b3', 'c3']
>>> list(itertools.chain.from_iterable([d[::3], d[1::3], d[2::3]]))... | python | 5 |
5,069 | 33,223,922 | Python append value at array increment to a list | <p>Let's say I have a list of lists:</p>
<pre><code>name_list = ['John', 'Smith'], ['Sarah', 'Nichols'], ['Alex', 'Johnson']
</code></pre>
<p>I have another arbitrary list, let's say of colors:</p>
<pre><code>color_list = ['Red', 'Green', 'Blue']
</code></pre>
<p>What's the simplest or most efficient way of appendi... | <p>You can <code>itertools.cycle</code> a slice of the list:</p>
<pre><code>name_list = [['John', 'Smith'], ['Sarah', 'Nichols'], ['Alex', 'Johnson']]
color_list = ['Red', 'Green', 'Blue']
from itertools import cycle, islice
i = 2
cyc = cycle(islice(color_list, 0, i))
for sub in name_list:
sub.append(next(c... | python | 4 |
5,070 | 73,629,204 | Python Exception Handling - BMI CALCULATOR | <p>I am coding a BMI calculator in python and wanted to add exception handling.
I created two functions 1. a height converter that converts the height to feet or meters depending on the user's input, and a weight converter that converts the user's weight to kg or pounds depending on the input. The def height_converter(... | <p>In your weight_converter function you are only going to return the converted value when the user enters bad input. In Python the indention determines in which code block the statement will belong. You need to put the return statement at the same indention level as your while True: That puts it outside the while lo... | python|exception|try-catch | 0 |
5,071 | 21,539,435 | python 'in' operator returning the wrong value | <p>I ran into a weird issue with the 'in' operator for python, which is reproduced from the ipython shell below:</p>
<pre><code> In [119]: Teff = 10000
In [120]: loggs = numpy.arange(4.5, 4*numpy.log10(Teff) - 15.02, -0.1)
In [121]: 4.0 in loggs
Out[121]: False
In [122]: loggs
Out[122]:
... | <p>The problem is that <code>4.0</code> is not in the array. A value very close to 4.0, but slightly off (due to floating point inaccuracies) is in the array, and when you print it, the printing routine is rounding to "4.0" for display purposes.</p>
<p>If you print out the actual element (<code>loggs[5]</code>), pyth... | python | 7 |
5,072 | 40,928,798 | Write to file Python, error? | <p>I tried to write in file:</p>
<pre><code> f = open('parsed.txt', 'w')
f.write(url + '\n' + title + '\n' + email + '\n\n')
</code></pre>
<p>But I get error:</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/Brand Cream/AppData/Local/Programs/Python/Python35/index.py", line 122, in parsePage
f... | <p>You probably have a function called <code>open</code> in an other place of your code which takes only one argument. This is why you get this error.</p> | python|python-3.x|beautifulsoup | 5 |
5,073 | 38,424,151 | How to scrape the number of followers from a URL | <p>I have a list of artists in an excel file with the urls of all their social medias accounts (Facebook, Instagram, Soundcloud, Twitter and Youtube).Is there any fast way to <strong>scrape</strong> the number of followers for each account and report it in the excel file? I have more than 2000 artists so it will be ver... | <p>If </p>
<ol>
<li>You don't have previous expriences in making a spider.</li>
<li>Some of these sites required login for viewing those number.</li>
<li>You only have to do this for one-time.</li>
</ol>
<p>You may checkout <a href="http://selenium-python.readthedocs.io/getting-started.html#simple-usage" rel="nofollo... | python|database|excel|web-scraping|social-media | 0 |
5,074 | 40,305,933 | How to add motion blur to numpy array | <p>I have a numpy array from image</p>
<p>So, is there a good way to do so:<code>
from PIL import Image
a = Image.open('img')
a = a.filter(MOTION_BLUR)
</code></p> | <pre><code>import cv2
import numpy as np
img = cv2.imread('input.jpg')
cv2.imshow('Original', img)
size = 15
# generating the kernel
kernel_motion_blur = np.zeros((size, size))
kernel_motion_blur[int((size-1)/2), :] = np.ones(size)
kernel_motion_blur = kernel_motion_blur / size
# applying the kernel to the input im... | python|image|python-imaging-library|blur | 11 |
5,075 | 39,921,087 | a = open("file", "r"); a.readline() output without \n | <p>I am about to write a python script, that is able to read a txt file, but with readline() there is always the \n output. How can i remove this from the variable ? </p>
<pre><code>a = open("file", "r")
b = a.readline()
a.close()
</code></pre> | <p>That would be:</p>
<pre><code>b.rstrip('\n')
</code></pre>
<p>If you want to strip space from each and every line, you might consider instead:</p>
<pre><code>a.read().splitlines()
</code></pre>
<p>This will give you a list of lines, without the line end characters. </p> | python | 50 |
5,076 | 29,216,208 | unconverted data remains: .387000 in Python | <p>I have a datetime that is a string I read from a text file. I want to trim the extra milliseconds off of it, but I want to convert it to a datetime variable first. This is because it may be in different formats depending on what is in the text file. How ever, everything I have tried wants me to already know the f... | <p>You are doing it backwards. Try this:</p>
<pre><code>from datetime import datetime
mytime = "2015-02-16 10:36:41.387000"
myTime = datetime.strptime(mytime, "%Y-%m-%d %H:%M:%S.%f")
myFormat = "%Y-%m-%d %H:%M:%S"
print "Original", myTime
print "New", myTime.strftime(myFormat)
</code></pre>
<p>result:</p>
<pre><c... | python|strftime|strptime | 31 |
5,077 | 8,881,191 | Kill hanging function in Python in multithreaded enviorment | <p>I would like to kill a function that executes to long. What is important this function is <em>inside C extension (wrapped in Cython)</em>, and I would like this solution to work in multithreaded enviorment. Since it is wrapped in Cython this thread could hold GIL. </p>
<p>I have no control whatsoever on what is hap... | <p>My solution is to wrap this function in another python process and if needed kill that process. </p>
<p>A piece of advice for anyone who googles this question: since process startup time (starting interpreter, loading modules and then loading data into memory) can last couple of seconds you need to group your funct... | python|multithreading|cython|cpython | 1 |
5,078 | 51,807,934 | select an image to show with dialog | <p>How do I select an image to show using dialog? I only can show an image when I know it's exact path. But I want to be like that dialog when you upload your photo to social networks or something. Now I have this code:</p>
<pre><code>from tkinter import *
from PIL import ImageTk, Image
root = Tk()
img = Image.open(... | <p>You use the Tkinter FileDialog, let the user choose the image and use that location as string for your image <a href="http://effbot.org/tkinterbook/tkinter-file-dialogs.htm" rel="nofollow noreferrer">http://effbot.org/tkinterbook/tkinter-file-dialogs.htm</a></p> | python|tkinter | 1 |
5,079 | 18,903,911 | Tkinter color-chooser window focus | <p>I have three windows:</p>
<ul>
<li>Root window</li>
<li>Toplevel window</li>
<li>Color-chooser window.</li>
</ul>
<p>The root window has a menu command that opens the toplevel. The toplevel has a button that opens the color-chooser.</p>
<p>When the color-chooser button is pressed and the color-chooser opens, some... | <p>You aren't telling the color dialog which window it belongs to, so by default it attaches itself to the root window. With some window managers this will cause the parent window to be raised to the top of the stacking order.</p>
<p>Try passing in the <code>parent</code> attribute, giving it a value of the toplevel w... | python|user-interface|tkinter | 3 |
5,080 | 62,446,387 | Python I can't open file 'app.py' in flask | <p>I was using flask to develop a Python project. It was working fine to start the backend program via <code>python3 app.py</code> under the <code>backend_code/</code> directory.
However, when I tried it today, it showed </p>
<pre><code>my_user_namedeMBP:backend_code my_user_name$ python3 app.py
* Serving Flask app ... | <p>I have the same sort of error, using Dash app (which is based on Flask).</p>
<p>As far as I got is that it could be related to <code>sys.path.append</code> in my several <code>.py</code> files. But if I do not have this path appended I cannot load some functions in other folder (which is a DB helper).</p>
<p>Anybody... | python|python-3.x|linux|flask|backend | 1 |
5,081 | 67,425,731 | How to number each consecutive night in a pandas dataframe using python | <p>In Python 3x I have some filled lists and I have put these in a pandas dataframe with 'ID' and 'Time' as columns:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'ID': ID, 'UTCTime': UTCTime})
print(df)
ID UTCTime
3 4 2021-04-03 21:56:53
4 5 2021-04-03 21:56:55
5 6 2021-04-03 21:56:57... | <p>Let's try something like this:</p>
<pre class="lang-py prettyprint-override"><code># Ensure UTCTime is DateTime
df['UTCTime'] = pd.to_datetime(df['UTCTime'])
# Mask To get Times We're interested in
m = (18 <= df['UTCTime'].dt.hour) | (df['UTCTime'].dt.hour < 6)
# Shift Values Between Start and End Time so tha... | python|pandas|indexing | 0 |
5,082 | 67,374,762 | $pip command gets ImportError: No module named typing | <p>When I am trying to run the following command:</p>
<p><code>$ pip</code></p>
<p>I get:</p>
<pre><code>Traceback (most recent call last):
File "/usr/bin/pip", line 9, in <module>
from pip import main
File "/home/ssm-user/.local/lib/python2.7/site-packages/pip/__init__.py", line 1, in... | <p>Turns out the issue is the same as <a href="https://stackoverflow.com/questions/65869296/installing-pip-is-not-working-in-python-3-6/65871131#65871131">this</a>. I followed the solution and downgraded pip and that solves the issue.</p> | python|pip | 1 |
5,083 | 36,592,729 | Writing the output of a python script in a Hadoop table using Hive's TRANSFORM command | <p>I need to use a python script within a Hive query in order to transform data from a Hadoop table (mytable1) and writing the output of the transformation into another table (mytable2), because the data I need is in a complicated JSON. The transformation should take 1 line from mytable1 and write 360 lines in mytable2... | <p>Not sure which version of python you are using.
But you can write to Hive from CSV file using OS library.
Below is the code</p>
<pre><code>import os;
output.to_csv('/home/output.csv',sep='\t', index=False, encoding='utf-8')
load_statement = "hive -e \"LOAD DATA LOCAL INPATH '/home/output.csv' OVERWRITE INTO TABL... | python|hadoop|hive | 1 |
5,084 | 36,247,335 | why my flask-pagedown can't has a newline why I write code by markdown? | <p><a href="https://i.stack.imgur.com/gn6ar.png" rel="nofollow noreferrer">demo</a>
like this,it use <code>{{ pagedown.include_pagedown() }}</code> to preview,but it can't have a newline,why and how to solve ?
Here's my code.</p>
<pre><code>class Post(db.Model):
__tablename__ = 'post'
id = db.Column(db.Integer... | <p>CODE BLOCKS</p>
<p>Pre-formatted code blocks are used for writing about programming or markup source code. Rather than forming normal paragraphs, the lines of a code block are interpreted literally. Markdown wraps a code block in both and tags.
<strong><em>To produce a code block in Markdown, simply indent every ... | python|flask | 0 |
5,085 | 19,365,573 | wxPython: Binding Multiple Widgets to the Same Handler | <p>I have created a huge code and my program is a bit slow,I want to ask if there is a way to bind multiple widgets into the same handler...see below some parts of my code</p>
<pre><code> self.button=AB.AquaButton(self,label="Sensor 1",pos=(10,10),size=(90,35))
self.Bind(wx.EVT_BUTTON, self.OnButton, self.butto... | <p>Yes you can bind multiple widgets to the same handler. You just need to assign a name to each of the widgets or a unique id. I recommend the name because you don't want to accidentally use a system id to one of your widgets. Anyway, I wrote an article that explains it all here:</p>
<ul>
<li><a href="http://www.blog... | python-2.7|wxpython|wxwidgets|wxtextctrl | 3 |
5,086 | 13,529,945 | POS tagging - NLTK thinks noun is adjective | <p>In the following code, why does nltk think 'fish' is an adjective and not a noun?</p>
<pre><code>>>> import nltk
>>> s = "a woman needs a man like a fish needs a bicycle"
>>> nltk.pos_tag(s.split())
[('a', 'DT'), ('woman', 'NN'), ('needs', 'VBZ'), ('a', 'DT'), ('man', 'NN'), ('like', 'IN'... | <p>If you used a Lookup Tagger as described in the <a href="http://nltk.org/book/ch05.html" rel="nofollow">NLTK book, chapter 5</a> (for example using WordNet as lookup reference) first, your tagger would already "know" that <em>fish</em> cannot be an adjective. For all words with several possible POS Tags you could th... | python|nltk | 4 |
5,087 | 22,186,343 | What permission should set to the directory to avoid Permission Denied? | <p>I'm using python manage.py runserver in development mode and getting </p>
<pre><code>IOError at /cmanager/upload/save
[Errno 13] Permission denied: u'/tmp/temp/IMG_27022014_183050.png'
</code></pre>
<p>Once I run the <code>chmod -R 775 "/tmp/temp/"</code>, it works. But on every shutdown/restart of computer, that ... | <p>It is not good to set permissions with <code>os.chmod</code> inside your script, because you can not escalate priveleges any higher than whatever the process itself has. </p>
<p>I don't think you should be using <code>os</code> module at all here. Use builtin <code>tempfile</code> module for a tried-and-tested cr... | python | 1 |
5,088 | 22,380,409 | How is the number of levels in a 3D-contour-plot set? | <p>Having an array witch looks like this plotting it as surface:
<img src="https://i.stack.imgur.com/h31UV.jpg" alt="Surface"></p>
<p>plotting the same array as 3D-contour it only shows 5 levels. Where is set how many levels it shows, and how can I change it?</p>
<p><img src="https://i.stack.imgur.com/v4kFg.jpg" alt... | <p>In the <a href="http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#contour-plots" rel="nofollow">tutorial</a>, the function contour passes the arguments to <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.contour" rel="nofollow">axes.contour</a>. There it is explained how to set the levels... | python|matplotlib | 3 |
5,089 | 16,864,591 | A pattern where a class has a number of similar methods (same type signature, similar semantics) | <p>It's hard to describe this in the abstract, so let me just give a (simplified & snipped) example:</p>
<pre><code>class ClassificationResults(object):
#####################################################################################################################
# These methods all represent aggregate... | <p>Why don't you simply store the actual methods in the list and avoid calls to <code>getattr</code> altogether?</p>
<pre><code>>>> class SomeClass(object):
...
... def method_one(self):
... print("First!")
... return 0
...
... def method_two(self):
... print("Second!... | python|design-patterns|introspection | 2 |
5,090 | 43,668,002 | Creating a .txt file of file directories | <p>I am trying to create a .txt file of file directories at a location, remove the prefixes and save the text file.</p>
<p>I use the <code>os.walk</code> module to build a list of directories of a location into a .txt file. I always get the text file of the directories.</p>
<p>The part where it removes the prefixes o... | <p>you've mixed up the variable names, actually I'd expect that if run it would raise some exceptions. </p>
<ul>
<li>you have <code>trim_output</code> for both the output file and the trimmed line</li>
<li>you are calling <code>remove_prefix</code> on the "input_file_object" not on the <code>line</code></li>
<li>you g... | python|python-2.7 | 0 |
5,091 | 54,541,962 | How to add calculated column to Dataframe counting frequency in column in pandas | <p>I have dataframe like this:</p>
<pre><code> county
1 N
2 N
3 C
4 N
5 S
6 N
7 N
</code></pre>
<p>and what I'd like to reach is:</p>
<pre><code> county frequency
1 N 5
2 N 5
3 C 1
4 N 5
5 S 1
6 N 5
7 N 5
</code></pre>
<p>Is t... | <p>Map the values from value_counts to the column</p>
<pre><code>df['frequency'] = df['county'].map(df['county'].value_counts())
county frequency
1 N 5
2 N 5
3 C 1
4 N 5
5 S 1
6 N 5
7 N 5
</code></pre> | python|pandas|dataframe|countif | 14 |
5,092 | 54,276,908 | python selenium autocomplete search issue | <p>I am trying to fill up an autocomplete zipcode / town form. Even if you input the whole zipcode / town in once you still must validate the autocomplete search (just under the input).I do not put the whole error messages for each attempt otherwise my post would be too long (I put a number for each attempt and --> to ... | <p>using WebdriverWait try clicking the <code>li</code> element</p>
<pre><code>wait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//li[@class="selected" and contains(., "Toulouse")]'))
).click()
</code></pre>
<p>also try with different condition like <code>presence_of_element_located</code> or <code>v... | python|selenium | 0 |
5,093 | 54,458,259 | call dictionary from one function to another | <p>How can I call a dictionary created in one function to another?</p>
<p>I have tried using <a href="https://stackoverflow.com/questions/40251960/how-do-i-access-a-dictionary-from-a-function-to-be-used-in-another-function">How do I access a dictionary from a function to be used in another function?</a> but it doesn't... | <p>Use <code>return</code> and call <code>server</code> from within <code>create_csv</code>. This may necessitate feeding <code>id_</code> to <code>create_csv</code>, but this is likely reasonable, as presumably <code>dictionary1</code> is constructed based on <code>id_</code>.</p>
<pre><code>def server(id_):
# so... | python|python-3.x|csv|dictionary | 3 |
5,094 | 54,418,900 | I want to repeat my code x amount of time what should i do? | <pre><code>import time
import ctypes
for count in (3000):
def Mbox(title, text, style):
return ctypes.windll.user32.MessageBoxW(0, text, title, style)
Mbox('Virus detected', 'Would you like to run your anti-viruse software?',6)
</code></pre> | <p>This will work for you.</p>
<pre><code>import time
import ctypes
def Mbox(title, text, style):
return ctypes.windll.user32.MessageBoxW(0, text, title, style)
for count in range(3000):
print(Mbox('Virus detected', 'Would you like to run your anti-viruse software?',6))
</code></pre> | python | 2 |
5,095 | 71,289,957 | How to call specific some function right after calling __init__ in Python? | <p>Here is an example class <code>Permit</code>:</p>
<pre><code>class Permit(object):
def __init__(self):
super(Permit, self).__init__()
# init todo list
self.todo = [1,2,3,4,5]
</code></pre>
<p>What I wanna do:</p>
<ul>
<li>register some new elements in <code>self.todo</code> list, but not ... | <p>You can add additional "constructors" in Python by using class methods that instantiate an instance of the class and perform modifications to that instance</p>
<pre><code>class Permit(object):
def __init__(self):
super(Permit, self).__init__()
# init todo list
self.todo = [1,2,3... | python|init|metaclass | 2 |
5,096 | 9,047,908 | Swap the elements of two sequences, such that the difference of the element-sums gets minimal. | <p>An interview question: </p>
<blockquote>
<p>Given two non-ordered integer sequences <code>a</code> and <code>b</code>, their size is n, all
numbers are randomly chosen: Exchange the elements of <code>a</code> and <code>b</code>, such that the sum of the elements of <code>a</code> minus the sum of the elements o... | <p>Revised solution:</p>
<ol>
<li><p>Merge both lists x = merge(a,b).</p></li>
<li><p>Calculate median of x (complexity O(n) See <a href="http://en.wikipedia.org/wiki/Selection_algorithm" rel="noreferrer">http://en.wikipedia.org/wiki/Selection_algorithm</a> )</p></li>
<li><p>Using this median swap elements between a a... | c++|python|algorithm|data-structures | 8 |
5,097 | 47,903,168 | Starting Jmeter server with python script, base directory | <p>I need to start JMeter-server on target host with some python script. Jmeter has temporary directory like <strong><em>/tmp/jmeter-3sc0ppq5/</em></strong>. Inside the script, I have some BeanShell which is creating a file and it`s needed to have appeared in his own base directory in <strong><em>bin/</em></strong> dir... | <p>A good practice is to send the base directory as property and use it when needed.</p>
<p>You can send in <a href="http://jmeter.apache.org/usermanual/get-started.html#options" rel="nofollow noreferrer">JMeter command line</a> using as</p>
<pre><code>-JbaseDir=/tmp/jmeter-3sc0ppq5/
</code></pre>
<p>In <a href="http:/... | python|jmeter | 0 |
5,098 | 47,896,617 | How do you delete rows with a certain object in pandas, python? | <p>I have a column in my data that contains these kind of values</p>
<p>2</p>
<p>2</p>
<p>yes</p>
<p>2</p>
<p>yes</p>
<p>In python pandas how would I identify the entire row containing a string of letters and then delete or drop the entire row?</p>
<p>Thanks</p> | <p>IIUC:</p>
<pre><code>df = df[~pd.to_numeric(df['col'], errors='coerce').isna()]
</code></pre>
<p>or</p>
<pre><code>df = df[pd.to_numeric(df['col'], errors='coerce').notna()]
</code></pre> | python|pandas|jupyter-notebook | 1 |
5,099 | 37,368,179 | pyramid beaker + Sessionauthenticationpolicy how they work? | <p>For my webapp I use beaker and sessionauthenticationpolicy.
When looking at pyramid.security I noticed that the "remember" function of "sessionauthenticationpolicy" return an empty list so I can't set a cookies
on the response returned to the user(in the login view) to track him based on
his "userid" the next time ... | <p>You can read the user id from the session store on the server side. Often applications also expose <code>request.user</code> attribute: <a href="https://github.com/websauna/websauna/blob/master/websauna/system/__init__.py#L201" rel="nofollow">https://github.com/websauna/websauna/blob/master/websauna/system/<strong>i... | python|pyramid|beaker | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.