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 |
|---|---|---|---|---|---|---|
1,100 | 46,019,109 | Django trying to add up values in the django template | <p>Hi Guys I am trying to figure this out but not having any luck.</p>
<p>So I am showing my events in the homepage which shows how many seats are available, once the user has made a booking I would like to minus that from the amount showing on the homepage.</p>
<p>But I am already stuck at adding all the values up f... | <p>Generally, purpose of templates is not to implement logic. All the logic should go into your views. I would recommend you to do that in your views and either store it in a dict or a list and send it to front-end. </p>
<p>Once the user made a booking, if you want to modify the value on the HTML without reloading, yo... | django|python-2.7 | 0 |
1,101 | 24,482,618 | In an MVC model, where is the position of http handlers? | <p>I'm developing Python tornado apps in MVC. I have a folder for models which contains all of classes to access database. another for controller which contains classes to do some controls an more logical works. the problem is that I don't know exactly where to put my HTTP handlers. should I put them in View folder of ... | <p>You can take example from Django, which use model named MTV (Model-Template-View) - you can read more about this <a href="http://www.djangobook.com/en/2.0/chapter05.html#the-mtv-or-mvc-development-pattern" rel="nofollow">here</a> or in <a href="https://docs.djangoproject.com/en/dev/faq/general/#django-appears-to-be-... | python|model-view-controller|tornado | 0 |
1,102 | 41,073,612 | Sorting dictionary inside a dictionary python | <p>Im trying to sort this dictionary from highest number to lowest number. However I tried to sort the dictionary, but every time the error of :
TypeError: string indices must be integers
keeps coming up. This is what I coded </p>
<pre><code>aurl_params = {}
dayum = requests.get(starturl, params = aurl_params)
lis... | <p>Use the following approach to get the needed result:</p>
<pre><code>newlist = sorted(liste['data'], key=lambda o: o['media_count'], reverse=True)
print(newlist)
</code></pre>
<p>The sequence that need to be sorted is <code>liste['data']</code></p> | python|sorting|dictionary | 0 |
1,103 | 38,109,126 | Kivy kv file is not working | <p>I have the same issue like described in this theme <a href="https://stackoverflow.com/questions/34748579/kivy-using-a-screenmanager-from-kv-file/38109098#38109098">kv incorrect</a>. When I use Builder and load the kv file I have normal working app. But when I try to use autoload kv file I have only black screen. Cou... | <p>In your <code>kv</code> file, you define <code>ScreenManagement</code> to be the root element with its associated screens. But in <code>build</code>, you return a newly created <code>ScreenManagement</code> object, which will not have any children defined.</p>
<p>Solution:
Define <code>build</code> as </p>
<pre><c... | python|kivy|kivy-language | 2 |
1,104 | 39,993,460 | Why does pandas dataframe indexing change axis depending on index type? | <p>when you index into a pandas dataframe using a list of ints, it returns columns.</p>
<p>e.g. <code>df[[0, 1, 2]]</code> returns the first three columns.</p>
<p>why does indexing with a boolean vector return a list of rows?</p>
<p>e.g. <code>df[[True, False, True]]</code> returns the first and third rows. (and er... | <p>Because if use:</p>
<pre><code>df[[True, False, True]]
</code></pre>
<p>it is called <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> by mask:</p>
<pre><code>[True, False, True]
</code></pre>
<p>Sample:</p>
<pre><code>df = pd.D... | python|pandas | 2 |
1,105 | 43,546,139 | Odoo: OSError: [Errno 2] No such file or directory | <p>Trying to re-install Odoo
Did the following steps:</p>
<ol>
<li>Deleted the previous odoo dir</li>
<li>Deleted previous postgres users and databases, except the user which I was using and that user created databases</li>
<li>Tried the regular user and database creation in postgres</li>
</ol>
<p>But once I try to i... | <p>Try to find the Odoo configuration file. This file contains directory name where Odoo looks up for the modules. In this case, your Odoo settings are left behind after deletion of the Odoo. Delete or modify this file accordingly to your new Odoo installation.</p>
<p>Where to look: for different platforms (Linux-Wind... | python|postgresql|openerp|postgresql-9.1|odoo-10 | 1 |
1,106 | 52,825,652 | How to reorder a dataframe based on a list? pandas | <p>I have a df and I want to reorder it based on athe list as shown using Python:</p>
<pre><code>df=pd.DataFrame({'Country':["AU","DE","UR","US","GB","SG","KR","JP","CN"],'Stage #': [3,2,6,6,3,2,5,1,1],'Amount':[4530,7668,5975,3568,2349,6776,3046,1111,4852]})
</code></pre>
<p>df</p>
<pre><code>list=["US","CN","GB","... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Categorical.html" rel="noreferrer"><code>pd.Categorical</code></a></p>
<pre><code>list_ = ["US","CN","GB","AU","JP","KR","UR","DE","SG"]
df['Country'] = pd.Categorical(df.Country, categories = list_, ordered = True)
df.sort_values(by='Count... | python|pandas|list|dataframe|reorderlist | 6 |
1,107 | 38,532,831 | Replacing cells in a column, but not header, in a csv file with python | <p>I've been looking for a few hours now and not found what I'm looking for...</p>
<p>I'm looking to make a program that takes an already compiled .csv file with some information missing and asking the user what they would like to add and then placing this in the csv but not effecting the header line. Then saving the ... | <ol>
<li>We open the input file and the output file with a python context manager.</li>
<li>get the user input using <code>input()</code> (python 3) or <code>raw_input()</code> (python 2) functions</li>
<li>grab the 1st row in the file and write it out without changing anything and write that out</li>
<li><p>Loop throu... | python|csv | 1 |
1,108 | 37,076,808 | How to dynamically visualize dataset on web? | <p>I am developing a website where I have around 800 data sets. I want to visualize my data using bar charts and pie charts, but I don't want to hard code this for every data set. What technology can I use to dynamically read the data from a json/csv/xml and render the graph? (btw I'm going to use a Python based backen... | <p>Js library like d3.js or highcharts can be helpful to solve your problem. You can easily send the data from sever to front-end where these library can gracefully plot the data.</p> | javascript|python|dynamic|data-visualization | 0 |
1,109 | 36,947,619 | Is it possible to use query parameters on the Django Admin Site | <p>I work with multi-tenancy and am passing the <code>schema name</code> through a query parameter. My <code>middleware</code> takes care of the parameter and sets the correct schema. It works very well on my API requests (direct <strong>posts</strong> and <strong>gets</strong>), but now I need to access the admin page... | <p>Was just working on the same problem.</p>
<p>Problem is that django admin catches any uknown(unregistered via some filter on admin view) query params and if any found raises exception which redirects</p>
<p>Solution is to call something like that inside middleware:</p>
<pre><code>def extract_client_id_from_admin_... | python|django|django-rest-framework|multi-tenant|query-parameters | 0 |
1,110 | 48,524,527 | How do global variables work in recursion? | <pre><code>count=0
global count
def fact(n):
count+=1
if n==1:return 1
else:return(n*fact(n-1))
print(fact(5))
</code></pre>
<p>When the variable count is declared as global, is the variable count accessible in all recursive frames?</p>
<p>The above code doesn't work, however the below code works. Can som... | <p><code>count += 1</code> is a <em>local</em> assignment that shadows the global <code>count</code>. It doesn't matter that there is a global variable available to increment. You have to declare the global in order for the assignment to affect the global.</p>
<p>Using the <code>global</code> keyword outside the funct... | python|python-3.x|python-2.7 | 3 |
1,111 | 48,020,008 | django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'message' used in key specification without a key length") | <p>I am trying to create a model using <code>django 1.11</code> and <code>mysql</code>(latest) as my backend using <code>mysqlclient</code>. I have searched various blogs and docs but was still not able to find my solution.
This is my code Posts.models.py
Please forgive the indentation error here if any.</p>
<pre><cod... | <p>Set length to the text field. It did work for me. Like</p>
<pre><code>models.TextField(max_length=1000)
</code></pre> | python|mysql|django|django-models | 0 |
1,112 | 69,927,721 | How to drop the columns in pandas with multiple condtions | <p>I am new to python and pandas</p>
<p>On the below data frame ,I need to the drop the columns which are totally "None" , with "blanks and None", but not the columns with values and None</p>
<p><a href="https://i.stack.imgur.com/TsPy0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.c... | <p>You can test missing values <code>NaN</code> and <code>None</code> like <code>Nonetype</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isna.html" rel="nofollow noreferrer"><code>DataFrame.isna</code></a>, then possible strings by <a href="http://pandas.pydata.org/pandas... | python|pandas|dataframe | 5 |
1,113 | 72,950,659 | How to access prediction from another python module? | <p>I have a file <em>file_calling_class.py</em> that needs to access the prediction value from another python module in <em>file_with_class.py</em>. However, I do not know how to access the prediction. The function alone works fine if it is the only script but if I want to pass the <em>budget</em> value from <em>file_c... | <p>You are not invoking the <code>.calculate_sales()</code> method in your call. Try changing <code>sales = file_with_class.CalcSales(budget=budget).__str__()</code> in <code>file_calling_class.py</code> to:</p>
<pre class="lang-py prettyprint-override"><code>sales = file_with_class.CalcSales(budget=budget).calculate_s... | python|python-module|self | 1 |
1,114 | 55,788,627 | Keras `steps=None` error even when using Sequence class | <p>I am trying to do some custom training with Keras with Tensorflow backend. I am using the <code>fit_generator()</code> to supply data. My generator is a derived class of <code>keras.utils.Sequence</code>. </p>
<pre><code>gen = PitsSequence( PITS_PATH,nP=nP, nN=nN, n_samples=n_samples, initial_epoch=initial_epoch, i... | <p>I think your problem lies in the combination of <code>use_multiprocessing=True</code> and <code>workers=0</code>. If you look at the <a href="https://keras.io/models/sequential/#fit_generator" rel="nofollow noreferrer">documentation</a> you can read about their settings. Hope that helps.</p> | python|python-2.7|tensorflow|keras|deep-learning | 0 |
1,115 | 64,634,431 | How to save a randonly generated image with Python? | <p>I'm trying to solve a CAPTCHA on a <a href="https://www.list-org.com/bot" rel="nofollow noreferrer">website</a>.</p>
<p>< img src="/kcap.php?PHPSESSID=iahvgmjcb93a0k7fqrf43sq9sk" ></p>
<p>Html-code contains a redirect to php-generated img. But, if i try to follow this <a href="https://www.list-org.co... | <p>The image changing is being done at the server side, if you need a copy of this image you will need to save the image at the point of the page loading.</p>
<p>Looking at the data these images are JPEG's, this will download the image from that link,</p>
<pre class="lang-py prettyprint-override"><code>import urllib.re... | python|php|image|parsing|captcha | 1 |
1,116 | 53,248,761 | How can I make python tts.sapi speak asynchronously? | <p>Here is the text to speech code I use in my voicebot program :</p>
<pre><code>import tts.sapi
voice = tts.sapi.Sapi()
def say(text):
voice.say(text)
</code></pre>
<p>It works great but the thing is I want to be able to interrupt the function if needed.
I mean being able to execute other commands while it spe... | <p>Using the tts.sapi wrapper, you'll need to set up an event loop and event interests (so that SAPI will call you back). Instead, you might want to look at the <a href="https://pypi.org/project/pyttsx/1.0/" rel="nofollow noreferrer">pyttsx</a> package. It appears to support async speaking. </p> | python|text-to-speech|voice|sapi | 0 |
1,117 | 68,740,357 | Do I need to load the weights of another class I use in my NN class? | <p>I have a model that needs to implement self-attention and this is how I wrote my code:</p>
<pre><code>class SelfAttention(nn.Module):
def __init__(self, args):
self.multihead_attn = torch.nn.MultiheadAttention(args)
def foward(self, x):
return self.multihead_attn.forward(x, x, x)
... | <blockquote>
<p>In other words, is this necessary?</p>
</blockquote>
<p>In short, <strong>No</strong>.</p>
<p>The <code>SelfAttention</code> class will be automatically loaded if it has been registered as a nn.module, nn.Parameters, or manually registered buffers.</p>
<p>A quick example:</p>
<pre><code>import torch
imp... | python|pytorch|artificial-intelligence | 1 |
1,118 | 67,513,214 | What is bias node in googlenet and how to remove it? | <p>I am new to deep learning, i want to build a model that can identify similar images, i am reading <a href="https://arxiv.org/pdf/1811.12649.pdf" rel="nofollow noreferrer">classification is a Strong Baseline for Deep Metric Learning</a> research paper. and here is they used the phrase: <code>"remove the bias ter... | <p>To compute the layer n outputs, a linear neural network computes a linear combination of the layer n-1 output for each layer n output, adds a scalar constant value to each layer n output (the bias term), and then applies an activation function. In pytorch, one could disable the bias in a linear layer using:</p>
<pre... | deep-learning|neural-network|computer-vision|pytorch | 2 |
1,119 | 67,580,053 | Pandas GroupBy columns to get 'mode' | <p>Dataset as beloe and I want to aggregate the by 'Name' and 'Weeks' to get their mode.</p>
<p>I tried 2 ways but neither worked:</p>
<pre><code>import pandas as pd
from io import StringIO
csvfile = StringIO("""
Name Weeks Sales
Amelia 202106 57
Amelia 202105 61
Amelia 202106 59
Amelia 2021... | <p>TRY:</p>
<pre><code>from statistics import mode
mode = df.groupby(['Name', 'Weeks'])['Sales'].apply(mode)
</code></pre>
<pre><code>Name Weeks
Amelia 202103 49
202104 95
202105 61
202106 57
Elijah 202103 97
202104 89
202105 40
202106 49
Jam... | pandas|dataframe|statistics | 1 |
1,120 | 71,252,050 | Generating multiple strings by replacing wildcards | <p>So i have the following strings:</p>
<pre><code>"xxxxxxx#FUS#xxxxxxxx#ACS#xxxxx"
"xxxxx#3#xxxxxx#FUS#xxxxx"
</code></pre>
<p>And i want to generate the following strings from this pattern (i'll use the second example):
Considering #FUS# will represent 2.</p>
<pre><code>"xxxxx0xxxxxx0xxxxx&qu... | <pre><code>import re
stringV1 = "xxx#FUS#xxxxi#3#xxx#5#xx"
stringV2 = "XXXXXXXXXX#FUS#XXXXXXXXXX#3#xxxxxx#5#xxxx"
regex = "(#FUS#|#DSP#|#([0-9]|[1-9][0-9]|[1-9][0-9][0-9])#)"
WILDCARD_FUS = "#FUS#"
RANGE_FUS = 3
def getSignalsFromWildcards(app, can):
sigList = list()
... | python|regex|string|replace|wildcard | 0 |
1,121 | 71,115,300 | Django FileField file does not open correctly | <p>In my django app i create a model with a fiels of type FileField for store some documents:</p>
<pre><code>...
device_file = models.FileField(upload_to='uploads/')
...
</code></pre>
<p>in my <code>settings.py</code> i have:</p>
<pre><code>STATIC_URL = 'mqtt_site/static/'
MEDIA_ROOT='mqtt_site/static/media/'
</code><... | <p>Media and static shouldn’t share the same folder.</p> | python|django|django-admin | 0 |
1,122 | 63,383,479 | How to find identical rows of two arrays with different size? | <p>I have two arrays with different size</p>
<pre><code>a = np.array([[5, 0], [2, 4], [0, 1], [3, 4], [1, 5], [5, 6], [7, 9]])
b = np.array([[0, 3], [5, 6], [2, 5], [2, 4]])
</code></pre>
<p>I need</p>
<pre><code>c = np.array([False, True, False, False, False, True, False])
</code></pre>
<p>i.e. array 'b' have rows [5,... | <p>Let's try broadcasting:</p>
<pre><code>(a[None,:] == b[:,None]).all(-1).any(0)
</code></pre>
<p>Output:</p>
<pre><code>array([False, True, False, False, False, True, False])
</code></pre> | python-3.x|numpy | 2 |
1,123 | 61,162,553 | How to best print dictionaries created from user defined instance variables? | <p>I am trying to organize my cows into a dictionary, access their values, and print them to the console.</p>
<p>Each instance of a cow is assigned to an index in list cow.</p>
<p>I am attempting to create a dictionary as follows:</p>
<pre><code>for i in cows:
cowDict[i.getName] = (i.getWeight, i.getAge)
</code>... | <p>getName is a function so try </p>
<pre><code>for i in cows:
cowDict[i.getName()] = (i.getWeight(), i.getAge())
</code></pre> | python|dictionary|oop|repr | 1 |
1,124 | 61,130,312 | Generate Test data using TfIdfVectorizer | <p>I have separated my data into train and test parts. My data table has a 'text' column. Consider that I have ten other columns representing numerical features. I have used TfidfVectorizer and the training data to generate term matrix and combine that with numerical features to create the training dataframe. </p>
<pr... | <p>you can use <code>transform</code> method of trained vectorizer for transforming your test data on already trained vectorizer. you can reuse the trained vectorizer for test data set TF-IDF score generation by</p>
<pre class="lang-py prettyprint-override"><code>tfidf_vectorizer_test = tfidf_vectorizer.transform(X_te... | python|scikit-learn|tfidfvectorizer | 0 |
1,125 | 72,726,518 | open all the text files in a folder | <p>i have this code that takes in a text folder and takes the 25th element in the first line of the file and place it in the 7th. However, this code opens only one text file and writes it to another but what i want that the code reads all the files in the folder and writes them in the same path.</p>
<pre><code>index= 1... | <p>I like to use the <code>glob</code> module for things like this. See if this helps:</p>
<pre class="lang-py prettyprint-override"><code>import glob
all_text_files = glob.glob("*.txt")
for text_file in all_text_files:
with open(text_file, "r") as f:
lines = f.readlines()
# do ... | python | 2 |
1,126 | 59,396,099 | Openpyxl yields TypeError on saving file, why? | <p>since the last package update the following code does not run any more. (This is an example, i have a couple of scripts that unfortunately require this functionality) The following code snippet is the simplest example i can imagine which worked before.</p>
<p>Current specs:
Win10 64bit,
Python 3.7.5 64bit,
IPython ... | <p>I got the same problem. It seems to be a bug of new version openpyxl package. You need to roll back to older version to get it work or you can switch to xlsxwriter & xlrd packages.</p>
<p>Check these posts for more information:
<a href="https://stackoverflow.com/questions/59168758/the-function-to-excel-of-panda... | anaconda|openpyxl|python-3.7 | 0 |
1,127 | 63,023,314 | Gaussian NB vs LDA in scikit learn | <p>From my understanding, if we only have one feature, then Gaussian NB (naive bayes classification) and LDA (Linear Discriminant Analysis) should give the same result.</p>
<p>But I didn't succeed with scikit learn.</p>
<p>First I generate some toy data</p>
<pre><code>from sklearn.datasets import make_blobs
X, y = make... | <p>The main high-level difference between GNB, LDA and QDA when there are two classes <code>C1</code> and <code>C2</code> is as follows:</p>
<p>GNB : assumes covariance of <code>X</code> under classes <code>C1</code> and <code>C2</code> are different, but the off-diagonal elements are <code>0</code>.</p>
<p>QDA : assum... | python|scikit-learn|lda|naivebayes | 2 |
1,128 | 35,745,811 | Python script to copy some messages from slack which were posted in some time range | <p>I want to write a python script using some slack API's which will be able to copy some messages which were pasted between say 10AM to 11AM in a <code>channel A</code> & then paste the same messages in a different <code>channel B</code>.</p>
<p>I know that it's easy to write a message in slack via a python scrip... | <p>One way would be to use Requests (or any http client you like) with this endpoint: <a href="https://api.slack.com/methods/channels.history" rel="nofollow">https://api.slack.com/methods/channels.history</a></p>
<p>This returns a list of messages for a given channel that you can filter with the <code>oldest</code> an... | python|slack-api|slack | 2 |
1,129 | 42,884,938 | Client side to connect to sybase IQ using Python3 | <p>I am using Ubuntu and I want to connect to a sybase IQ server (remote) from my client machine ,I tried installing/using sqlanydb according to sybase documentation, but i don't see any parameter in sqlanydb.connect() related to IP of the sybase server. I think this routine imagines that sybase db is on localhost, ... | <p>You do need to install the client software. The python driver is basically a python interface to the dbcapi client library, so you can't use it without the client software installed on the machine.</p>
<p>For connecting to a remote server, you can use the HOST parameter. The <code>connect()</code> function takes as... | python|python-3.x|sybase|sap-iq | 4 |
1,130 | 65,779,244 | What does the "scale" parameter in scipy.stats.t.std() stand for? | <p>My goal is, to find the standard deviation of a dataset with a supposed t-distribution to calculate the survival function given a quantile.
As the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.t.html" rel="nofollow noreferrer">documentation</a> of scipy.stats is very counter intuitive to ... | <p>Student's T distribution is not supposed to be shifted or scaled, it's used as a standard distribution with mean=0, usually to test the difference between two means of normally distributed populations <a href="https://en.wikipedia.org/wiki/Student%27s_t-distribution" rel="nofollow noreferrer">https://en.wikipedia.or... | python|scipy|scipy.stats | 1 |
1,131 | 51,113,475 | Python 'delete' class ids for graph theory program in tkinter | <p>I am writing a program, that is able to create vertices and edges with 'onclick'. In my menu I have an option 'New' that should clean the canvas in order to start anew. </p>
<p>I am creating vertices with create_oval and as far as I understood every object gets a class id 1,2,3,... if I press now the button for new... | <p>The tkinter canvas does not re-use ids. If you create an item with an id of 1 and then delete it, the next item will have an id of 2. This is one of the reasons why the canvas has performance problems if you repeatedly create and delete many objects. </p> | python|user-interface|tkinter | 0 |
1,132 | 34,947,637 | Perform method of action chains does not work | <p>I have a case where I need to drag and drop an element using Selenium webdriver and Python.</p>
<p>I tried using the <code>ActionChains</code> class of the Selenium, the code somewhat looks like this:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
so... | <p>The <code>source</code> and <code>target</code> need to be <code>WebElement</code> instances:</p>
<pre><code>source = webdriver_api.find_element_by_xpath("//span[text()='user1']")
target = webdriver_api.find_element_by_xpath("//span[text()='user2']")
acs = ActionChains(webdriver_api)
change = acs.drag_and_drop(sou... | python|selenium | 0 |
1,133 | 45,118,710 | Fill in values between given indices of 2d numpy array | <p>Given a numpy array,</p>
<pre><code>a = np.zeros((10,10))
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, ... | <p>You can use <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>broadcasting</code></a> -</p>
<pre><code>r = np.arange(10)[:,None]
out = ((start <= r) & (r <= end)).astype(int)
</code></pre>
<p>This would create an array of shape <code>(10,len(start)<... | python|numpy | 10 |
1,134 | 44,884,013 | uploading files from python to GCS | <p>I'm able to list the buckets of GCS from Python boto.
Able to copy files to GCS using gsutil command.
Able to download files from GCS to compute instance using python API.
I have followed steps from below document. </p>
<p><a href="https://cloud.google.com/storage/docs/xml-api/gspythonlibrary" rel="nofollow norefer... | <p>That generally happens when you did not include the storage scopes in the access scopes when you set up the vm. Unfortunately you cannot change them after you start the vm, you will need to recreate it.</p>
<p><a href="https://cloud.google.com/compute/docs/access/service-accounts#accesscopesiam" rel="nofollow nore... | python-2.7|google-cloud-platform|google-cloud-storage|google-compute-engine | 1 |
1,135 | 69,657,376 | Gstreamer adding dynamic demuxer element chains | <p>We have multiple cameras that send muxed RTP and RTCP to the same port of a video processor. In this example I just use raw video frames to make it simple, later it will be H.264 that I hope to decode on the GPU.</p>
<p>With gst-launch I get it to work:</p>
<pre><code>gst-launch-1.0 rtpbin name=rtpbin funnel name=fr... | <p>So it turns out I missed that any new elements added to a pipeline needs to be set to playing. I had miss-read the documentation that indicated that all elements of a pipeline are in the same state. Here are the changes that make it work:</p>
<pre><code> def _demuxer_new_pad(self, demuxer, pad):
name = pa... | python|gstreamer | 0 |
1,136 | 58,282,421 | how to mark the x axis more than 8 points in pyplot polar | <p>I want to mark my plot as 24 hours and i need to mark every hour.
I tried the following code, but the plot only divide into 8 and only mark upto 7.</p>
<pre><code>theta = np.arange(0, 360 + 360 / 144, 360 / 144) * np.pi / 180
fig1 = plt.figure()
ax1 = fig1.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
ax1.set_ylim(0, ... | <p>You can set everything between 0 and 2*np.pi like : </p>
<pre><code>fig1 = plt.figure()
ax1 = fig1.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
ax1.set_xlim((0,2*np.pi))
tick_array=np.arange(0,2*np.pi+2*np.pi/24,2*np.pi/24)
label_array=np.arange(1,25)
ax1.set_xticks(tick_array)
ax1.set_xticklabels(label_array)
</c... | python|matplotlib | 1 |
1,137 | 55,042,989 | Pandas - Merge rows on column A, taking first values from each column B, C etc | <p>I have a dataframe, with recordings of statistics in multiple columns.
I have a <code>list</code> of the column names: <code>stat_columns = ['Height', 'Speed']</code>.
I want to combine the data to get one row per <code>id</code>.
The data comes sorted with the newest records on the top. I want the most recent data,... | <p>For me your solution working, maybe is necessary replace empty values to <code>NaN</code>s:</p>
<pre><code>df_stats = df_path.replace('',np.nan).groupby('id', as_index=False).first()
print (df_stats)
id Index Height Speed
0 100007 0 54.0 8.3
1 100014 5 44.0 NaN
2 100035 4 ... | python|pandas | 3 |
1,138 | 54,866,675 | Eclipse can't find library for compiled executable | <p>In Eclipse 4.10.0 I'm working on a Python script that calls a C++/CUDA executable (that I wrote and compiled myself too with Nsight) at one point via <code>subprocess.call()</code>. This causes an error message: <code>error while loading shared libraries: libcufft.so.10.0: cannot open shared object file: No such fil... | <p>I found the answer <a href="https://stackoverflow.com/a/19977247/5522601">here</a>: In the Python project's run configuration, go to the Environment tab and add the path variable (in my case <code>LD_LIBRARY_PATH</code>) with the value of the directory of the library (in my case <code>/usr/local/cuda/lib64</code>).<... | python|eclipse | 1 |
1,139 | 38,263,027 | Pycharm debug watch: Can I show directly an image | <p>Similar to the functionality available in Visual Studio I'd like to have a look at some of the variables in my code as images using PyCharm Community Edition 2016.1.4. </p>
<p>In my case it's a mask that is applied to an image later on, that I want to visually check during debug when hitting a breakpoint.
So far I ... | <p>I had similar problems, so I've just created OpenCV Image Viewer Plugin, which works as you expect. You can install it to any JetBrains IDE, which support Python (directly or via plugin).</p>
<p><a href="https://plugins.jetbrains.com/plugin/14371-opencv-image-viewer" rel="nofollow noreferrer">https://plugins.jetbrai... | python|pycharm|opencv3.0 | 2 |
1,140 | 44,196,084 | How to call an API in Flask Restplus? | <p>I'm trying to figure out how can I call an API using Flask-Restplus (normally, I'd just use API key, as it always was possible - let's say the easiest example is weather). I know how I can do it in Flask, but have no idea how can I do it in Restplus. There are tons of documentations, but mostly about working with lo... | <p><a href="http://flask-restplus.readthedocs.io/en/stable/" rel="nofollow noreferrer">Flask-RESTPlus</a> package deals with creating and exposing APIs. If you need to access external APIs within your application you are suppose to use <a href="http://docs.python-requests.org/en/master/" rel="nofollow noreferrer">Reque... | python|python-requests|api-design|flask-restplus | 1 |
1,141 | 44,208,077 | boolean indexing to store a column value as a variable in python | <p>Let's say I have a CSV file which reads </p>
<pre><code>Student_Name Grade
Mary 75
John 65
Stella 90
</code></pre>
<p>I'd like to store Stella's grade as a variable.
My current code looks like:</p>
<pre><code>import pandas as pd
student_grades = pd.read_csv('.../Term2grades.csv')
x = student_grades.lo... | <p>Access the underlying numpy array and take its first element (assuming you have a single element):</p>
<pre><code>student_grades.loc[student_grades['Student_Name'] == "Stella", 'Grade'].values[0]
Out: 90
</code></pre>
<p>You can also use <code>iat</code> or <code>iloc</code> on the returning Series:</p>
<pre><co... | python|csv|pandas|variables|import | 1 |
1,142 | 41,717,358 | how to add matrices as values in a dictionary? | <p>I have a dictionary which its values are matrices and its keys are the most frequent words in the train file. I have a test file, I have to see if the words in each line of that are in the dictionary it gets their values which are matrices and add the matrices and then divide them to the number of words. the answer ... | <p>The <code>val</code> is an <code>numpy.array</code> and you can use the sum() function: <code>val.sum()</code></p> | python|python-3.x|dictionary|matrix|nlp | 0 |
1,143 | 36,226,831 | Django Rest creating Nested-Objects (ManyToMany) | <p>I looked for an answer to this question specifically for Django Rest, but I haven't found one anywhere, although I think a lot of people have this issue. I'm trying to create an object with multiple nested relationships but something is keeping this from happening. Here are my models for reference:</p>
<pre><code>... | <p>I think <code>favorite.items.add</code> expects you to pass in a single instance of an <code>Item</code>, so you should replace this:</p>
<pre><code>for item in favorites_data:
favorite.items.add(item)
</code></pre>
<p>With this:</p>
<pre><code>for key in favorites_data:
for item in favorites_data[key]:
... | python|django|post|django-rest-framework | 1 |
1,144 | 35,882,219 | Python: is using decorator to change method arguments a bad thing? | <p>I implemented a decorator to change a class method's arguments in this way:</p>
<pre><code>def some_decorator(class_method):
def wrapper(self, *args, **kargs):
if self._current_view = self.WEAPON:
items = self._weapons
elif self._current_view = self.OTHER:
items = self._o... | <p>Yeah, I think in this case, more explicit is better. Why not leave the decorators off and just use for-loops in the method itself:</p>
<pre><code>def update_status(self, status):
for item in self.items:
item.update_status(status)
def refresh(self):
for item in self.items:
item.refresh()
</... | python | 2 |
1,145 | 29,732,812 | How to export queryset in Django 1.7 to xls file? | <p>I using Django 1.7.1 with Python 3.4. I would like to export search results to Excel file.
I have this function in view.py</p>
<pre><code>def car_list(request):
page = request.GET.get('page')
search = request.GET.get('search')
if search is None:
cars= Car.objects.filter(plate__isnull = False ... | <p>Passing <code>mimetype</code> to <code>HttpResponse</code> is deprecated and removed in Django 1.7</p>
<p>You have to use <code>content_type</code></p> | python|django|django-templates|django-views | 1 |
1,146 | 46,278,288 | Git - Should Pipfile.lock be committed to version control? | <p>When two developers are working on a project with different operating systems, the <code>Pipfile.lock</code> is different (especially the part inside <code>host-environment-markers</code>).</p>
<p><a href="https://stackoverflow.com/questions/12896780/should-composer-lock-be-committed-to-version-control">For PHP, mo... | <p>Short - Yes!</p>
<p>The lock file tells pipenv exactly which version of each dependency needs to be installed. You will have consistency across all machines.</p>
<p>// update: <a href="https://github.com/pypa/pipenv/issues/598" rel="noreferrer">Same question on github</a></p> | python|pip|pipenv | 85 |
1,147 | 46,202,315 | Pandas: Adding column via arithmetic on all matching indexes | <p><strong>Edit: Added a row with no matched index to demonstrate expected behavior</strong></p>
<p>I have the following two DataFrames:</p>
<p><code>requests</code>:</p>
<pre><code> requests
asn pop country
1 1 us 100
br 50
2 br 200
3 hk 150
4 uk ... | <p>There is problem your <code>MultiIndex</code> not matched, so get <code>NaN</code>s. solution is add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>reindex</code></a>.</p>
<pre><code>requests['network'] = traffic["total"].div(traffic["c... | python|pandas|dataframe | 3 |
1,148 | 49,570,464 | Error importing mnist dataset from tensorflow and ssl certificate error anaconda | <p>I have no idea what the problem is. I am trying to import the mnist data set from the tensorflow examples and I am finding it very difficult to proceed.</p>
<p>So far: I saw the SSL certifications error, so I tried the following:
1. pip remove certified and pip install certified
2. read a lot to fix the SSL error, ... | <p>I just had same issue like you, and resolved by run /Applications/Python 3.6/Install Certificates.command....just double click that :-) </p>
<p>FYI:
It's a Python 3.6 on MacOSX has no certificates at all (see the release notes), so it cannot verify the SSL certificate from GitHub's servers when trying to downlo... | tensorflow|ssl-certificate|anaconda|mnist | 1 |
1,149 | 49,512,644 | How to use "incorrect" JSON in python3 | <p>I have a JSON file in the following format - </p>
<p>Note the characters after 1 and 2 (etc) represent strings written without double quotes</p>
<pre><code>{
"Apparel": {
"XX": {
"1": YY,
"2": ZZ
},
"TT": {
"1":TTT,
"2":TTT,
... | <p>I understand from the question that the values of your JSON <strong>are not surrounded by quotation marks</strong>.</p>
<p>I wrote the following script that parses <strong>that specific file</strong> from the question:</p>
<pre><code>#!/usr/bin/env python3
from json import dumps
# Reads THAT SPECIFIC MALFORMATT... | python|json|io|python-3.5 | 1 |
1,150 | 21,388,484 | polyfit refining: setting polynomial to be always possitive | <p>I am trying to fit a polynomial to my data, e.g.</p>
<pre><code>import scipy as sp
x = [1,6,9,17,23,28]
y = [6.1, 7.52324, 5.71, 5.86105, 6.3, 5.2]
</code></pre>
<p>and say I know the degree of polynomial (e.g.: 3), then I just use scipy.polyfit method to get the polynomial of a given degree:</p>
<p>+++++++++++... | <h2>Always Positve</h2>
<p>I haven't been able to find a scipy reference that determines if a function is positive-definite, but an indirect way would be to find the all the roots - <a href="http://docs.scipy.org/doc/scipy/reference/optimize.nonlin.html" rel="nofollow">Scipy Roots</a> - of the function and inspect the... | python|machine-learning|scipy|constraints|data-fitting | 0 |
1,151 | 21,122,382 | modifying part of a list in place using list comprehensions in python | <p>I have a list that looks like </p>
<pre><code>test = ['A','B','C','D D','E E','F F']
</code></pre>
<p>I would like test to become the following (that is, the spaces removed)</p>
<pre><code>test = ['A', 'B', 'C', 'DD', 'EE', 'FF']
</code></pre>
<p>I used a list comprehension in Python to achieve this:</p>
<pre><... | <p>First of all, it sounds like you're optimizing prematurely.</p>
<p>Secondly, you can express your requirements with a single list comprehension:</p>
<pre><code>In [5]: test = ['A','B','C','D D','E E','F F']
In [6]: [t if i < 3 else re.sub(' ', '', t) for (i, t) in enumerate(test)]
Out[6]: ['A', 'B', 'C', 'DD',... | python|list | 3 |
1,152 | 54,758,510 | How to transform these output into a matrix format | <p><a href="https://i.stack.imgur.com/E9tcd.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E9tcd.jpg" alt="enter image description here"></a></p>
<p>I wrote a code that displays a 4x4 tkinter entry widget. So when I input the values in each entry boxes and after pressing the "Matrix Form" button to... | <p>You can use the command <code>np.reshape</code>, for example, for your case </p>
<p><code>np.reshape(YOUR_ARRAY, (4, 4))</code></p>
<p>would get you the desired output</p> | python | 0 |
1,153 | 33,105,887 | Best way to parse sections of json in python3 to separate items in list | <p>First off, I'm having trouble Googling this question since I don't know all of the terminology (so really, giving me the proper terms to use in my Google search would be just as useful in this question).</p>
<p>I have some JSON that I need to parse in python, put each JSON string in a list after its been parsed(Lis... | <p>Here's how you can iterate over that data, converting each dict in the <code>"components"</code> list back into JSON strings:</p>
<pre><code>import json
data = '''
{
"components": [
{
"self": "MY URL",
"id": "ID",
"name": "NAME",
"description": "THIS IS D... | python|json|python-3.x | 3 |
1,154 | 12,687,277 | Python deep nesting factory functions | <p>Working through "Learning Python" came across factory function. This textbook example works:</p>
<pre><code>def maker(N):
def action(X):
return X ** N
return action
>>> maker(2)
<function action at 0x7f9087f008c0>
>>> o = maker(2)
>>> o(3)
8
>>> maker(2)
&... | <p>You get a <code>TypeError</code> because function <code>func</code> doesn't return anything (thus its return is <code>NoneType</code>). It should return <code>subfunc</code>:</p>
<pre><code>>>> def superfunc(X):
... def func(Y):
... def subfunc(Z):
... return X + Y + Z
.... | python|function|factory | 4 |
1,155 | 12,937,175 | Sublime Text 2 plugin won't show up in Command Platte | <p>I started writing a Plugin for <strong>Sublime Text 2</strong>.</p>
<p>I created a new folder in "Packages/RailsQuick"</p>
<p>And Created 2 files:</p>
<p><strong>RailsQuick.py</strong></p>
<pre><code>import sublime, sublime_plugin
class GeneratorsCommand(sublime_plugin.WindowCommand):
def run(self):
self.... | <p>My lucky guess:</p>
<p>Your class name is wrong. <code>GeneratorsCommand</code> should match the one defined in <code>RailsQuick.sublime-commands</code> (<code>rails_quick_generators</code>). Sublime Text 2 needs to have 1:1 mapping between these names, otherwise it cannot know which plug-in belongs to which shortc... | python|plugins|sublimetext2 | 4 |
1,156 | 21,719,842 | Copying a key/value from one dictionary into another | <p>I have a dict with main data (roughly) as such: <code>{'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com}</code></p>
<p>and I have another dict like: <code>{'UID': 'A12B4', 'other_thing: 'cats'}</code></p>
<p>I'm unclear how to "join" the two dicts to then put "other_thing" to the main dict. What I need is... | <p>you want to use the <code>dict.update</code> method:</p>
<pre><code>d1 = {'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com'}
d2 = {'UID': 'A12B4', 'other_thing': 'cats'}
d1.update(d2)
</code></pre>
<p>Outputs:</p>
<pre><code>{'email': 'hi@example.com', 'other_thing': 'cats', 'UID': 'A12B4', 'name': 'John'... | python|dictionary | 32 |
1,157 | 21,736,479 | python virtualenv.el no longer works in emacs after updating python-mode | <p>I upgraded from <code>python-mode.el-6.1.2</code> to <code>python-mode.el-6.1.3</code> and my <code>M-x virtualenv-activate venvname</code> no longer activates the virtual environment in my emacs <code>*Python*</code> buffer. This same keystroke used to load the virtualenv. </p>
<p>My process for updating python-... | <p>I haven't maintained
<a href="https://github.com/aculich/virtualenv.el" rel="nofollow">my virtualenv</a> package in a
long time since I use docker and LXC for a better virtual environment
for my development purposes that provides stronger isolation,
first-class network interfaces, and support for non-python stacks.<... | python|emacs|virtualenv | 1 |
1,158 | 41,091,490 | Comparing three arrays | <p>I would like to ask, why this is returning 'True' (or what is the code doing when it is written like this): </p>
<pre><code>def isItATriple(first,second,third):
if first[0] == second[0] == third[0] or first[0] != second[0] != third[0]:
if first[1] == second[1] == third[1] or first[1] !=second[1] != third[1]:
... | <p>Let analyze:</p>
<p>first if: </p>
<pre><code>if first[0] == second[0] == third[0] or \
first[0] != second[0] != third[0]:
</code></pre>
<p>The first (before or) is True - because at 0 index all lists have 0;
If so - the condition after or is not checked (because python is lazy) <code>True or Anything</co... | python|arrays|if-statement|boolean|conditional-statements | 1 |
1,159 | 28,948,477 | Have researched the RE module without finding a solution | <p>Using python 2.7.5 and the following string. I am trying to sum and with the following code. Can someone steer me in the right direction? Thanks</p>
<pre><code><msg><src>CC128-v0.15</src><dsb>01068</dsb><time>09:19:01</time><tmprF>68.9</tmprF><sensor>0&l... | <p>This looks like an XML-like language, I'd strongly recommend using the XML libraries instead of regexes to parse it. </p>
<p>The problem in your code is this part:</p>
<pre><code>watts = str(int(watts_ex.findall(data)[0]))
</code></pre>
<p>You're just using result <code>0</code> from the <code>findall()</code>, I... | python | 0 |
1,160 | 8,453,946 | Can I edit XML loaded by xml.dom.minidom.parse? | <p>As I saw, when we run</p>
<pre><code>from xml.dom.minidom import parse
myXML = parse('anything.xml')
</code></pre>
<p>in a Python script, it loads the contents of "anything.xml", until you leave the script or <kbd>Ctrl+D</kbd> your Python session.</p>
<p>Is it possible to add attribute values to this loaded versi... | <p>The <code>parse</code> method returns you an instance of <code>xml.dom.minidom.Document</code>, on which you can invoke the plethora of methods listed in the documentation of <code>xml.dom</code>. Here's a small example:</p>
<pre><code>import xml.dom.minidom
d = xml.dom.minidom.parseString('<head>hello</h... | python|xml|parsing|caching | 3 |
1,161 | 8,890,320 | Get Plain text from a QLabel with Rich text | <p>I have a <code>QLabel</code> that contains rich text.<br>
I want to extract just the actual (visible) 'text' from the <code>QLabel</code>, and none of the code for formatting.<br>
I essentially need a function similiar to the <code>'.toPlainText'</code> method of other <code>Qt Widgets</code>.</p>
<p>I can not simp... | <p>Use a <a href="https://doc.qt.io/qt-4.8/qtextdocument.html" rel="noreferrer"><code>QTextDocument</code></a> to do the conversion:</p>
<pre><code>doc = QtGui.QTextDocument()
doc.setHtml(label.text())
text = doc.toPlainText()
</code></pre> | python|qt|pyqt|pyqt4|qlabel | 19 |
1,162 | 8,841,609 | Migrations across databases with inconsistend database backend - Input? | <p>I am migration some data from one database to another, it is production data that has accidentally ended up in a testing database.</p>
<p>It is typical a relational database centered around a single User table.</p>
<h3>Things to consider</h3>
<ul>
<li>Duplicate rows between <em>production</em> and <em>testing</em... | <p><strong>1.</strong> Backup all the data first. It never hurts to say this!</p>
<p><strong>2.</strong> Establish a reasonable sample size, i.e. how many records are you willing to look at in details, partly based on your time/money and the value of corrected accurate data.</p>
<p><strong>3.</strong> Create a list, ... | python|sql|soap|artificial-intelligence|suds | 1 |
1,163 | 8,493,100 | Python error with debugging | <p>I am very new with Python and I have just received this message while trying to use Visual Studio plugin for Python:</p>
<pre><code>try:
import boinc # getting the exception here
_BOINC_ENABLED = True
except:
_BOINC_ENABLED = False
</code></pre>
<p>and this is the error message that I get:</p>
<blockq... | <p>problem was that my project was not on the root of my hard drive and
the project was inside a folder named in hebrew.
the path of the folder containning the project must be in english for it to work</p> | python | 0 |
1,164 | 52,146,642 | How to scrape a webpage which has login if we have the credentials using python scrapy? | <p>Just want to know how to send request along with the login credentials to a login page to fetch the data.</p> | <p>It is usual for web sites to provide pre-populated form fields through elements, such as session related data or authentication tokens (for login pages). When scraping, you’ll want these fields to be automatically pre-populated and only override a couple of them, such as the user name and password. You can use the ... | python-2.7|scrapy-spider | 1 |
1,165 | 51,802,902 | rate_limit not working celery | <p>i have a simple structure:</p>
<ul>
<li><p>proj</p>
<ul>
<li>celery.py</li>
<li>tasks.py</li>
</ul></li>
<li>run_tasks.py</li>
</ul>
<p>celery.py:</p>
<pre><code>from __future__ import absolute_import, unicode_literals
from celery import Celery
app = Celery('proj',
broker='amqp://',
backend='a... | <p>From <a href="http://docs.celeryproject.org/en/latest/userguide/tasks.html#Task.rate_limit" rel="nofollow noreferrer">Celery Docs</a>:</p>
<blockquote>
<p>Note that this is a per worker instance rate limit, and not a global rate limit. To enforce a global rate limit (e.g., for an API with a maximum number of requ... | python|python-3.x|celery | 3 |
1,166 | 59,547,540 | Python Error:Commands out of sync; you can't run this command now | <p>Here is the scenario,
I am facing the error </p>
<pre><code>Error:Commands out of sync; you can't run this command now
</code></pre>
<p>I need to pass the string to MYSQL which is a mixture of double and Single quotes. But when the mysql parsing the string it couldnt process the parameters because Python converti... | <p>Based on searching past Stack Overflow questions related to the error:</p>
<blockquote>
<p>Commands out of sync; you can't run this command now</p>
</blockquote>
<p>This problem is caused by executing multiple SQL statements in the same call to <code>execute()</code>. You can't do that unless you pass the argume... | python|mysql|python-3.x|string | 0 |
1,167 | 63,697,794 | Python if-elif-else expressions returning a value and scope resolution | <p><strong>Question 1</strong></p>
<p>In rust, I can write code like this:</p>
<pre><code>let foo = if ... {
1
} else if ... {
2
} else {
3
};
</code></pre>
<p>Here foo is assigned the return value of that if-elseif-else expression.</p>
<p>Is something similar possible in Python?</p>
<p><strong>Question 2</strong... | <p>it seems the closest Py version is a ternary op</p>
<pre><code>#scenario 2
foo = "hello"
foo = "world" if True else foo
print(foo) # prints 'world'
</code></pre> | python | 1 |
1,168 | 36,427,782 | exception handling in python for a beginner | <pre><code>def flatten(nstd_list):
for item in nstd_list:
try:
yield from flatten(item)
except TypeError:
yield item
</code></pre>
<p>I am a beginner for python, can you here please explain me how does this work(step by step) </p> | <p>you can take <code>yield</code> as <code>return</code>, so the code is to get every single element from a nested list.</p>
<p>for example:</p>
<p>nstd_list = [[1],2]</p>
<p>first round: item is [1] and 2, so <code>yield flatten([1])</code> and <code>2</code></p>
<p>second round: item is 1, and return <code>1</co... | python|exception | 0 |
1,169 | 19,769,799 | GAE timeout when query DNS | <p>I'm trying to use a script to check if an email exists or not. For that I'm using DNS queries. This is the call that fails:</p>
<pre><code>from dns import resolver
mx_data = resolver.query(hostname, 'MX', source='')
</code></pre>
<p>It works if I execute the script standalone with python but it fails when it runs ... | <p>As Tim said, you need to set the resolver explicitly.</p>
<p>Example code:</p>
<pre><code>import dns.resolver
resolver = dns.resolver.Resolver()
resolver.nameservers = ['8.8.8.8']
mx_data = resolver.query(hostname, 'MX')
</code></pre>
<p>Note that 8.8.8.8 is googles dns server, but could be any other.</p>
<p>Al... | python|google-app-engine|sockets|dns | 0 |
1,170 | 19,349,690 | Multi-threaded websocket server on Python | <p>Please help me to improve this code:</p>
<pre><code>import base64
import hashlib
import threading
import socket
class WebSocketServer:
def __init__(self, host, port, limit, **kwargs):
"""
Initialize websocket server.
:param host: Host name as IP address or text definition.
:pa... | <blockquote>
<p>In CPython, the global interpreter lock, or GIL, is a mutex that
prevents multiple native threads from executing Python bytecodes at
once.</p>
</blockquote>
<p>So your code won't work. You can use <a href="http://docs.python.org/2/library/multiprocessing.html" rel="nofollow">processeses</a> inste... | python|multithreading|websocket | -1 |
1,171 | 21,953,892 | How to include rpm dependency in setup.py | <p>I'm new to python but i want to create rpm package by using setuptools and bdist_rpm option.
The problem I've occurred is how to include dependencies to other rpm (c/c++ binaries libraries).</p> | <p>You need to add the dependencies to the Requires section, see <a href="http://docs.python.org/2/distutils/builtdist.html#creating-rpm-packages" rel="nofollow">distutils documentation</a>.</p> | dependencies|rpm|setuptools|python-2.6 | 3 |
1,172 | 54,677,806 | Matplotlib - animate PIL images in Jupyter | <p>How can I create an animation in Jupyter using PIL images?</p>
<p>I'm creating drawings with PIL. Here is the code for one frame (other frames are generated by just increasing theta)</p>
<pre><code>import matplotlib.pyplot as plt
import math
from PIL import Image, ImageDraw
width, height = 800,800
theta = math.pi... | <p>I would advocate for doing the whole animation in matplotlib directly, since that is more memory efficient (no need to create store 100 images) and gives a better graphics quality (because pixels would not need to resampled).</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib import a... | python|matplotlib|jupyter-notebook | 1 |
1,173 | 39,277,078 | PyGTK-2.24.0 Installation cannot find NumPy | <p>I am trying to build the PyGTK source from version 2.24.0 with a local (prefix=$HOME/.local) installation of python 3.5.2. Running the configure script produces:</p>
<pre><code>$: ./configure --prefix=$HOME/.local
....
configure: WARNING: Could not find a valid numpy installation, disabling.
....
The following modu... | <p>I'm afraid you have some mix-up.
Here is what I did :</p>
<pre><code>sudo apt-get dist-upgrade
sudo apt-get install python3
sudo apt-get install python3-numpy
sudo apt-get install python3-matplotlib
sudo apt-get install python3-scipy
sudo apt-get install python3-pyfits
</code></pre>
<p>One can also use <code>pip... | python|numpy|makefile|pygtk|configure | 1 |
1,174 | 55,394,788 | how to fill missing time slots in python? | <p>I'm trying to fill the missing slots in the CSV file which has date and time as a string.</p>
<p>My input from a csv file is:</p>
<pre><code>A B C
56 2017-10-26 22:15:00 89
2 2017-10-27 00:30:00 54
20 2017-10-28 05:00:00 64
24 2017-10-29 06:00:00 2
91 2017-11-01 2... | <p>Using <code>resample</code> to get 15-min intervalsand <code>bfill</code> to fill missing values in <code>B</code>:</p>
<pre><code>df = df.set_index(pd.to_datetime(df.pop('B')))
df.loc[df.index.min().normalize()] = None
df = df.resample('15min').max().bfill()
df['A'] = 4*df.index.hour + df.index.minute//15
print(... | python|pandas|deep-learning | 1 |
1,175 | 52,827,721 | How to export data stored in GG Bigquery into GZ file. | <p>I used this code to export data into a csv file and it works:</p>
<pre><code>project_id = 'project_id'
client = bigquery.Client()
dataset_id = 'dataset_id'
bucket_name = 'bucket_name'
table_id = 'table_id'
destination_uri = 'gs://{}/{}'.format(bucket_name, 'file.csv')
dataset_ref = client.dataset(dataset_id, proje... | <p>You need to add a <code>jobConfig</code> like in:</p>
<pre><code>job_config = bigquery.job.ExtractJobConfig()
job_config.compression = 'GZIP'
</code></pre>
<p>Complete code:</p>
<pre><code>from google.cloud import bigquery
client = bigquery.Client()
project_id = 'fh-bigquery'
dataset_id = 'public_dump'
table_id ... | python-3.x|google-bigquery|export | 4 |
1,176 | 52,592,298 | send a file from a server to another server use rest framework | <p>I have a server that generates a file, I want to send that file to another server, when the file is ready.
so the server that receives file should always listen
and I have used Django rest framework, does anybody have a link to help me?</p> | <p><strong>Server A (Server receiving file from Server B)</strong></p>
<p>models.py</p>
<pre><code>class TestModel(models.Model):
# Other fields you are interested in saving
file_data = models.FileField()
</code></pre>
<p>serializers.py</p>
<pre><code>class TestModelSerializer(serializers.ModelSerializer):
... | python|django|django-rest-framework | 0 |
1,177 | 47,583,834 | Fading out a signal in numpy | <p>What is the most idiomatic way to produce a cumulative sum which "fades" out as it moves along. Let me explain with an example.</p>
<pre><code>>>> np.array([1,0,-1,0,0]).cumsum()
array([1, 1, 0, 0, 0], dtype=int32)
</code></pre>
<p>But I would like to provide a factor <code><1</code> and produce someth... | <p>Your result can be obtained by linear convolution:</p>
<pre><code>signal = np.array([1,0,-1,0,0])
kernel = 0.5**np.arange(5)
np.convolve(signal, kernel, mode='full')
# array([ 1. , 0.5 , -0.75 , -0.375 , -0.1875, -0.125 , -0.0625,
0. , 0. ])
</code></pre>
<p>If performance is a consideratio... | python|numpy | 5 |
1,178 | 52,349,503 | Error when opening Jupyter Notebook from terminal on Mac | <p>I get the following error when trying to open a Jupyter Notebook (using the command jupyter notebook) from the terminal on mac. </p>
<pre><code>Traceback (most recent call last):
File "/Applications/anaconda3/bin/jupyter-notebook", line 11, in <module>
sys.exit(main())
File "/anaconda3/lib/python3.6/s... | <p>I'm summarizing our conversations here as it helped you to resolve the problem.</p>
<p>There could be many possible options to address this issue. However, the very first approach to tackle this problem is to resolve permission issues. The last line of your error message is <code>PermissionError: [Errno 13] Permiss... | python|jupyter-notebook | 2 |
1,179 | 72,831,855 | Windows Python packages not compatible with Amazon Linux? | <p>I'm creating a layer for my lambda function by installing the dependencies locally, zipping the folder, and uploading it to S3. To ensure the packages are compatible with Lambda runtimes, I'm installing the packages like this (per the docs)</p>
<pre><code>pip install \
--platform manylinux2014_x86_64 \
--tar... | <p>The easiest way to do that is to download the library from pypi and then unzipped the file. Then, you must put the file in a folder called "python" and then, you have to zipp the folder nad upload to a layer. It must works.</p> | python|aws-lambda|pip|zbar|amazon-linux | 0 |
1,180 | 39,791,441 | Create Excel Hyperlinks in Python | <p>I am using win32com to modify an Excel spreadsheet (Both read and edit at the same time) I know there are other modules out there that can do one or the other but for the application I am doing I need it read and processed at the same time.</p>
<p>The final step is to create some hyperlinks off of a path name. Here... | <p>Borrowing heavily from <a href="https://www.experts-exchange.com/questions/21349668/Using-win32com-with-Python.html" rel="nofollow">this</a> question, as I couldn't find anything on SO to link to as a duplicate...</p>
<p>This code will create a Hyperlink in cells <code>A1:A9</code></p>
<pre><code>import win32com.c... | python|excel|python-2.7|win32com | 2 |
1,181 | 16,295,736 | How to remove elements from a list | <p>I have two lists</p>
<pre><code>first = ['-6.50', '-7.00', '-6.00', '-7.50', '-5.50', '-4.50', '-4.00', '-5.00']
second = ['-7.50', '-4.50', '-4.00']
</code></pre>
<p>I want to shorten <code>first</code> by every element that occur in <code>second</code> list.</p>
<pre><code>for i in first:
for j in second:
... | <pre><code>>>> first = ['-6.50', '-7.00', '-6.00', '-7.50', '-5.50', '-4.50', '-4.00', '-5.00']
>>> second = ['-7.50', '-4.50', '-4.00']
>>> set_second = set(second) # the set is for fast O(1) amortized lookup
>>> [x for x in first if x not in set_second]
['-6.50', '-7.00', '-6.00', ... | python|list|python-2.7 | 3 |
1,182 | 31,914,688 | python - pyodbc setting for increase package size in stored procedure params | <p>I'm using Python2.7 with <code>pyodbc==3.0.7</code> for connecting to SQL Server.</p>
<p>Everything is OK, but when I call a stored procedure with a string parameter that has 480 characters, it returns below error:</p>
<p>Code: </p>
<pre><code>cursor.execute("{CALL SP_NAME(?)}", (param))
</code></pre>
<p>Error: ... | <p>Maximum Length of <code>pyodbc</code> module is 255 characters in each transferring in Unix OS. i checked some attributes like <code>packet size</code> in "connection string" through this reference <a href="http://SQL%20Server%20connection%20strings" rel="nofollow">http://www.connectionstrings.com/sql-server/</a>, b... | sql-server|django|python-2.7|pyodbc | 0 |
1,183 | 38,685,626 | Properly creating a mouse event with Kivy | <p>I am trying to create a program that will control the mouse on on my Kivy application. What is the proper way to create a provider and send it the locations I want to move and click at?</p> | <p>Take a look at the recorder module, it can both record events and also replay them</p>
<p>Here is a small example: (change RECORD to False to watch the replay after recording ... )</p>
<pre><code>import kivy
from kivy.uix.button import Button
from kivy.app import App
from kivy.input.recorder import Recorder
rec =... | python|mouseevent|kivy|modeling | 1 |
1,184 | 51,680,405 | Dynamically add legend for arrows in matplotlib | <pre><code>import matplotlib.pyplot as plt
def plot_arrow(arrow_type):
if arrow_type == 'good_arrow':
arrow_color = 'g'
ar = plt.arrow(x, y, dx , dy, label=arrow_type, fc=arrow_color)
plt.legend([ar,], [arrow_type,])
</code></pre>
<p>The above callback function is used to draw arrows in a plot. I n... | <p>Why not just use <code>quiver()</code> in your case? See <a href="https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.quiver.html" rel="nofollow noreferrer">here</a>.</p>
<p><a href="https://i.stack.imgur.com/KJZvr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KJZvr.png" alt="enter image de... | python|matplotlib | 2 |
1,185 | 1,346,297 | Py2App Can't find standard modules | <p>I've created an app using py2app, which works fine, but if I zip/unzip it, the newly unzipped version can't access standard python modules like traceback, or os. The manpage for zip claims that it preserves resource forks, and I've seen other applications packaged this way (I need to be able to put this in a .zip fi... | <p>This is caused by building a <strong>semi-standalone</strong> version that contains symlinks to the natively installed files and as you say, the links are lost when zipping/unzipping unless the "<strong>-y</strong>" option is used.</p>
<p>An alternate solution is to build for <strong>standalone</strong> instead, wh... | python|macos|py2app | 4 |
1,186 | 63,128,862 | Import Error while running pytest in virtualenv | <p>I am trying to run my pytest (bdd) test cases in virtualenv. I have created a requirements.txt (using pip freeze) file in the root folder as below.</p>
<pre><code>apipkg==1.5
atomicwrites==1.3.0
attrs==19.1.0
behave==1.2.6
certifi==2019.6.16
chardet==3.0.4
chromedriver==2.24.1
contextlib2==0.6.0.post1
coverage==4.5.... | <p>There's an open issue with <code>pytest-yield</code> that prevents it to work with latest <code>pytest</code> version (5.1 and up): <a href="https://github.com/devova/pytest-yield/issues/6" rel="nofollow noreferrer">#6</a>. This means that you have either to downgrade to an older version of <code>pytest</code>:</p>
... | python|python-3.x|unit-testing|virtualenv|pytest | 2 |
1,187 | 32,526,834 | Place Python list in Excel column | <p>Say I have two lists in Python:</p>
<pre><code>A_List=["jim", "go"]
B_List=["kkj", "nmh",123]
</code></pre>
<p>how can I get those lists into a .csv Excel file, where in column A, A1 contains <code>jim</code>, B2 contains <code>nmh</code>, A2 contains <code>go</code>.</p>
<p>In other words, each list's items need... | <p>Use zip to create the rows. Since your lists are unequal in length, use <a href="https://docs.python.org/2/library/itertools.html#itertools.izip_longest" rel="nofollow"><code>itertools.izip_longest</code></a> to create blank entries for the end of the shorter list.</p>
<p>Use <a href="https://docs.python.org/2/libr... | python|excel|list|csv | 0 |
1,188 | 28,189,338 | passing variables in python through functions unicode error | <p>code :</p>
<pre><code>def power(base,exponent):
result = base**exponent
print "%d to the power of %d is %d." % (base, exponent, result)
n=raw_input("Enter a number whose power you wish to calculate:")
p=raw_input("Enter the power:")
power(n,p)
</code></pre>
<p>Some unicode error is coming while executing p... | <p><code>raw_input</code> returning string. You have to convert it to integer, because your function finding power of a number.</p>
<pre><code>def power(base,exponent):
result = base**exponent
print "%d to the power of %d is %d." % (base, exponent, result)
n=int(raw_input("Enter a number whose power you wi... | python | 1 |
1,189 | 44,167,920 | Python: AttributeError: 'str' object has no attribute 'font' | <p>I am using the following code to write to an excel file. Please correct me.
I am parsing an HTML page in this context. My aim is to find the table elements and write it into columns.</p>
<pre><code>for row in table.findAll('tr', { "class" : "product-row" }):
col = row.findAll('td')
i=1
Image = col[0].a.img['src']
... | <p>You are not using <a href="http://xlwt.readthedocs.io/en/latest/api.html#xlwt.Worksheet.Worksheet.write" rel="nofollow noreferrer"><code>.write()</code></a> method correctly. Provide row and column indexes followed by the data you want to write into a cell:</p>
<pre><code>record = (Image, Name, Width)
for col_inde... | python|excel | 0 |
1,190 | 34,624,189 | Python Pexpect and Check Point Gaia Expert Mode | <p>I administer a few Check Point Firewalls at work that run on the Gaia operating system. Gaia is a hardened, purpose-built Linux OS using the 2.6 kernel. </p>
<p>I am a novice at Python and I need to write a script that will enter "expert mode" from the clish shell. Entering expert mode is similar to invoking <code>... | <p>clish does not support SSH. But you can change the shell of your user to /bin/bash instead of /etc/clish.sh</p>
<pre><code>set user <myuser> shell /bin/bash
save config
</code></pre> | python|linux|security|gaia | 0 |
1,191 | 34,522,484 | How can I accelerate the array assignment in python? | <p>I am trying to make array assignment in python, but it is very slow, is there any way to accelerate?</p>
<pre><code>simi_matrix_img = np.zeros((len(annot), len(annot)), dtype='float16')
for i in range(len(annot)):
for j in range(i + 1):
score = 0
times = 0
if i != j:
x_idx = ... | <p>(1) You could use generators instead of list comprehension where possible. For example:</p>
<pre><code> x_idx = (p1 for (p1, q1) in enumerate(annot[i]) if np.abs(q1 - 1) < 1e-5)
y_idx = (p2 for (p2, q2) in enumerate(annot[j]) if np.abs(q2 - 1) < 1e-5)
</code></pre>
<p>With this, you iterate o... | python|arrays|numpy | 1 |
1,192 | 23,127,533 | Is there a generic way to create an URL template in Django? | <p>I'm looking for an easy way to compose URLs in the frontend with JavaScript. Let's take the URL patterns from the <a href="https://docs.djangoproject.com/en/dev/intro/tutorial03/#writing-more-views" rel="nofollow">Django tutorial</a> as an example:</p>
<pre><code>urlpatterns = [
# ex: /polls/
url(r'^$', vie... | <p>I've managed to hack something simple which does what I wanted, maybe it'll be useful for someone. It's a template tag which replaces named groups with <code>{{ name }}</code> sequences and takes the URL name as a single parameter. </p>
<pre class="lang-py prettyprint-override"><code>import re
from django import t... | python|django|django-urls | 0 |
1,193 | 23,265,051 | IndexError when applying setblocking(0) for a Blender3D Python script | <p>I'm currently running a script with Blender3D I ported from Python 2+ to Python 3+ with the help of someone from Stackoverflow. The script creates communication between a OMRON PLC (Programmable logic computer) and Blender/Python3+. The script uses TCP communication to write and read the PLC's memory. After the port... | <p>Your message is not long enough (sequence is shorter than 17). You should test length of frame, or use <code>zip</code> and slice to be sure, you don't try to call index that does not exist:</p>
<pre><code>tags = (b'ICF', b'RSV', b'GCT',
b'DNA', b'DA1', b'DA2',
b'SNA', b'SA1', b'SA2',
b'SID', b'MRC',... | python|sockets|tcp|blender | 0 |
1,194 | 23,385,749 | Python - must we have an __init__.py in every step of a directory in Windows? | <p>Lets say that we want <strong>on Windows</strong> with <code>Python 2.7</code> to either run a command <strong>from the GUI</strong> by typing it and hitting <kbd>Enter</Kbd> or <strong>right-click on the Python file and choose Edit with IDLE</strong> and when IDLE pops up inside IDLE press <kbd>F5</kbd>.</p>
<p>No... | <p>You only need to add <code>__init__.py</code> to directories that must be treated as packages. Any folder outside the <code>PYTHONPATH</code> search path is <em>never</em> a package and doesn't need to have an <code>__init__.py</code>.</p>
<p>You don't need <code>__init__</code> in the top-level directory listed on... | python|windows|import|directory|environment-variables | 4 |
1,195 | 47,169,474 | Parallel asynchronous IO in Python's coroutines | <p>Simple example: I need to make two unrelated HTTP requests in parallel. What's the simplest way to do that? I expect it to be like that:</p>
<pre><code>async def do_the_job():
with aiohttp.ClientSession() as session:
coro_1 = session.get('http://httpbin.org/get')
coro_2 = session.get('http://htt... | <blockquote>
<p>I need to make two unrelated HTTP requests in parallel. What's the
simplest way to do that?</p>
</blockquote>
<pre><code>import asyncio
import aiohttp
async def request(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
return await r... | python|python-asyncio|aiohttp | 25 |
1,196 | 71,040,337 | How to parse specific strings from an attribute inside xml using etree and xpath | <p>I have an XML with two of the same tags and same attribute but different value.</p>
<pre><code><testsuite>
<testcase>
<GenericItem html="Name: Epsilon&lt;br/&gt;ID: ID-032&lt;br/&gt;Owner: Infinitie &lt;a
href=&quot;mailto: infinitie@company.com
&quot;&g... | <p>The main problem is that you forgot <code>.</code> to create relative path to - and then you don't need <code>[i]</code> but always <code>[0]</code></p>
<pre><code>a = person.xpath('.//text()[contains(.,"Results")]')[0]
</code></pre>
<p>And in second part you should search in <code>@html</code> instead of ... | python|xml-parsing|lxml|elementtree | 0 |
1,197 | 33,833,973 | Count the number of nodes with the same name in a tree | <p>I'm trying count the number of nodes with the same name in a tree, but having difficulty. This is what I've tried:</p>
<pre><code>musics = {'genre':'music', 'children':[{'genre':'Pop', 'children':[{'genre':'Eurobeat','children':[]},
{'genre':'Austropop','ch... | <p>change <code>name_count</code> to be a function parameter so you could set a default value of 0 and pass in your current count for your recursive call:</p>
<pre><code>def count_name(self,genre,name_count = 0):
for node in self.children:
if node.genre == genre:
print ("same genre") #you prob... | python|python-2.7 | 1 |
1,198 | 46,935,240 | Lost Robot program | <p>This is an ICPC online round question. I checked sample input and my own imaginary inputs.
<a href="https://www.codechef.com/ACMIND16/problems/ICPC16A" rel="nofollow noreferrer">This is link to question</a></p>
<p>Here is my code. This code is in Python.</p>
<pre><code>for _ in range(int(input())):
x1,y1,x2,y2=m... | <p>Your code already does not parse the input correctly. Have a look:</p>
<pre><code>python /tmp/test.py
1
0 0 0 1
Traceback (most recent call last):
File "/tmp/test.py", line 3, in <module>
x1, y1, x2, y2 = map(int, input().split())
File "<string>", line 1
0 0 0 1
^
</code></pre>
<p>Be... | algorithm|python-3.x | 0 |
1,199 | 37,668,326 | Get child of box in a dialog in python Gtk3 | <p>I'm trying to get a date value from a Calendar in Python Gtk3. The Calendar is inside a dialog. I have the following code:</p>
<pre><code>import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class MyTest(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Titulo")
... | <p>This can be solved by properly using self.</p>
<pre><code>import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class MyTest(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Titulo")
self.connect("delete_event", Gtk.main_quit)
self.set_border_width(... | python-3.x|gtk3 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.