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,900
56,599,656
"OperationalError: database is locked" when deploying site to Azure
<p>I have built a django website and a part of it is Microsoft authentication link. When I upload the site to azure cloud and click on the "log in" link, I recieve the following error: <br></p> <pre><code>OperationalError at /login database is locked Request Method: GET Request URL: http://bhkshield.azurewebsites.n...
<p>It seems like a duplication of this question: <a href="https://stackoverflow.com/questions/3172929/operationalerror-database-is-locked">OperationalError: database is locked</a>.</p> <p>From the documentation of Django: <a href="https://docs.djangoproject.com/en/dev/ref/databases/#database-is-locked-errorsoption" re...
python|django|sqlite|azure-web-app-service
0
1,901
60,873,534
How can I reference a user globally in Django for all Exceptions?
<p>I have two questions that correlate.</p> <p>1) Does django-rest-framework have a way to reference a user globally?</p> <p>2) Does django / python allow me to change the generic exception class to include this user ID as meta every time it throws?</p> <p>I know I can create custom exception classes and raise them ...
<p>You can create a <a href="https://docs.djangoproject.com/en/3.0/topics/http/middleware/#writing-your-own-middleware" rel="nofollow noreferrer">custom middleware</a> that catches all exceptions, you can then log the exception along with the user</p> <pre><code>def exception_middleware(get_response): def middlew...
python|django|exception|django-rest-framework
0
1,902
68,085,691
Finding difference of sets of frozensets
<p>If I do:</p> <pre><code>set({frozenset({1,2}), frozenset({1})}) - set(frozenset({1})) </code></pre> <p>I would expect:</p> <pre><code>{frozenset({1, 2})} </code></pre> <p>as the result but actually I get:</p> <pre><code>{frozenset({1}), frozenset({1, 2})} </code></pre> <p>Why?</p>
<p>That is because when you do <code>set(frozenset({1}))</code> that's actually <code>{1}</code>. If you try:</p> <pre><code>set({frozenset({1,2}), frozenset({1})}) - {frozenset({1})} </code></pre> <p>you may get the result you want.</p>
python|python-3.x|set
1
1,903
63,263,191
How to apply a complicated function a function on a column without “apply”?
<p>I have a dataframe df:</p> <pre><code>A | B | C | ... | D 1000 | 600 | 600 | productdesc | 0 1500 | 400 | 600 | productdesc | 1 1000 | 600 | 300 | productdesc | 0 </code></pre> <p>and a function do_stuff():</p> <pre><code>def do_stuff(A, B, C): * calculations * return result </code></pre> <p>I...
<p>Just need to ensure you return a <code>list</code> or <code>np.array</code> of same size as data frame</p> <pre><code>df = pd.DataFrame({f&quot;col{i}&quot;:[random.randint(0,10) for i in range(10)] for i in range(4)}) def dostuff(a): return [f&quot;*result of dostuff({x},{a[1][i]},{a[2][i]})*&quot; for i,x in ...
pandas|performance|apply
1
1,904
63,110,904
How to use Cyberduck Credentials to Access WebDAV with Python
<p>I've never used <strong>WebDav</strong> before, but I downloaded <strong>Cyberduck</strong> and used it to connect to an internal work drive and download an entire directory to my desktop. However, for reasons I can't yet identify, I run into random errors where some files don't download. I believe this is related t...
<p>It seems Cyberduck is configured for using NTLM authentication, but requests by default use Basic authentication.</p> <p>For connecting to WebDAV server with NTLM authentication you can use 3rd party library which implements it, for example <a href="https://github.com/requests/requests-ntlm" rel="nofollow noreferrer...
python|python-3.x|webdav|cyberduck
1
1,905
35,352,577
Django-sorting Cannot reorder a query once a slice has been taken
<p>Use django-sorting library according to this example: <a href="https://github.com/directeur/django-sorting/wiki/example-usage" rel="nofollow">django-sorting example</a>, but get errors said "<strong>Cannot reorder a query once a slice has been taken.</strong>" at line "{% autosort object_list %}".</p>
<p>A slice is something like <code>object_list = MyModel.objects.all()[:5]</code>. Trying to autosort that would throw this error.</p> <p>You'll need to pass an entire queryset to autosort.</p>
python|django|django-templates|django-views
1
1,906
59,663,362
What is the difference between TF model garden and tf.keras.applications?
<p>With the new TensorFlow 2 we have their <a href="https://github.com/tensorflow/models/tree/master/official" rel="nofollow noreferrer">Model Garden</a> (in GitHub under <code>/models</code>), as well as the pre-trained models for Keras under <code>tf.keras.applications</code>. </p> <p>What is the difference between...
<p><strong><em>Tensorflow Keras Applications</em></strong><br/> - pre-trained models for CNNs. They include most frequently used CNN architectures such as ResNet, InceptionNet, VGG etc. <br> - tf.keras.applications allow you to directly import a CNN architecture (see docs <a href="https://www.tensorflow.org/api_docs/p...
tensorflow|keras
1
1,907
71,056,125
How can I continue a nested conversation in a separate file
<p>I am not a professional programmer but I'm trying to build a python-telegram-bot for work using ConversationHandlers. Basically, I offer users a menu of options, summarized as:</p> <ul> <li>Complete Survey</li> <li>EXIT</li> </ul> <p>If &quot;Complete Survey&quot; is selected, the bot then asks for the user ID. Depe...
<p>I have been developing telegram bots for about a year now, and I hope the best approach is to structure your project first. Let me explain that all in detail.</p> <h2>&quot;Foldering&quot;</h2> <p><a href="https://i.stack.imgur.com/D0JAe.png" rel="nofollow noreferrer">Folder structure</a></p> <p>Basically, all the c...
python|telegram-bot|python-telegram-bot
1
1,908
50,334,782
Define bubble sizes according to a column and bubble colors according to another column in scatter plot (matplotlib)
<p>I'm building a simple scatter plot that reads data from a xls file. It's the classic Life expectancy x GDP per capita scatter plot. Here's the code:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import matplotlib.cm as cm #ler a terceira sheet da planilha data = pd.read_excel('sample.xls', sh...
<p>You could transform the <code>Region</code> to a numeric representation, and use that as a "key" to your colormap. Below are two methods to do that (one is commented out, pick whichever you choose, the result should be the same):</p> <pre><code>plt.scatter(x = data['LifeExpec'], y = data['GDPperCapita'], ...
python|python-3.x|matplotlib
0
1,909
56,014,258
Pandas how to select top 2 values after group by?
<p>I got confused with sortby or nlargest functions. Can someone show me the light please? New and learning Python with all your help.</p> <p>Current Dataset:</p> <pre><code>df = pd.DataFrame({'State':['TX','TX','TX','LA','LA','LA','LA','MO','MO'], 'County':['TX1','TX1','TX1','LA1','LA1','LA1','LA1...
<p>More than one way to do this but I think the "built-in" method to select ordinal data is most likely <code>nth()</code>. <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.nth.html" rel="nofollow noreferrer">Docs</a>.</p> <pre><code>import pandas as pd &gt;&gt;&gt;df ...
python|pandas
1
1,910
69,321,988
Sum columns based on multiple lists with whitespace replacement in Pandas
<p>I want to create three sum columns based on the items from each list. The process is to replace the whitespace with underscore before summing the columns. I was trying to do a loop instead of doing a list comprehension one by one, but I might have missed out something in the loop. How can I achieve my expected resul...
<p>You need to loop through <code>xup</code> and <code>yup</code> in parallel using <code>zip</code> instead of nesting them:</p> <pre><code>for sum_col, cols in zip(xup, yup): cols = [x.replace(' ', '_') for x in cols] df[sum_col] = df[df.columns.intersection(cols)].sum(1) df apple_pie watermelon_pie ...
python|pandas
0
1,911
55,504,692
Input string. Associate index to each character in string for a dictionary
<p>I am asking the user to enter a string. I am ultimately trying to pass the string to a dictionary, where the the index of each character is associated with each character in the string. Ex: Input = CSC120</p> <p>What I have done so far is entered a string and passed it to a set. The issue is that when I pass it to...
<p>It can be done with a <a href="https://docs.python.org/3/reference/expressions.html#dictionary-displays" rel="nofollow noreferrer">dictionary display</a> (aka comprehension):</p> <pre><code>Input = 'CSC120' d = {i: c for i, c in enumerate(Input)} print(d) # -&gt; {0: 'C', 1: 'S', 2: 'C', 3: '1', 4: '2', 5: '0'} ...
python
1
1,912
44,678,001
Sum column of a hierarchical index?
<p>The DataFrame without sum for column of a hierarchical index:</p> <pre><code> dex1 dex2 dex3 one two H D A 1 2 B 4 5 C 7 8 I E A 1 1 B 2 2 C 3 3 </code></pre> <p>The DataFrame with sum...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> + <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.sum.html" rel="nofollow noreferrer"><code>GroupBy.sum</code></a>:</...
python|loops|pandas|dataframe|indexing
2
1,913
41,117,745
How can I mock waiting library in Python?
<p>I'm using the <a href="https://github.com/vmalloc/waiting" rel="nofollow noreferrer"><code>waiting</code></a> library in some of my code to wait for a condition to become true. As a part of the library, <code>waiting.wait</code> returns <code>True</code> when the predicate is true; otherwise it throws and exception ...
<p>Your <code>waiting.wait.return_value = True</code> won't work, because <code>waiting.wait</code> is not a mock object. You only added an arbitrary attribute to the existing <code>wait</code> function, but that function won't use that attribute.</p> <p>To mock out the <code>wait</code> function, just <em>mock it dir...
python|python-3.x|unit-testing|mocking|polling
1
1,914
51,781,960
pandas set column value only for common rows with another table
<p><strong>Input</strong></p> <pre><code>table 1 +---+---+---+ | A | B | C | +---+---+---+ | a | b | 0 | +---+---+---+ | x | y | 0 | +---+---+---+ | w | q | 0 | +---+---+---+ table 2 +---+---+ | A | B | +---+---+ | a | b | +---+---+ | w | q | +---+---+ </code></pre> <p><strong>Output</strong></p> <pre><code>table ...
<p>Use</p> <pre><code>In [303]: df1['C'] = df1.merge(df2, how='left', indicator='_')['_'].eq('both').astype(int) In [304]: df1 Out[304]: A B C 0 a b 1 1 x y 0 2 w q 1 </code></pre>
pandas
2
1,915
39,334,795
pydbg 64 bit enumerate_processes() returning empty list
<p>I'm using pydbg binaries downloaded here: <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#pydbg" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#pydbg</a> as recommended in previous answers.</p> <p>I can get the 32-bit version to work with a 32-bit Python interpreter, but I can't get the 64-bit versio...
<p>Pydbg defines the PROCESSENTRY32 structure wrong.</p> <p>Better use a maintained package such as <a href="https://pythonhosted.org/psutil/#psutil.process_iter" rel="nofollow">psutil</a> or use ctypes directly, e.g.:</p> <pre><code>from ctypes import windll, Structure, c_char, sizeof from ctypes.wintypes import BOO...
python|pydbg
1
1,916
52,487,598
Error in regression analysis with 3 classes
<p>I am trying to apply one vs all logistic regression:</p> <p>I am using one vs all method (class1 vs class2+ class3, c2 vs c1+c3, c3 vs c1+c2) to calculate the three cases weights w1,w2,w3:</p> <pre><code> for n1 in range(0,50000): s1 = np.dot(dt, w1) p1 = (1 / (1 + np.exp(-s1))) gr1 = (n...
<p>so. the iris data set is not perfect linearly separable in all the sets. so wen we use a linear classifier like logistic regression the loss in the part that is not linearly separable tends to be unpredictable. you can put a a very small learning hate and a patiently method to avoid overffitting. normalization of yo...
python
1
1,917
48,016,658
Django bulk create objects from QuerySet
<p>If I have a <code>QuerySet</code> created from the following command:</p> <pre><code>data = ModelA.objects.values('date').annotate(total=Sum('amount'), average=Avg('amount')) # &lt;QuerySet [{'date': datetime.datetime(2016, 7, 15, 0, 0, tzinfo=&lt;UTC&gt;), 'total': 19982.0, 'average': 333.03333333333336}, {'date':...
<p>This is more efficient than your call because it uses <code>bulk_create</code>, which invokes just one SQL bulk create operation, as opposed to one create per object; also, it is much more elegant:</p> <pre><code>ModelB.objects.bulk_create([ ModelB(**q) for q in data ]) </code></pre> <p>As to how this works, the dou...
python|django|django-queryset
19
1,918
51,257,322
What technology is used to serve HTTP requests compatible with Python
<p>I'm building an application on AWS and well, this world is new to me.</p> <p>I expose the problem</p> <p>I have experience with Apache / PHP, Apache is the one who helps me serve HTTP requests and PHP is the language of Backend.</p> <p>The backend language that I am using in this new project is Python, but my que...
<p>I would recommend to look at uWSGI:</p> <ul> <li><a href="https://uwsgi-docs.readthedocs.io/en/latest/WebServers.html" rel="nofollow noreferrer">https://uwsgi-docs.readthedocs.io/en/latest/WebServers.html</a></li> </ul> <p>mod_wsgi for Apache:</p> <ul> <li><a href="https://modwsgi.readthedocs.io/en/develop/" rel=...
python|apache|http
1
1,919
62,161,420
AttributeError: Tensor.op is meaningless when eager execution is enabled
<p>I am trying to implement RESNET 50 from scratch. After accumulating all the layers, I call <code>tf.keras.Model</code>. However, it gives an error:</p> <blockquote> <p>AttributeError: Tensor.op is meaningless when eager execution is enabled.</p> </blockquote> <p>For testing, I am inputting a 4-D tensor. <code>conv_d...
<p>the problem in your code is you are giving <strong>X</strong> as <strong>input</strong> as well as <strong>output</strong>.</p> <p><strong>Try this</strong></p> <pre><code>import tensorflow as tf def ResNet50(input_shape, classes): inputs = tf.keras.Input(shape=input_shape)#input_shape = (224,224,3) X = tf.kera...
keras|deep-learning|conv-neural-network|tensorflow2.0|resnet
0
1,920
62,134,918
get_attribute problem with selenium python
<p>I've been suing Selenium-Python for about 2 months. I want to get 'rel' attribute value. Every other values are working, but 'rel' value returns none i.e </p> <pre><code>&lt;span class="isOdd" data-ratio="-1" data-outcome="1.85" data-percentage="23" data-market-id="1677954" data-outcomeno="1" data-id="undefined" re...
<p>This might be what you are after?</p> <pre><code>link=WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH,"//*[@id='eventContentContainer']/div[4]/div[4]/span[4]/ul/li[4]/span"))) print(link.get_attribute('rel')) </code></pre> <p>Add these imports before trying the above:</p> <pre><code>from...
python|selenium|attributes
0
1,921
62,430,477
How to set a background image in tkinter using grid only
<p>I'm trying to set a background image to my tkinter window, however I don't quite know how to resize it so it fits the dimensions of the window. I've looked online, and all the tutorials/answers use pack (to expand and fill), but I can't use pack because I have a bunch of other buttons/labels that all use grid (this ...
<p>You can use <code>place(x=0, y=0, relwidth=1, relheight=1)</code> to lay out the background image label. In order to fit the image to the window, you need to resize the image when the label is resized.</p> <p>Below is an example based on your code:</p> <pre><code>import tkinter as tk from PIL import Image, ImageT...
python|tkinter
4
1,922
63,451,149
Matrix Elements Ratio Control
<p>I am using the code</p> <pre class="lang-py prettyprint-override"><code>import numpy as np P=np.random.choice([0, 1], (10000, 10, 10, 10)) </code></pre> <p>to generate 10,000 3D binary matrices. But I need to control the ratio of ones to zeros in each of the matrices. What I mean is that for any given matrix, I want...
<p>You should specify probablity parameter in <a href="https://docs.scipy.org/doc//numpy-1.10.4/reference/generated/numpy.random.choice.html" rel="nofollow noreferrer">numpy.random.choice</a></p> <pre class="lang-py prettyprint-override"><code>import numpy as np size = (10000, 10, 10, 10) prob_0 = 0.3 # 30% of zeros p...
python|numpy|matrix|probability
1
1,923
13,569,105
How to properly eliminate elements in dictionary until one string remains
<p>I really need help on this</p> <pre><code>def get_winner (dict_winner): new_dict = {} for winner in dict_winner: first_letter = winner[0] value = dict_winner[winner] if first_letter in new_dict: new_dict[first_letter] += value else: new_dict[first_let...
<p>My solution - in one step:</p> <pre><code>def get_winner(candidates): winners = dict.fromkeys(map(lambda f: f[0] for f in candidates.keys())) for cand, votes in candidates.iteritems(): winners[cand[0]]+=votes return [winner for winner, vote in winners.iteritems() if vote ==max(winners.values())...
python|dictionary
0
1,924
16,963,301
python 2.7 random sampling causes memory error
<pre><code>random.sample(range(2**31 - 1), random.randrage(1, 100)) </code></pre> <p>This results in:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; MemoryError </code></pre> <p>I'm running python 2.7.3 on ubuntu 12.04 64-bit with 6GB RAM.</p> <p>I thought 2**31 ...
<p>You are probably referring to the limit on integers in languages like <code>C</code> where an <code>int</code> is usually 4 bytes. In Python 2.7 integers have no limit and are automatically promoted to a larger type when needed, holding infinite precision. Your problem is not directly related to this, you are trying...
python|python-2.7|random
8
1,925
16,836,023
Has anyone Compared Qt Commercial Charts with matplotlib?
<p>What is better to use for interactive data plotting? matplotlib (<a href="http://www.matplotlib.org" rel="nofollow">http://www.matplotlib.org</a>) or Qt Commercial Charts (<a href="http://qt.digia.com/Product/Qt-Add-Ons/Charts/" rel="nofollow">http://qt.digia.com/Product/Qt-Add-Ons/Charts/</a>) There are several fu...
<p><code>matplotlib</code> is interactive, see <a href="http://matplotlib.org/examples/user_interfaces/interactive.html" rel="nofollow">this demo</a> - you can even embed it in <a href="http://matplotlib.org/examples/user_interfaces/embedding_in_qt.html" rel="nofollow"><code>Qt</code></a> (which I use all the time and ...
python|qt|matplotlib|pyqt4|pyqtgraph
4
1,926
16,650,962
Referencing a list element by it's name
<p>I'm trying to scan through a list of dictionary references to get the number of keys in each dictionary. How do I go about referencing an element's name as opposed to the content of the dictionary? Each of the elements in the audit_dicts list is a reference to an existing dictionary.</p> <pre><code>audit_dicts = ...
<p>Lists don't contain names, they contain references to other objects. If you want to be able to use more than just an index to refer to the elements then you should use another data structure such as a <code>dict</code>.</p>
python
6
1,927
43,540,399
how to print the matched words in python
<p>I have a text file and 2 user defined positive and negative files. I'am comparing the words present the 2 files with the text file, and returning either positive or negative. </p> <p>But i need to print those keywords in the text, which categorized them to either positive or negative.</p> <p>example of the output ...
<p>A good start would be to have the right indentation in the assign_comments_labels(x) function. Indent the whole body.</p> <p><strong>Edited answer</strong>:<br> Ok I get your question now;</p> <p>This code should work for you based on the logic you used above:</p> <pre><code>def get_keyword(x): x_ = x.split(" ...
python|string|python-3.x|match|search-keywords
1
1,928
54,531,476
Pandas source code import multiple modules
<p>I was looking at the pandas source code <a href="https://github.com/pandas-dev/pandas/blob/2e38d5552a5c7b2c0091cecddd483f4f08ad1d2c/pandas/core/groupby/ops.py" rel="nofollow noreferrer">here</a>, and I found the following statement a little bit weird: </p> <pre><code>from pandas._libs import NaT, groupby as libgrou...
<p>from <code>pandas._libs</code> it actually imported 5 method/class/module:</p> <ol> <li>NaT,</li> <li>grouby as libgroupy (so in your script you will now use libgroupy)</li> <li>iNaT</li> <li>lib</li> <li>reduction</li> </ol> <hr /> <p>Now <code>NaT</code> and <code>iNaT</code> indeed doesn't exists in the <code>...
python|python-3.x|pandas|cython|pandas-groupby
2
1,929
54,353,912
How to replace specific integer number with a character in python using regex?
<p>I tried to replace a specific number like 22 in my string with a string like "Hi there", but it also replace float numbers like 22.14 in my string (Hi there.14).</p> <pre><code> import re my_string = "22 and 22.14" re.sub(r'\b22\b', "Hi there", my_string) </code></pre>
<p>You can use this regex, which will not let it match decimal values by using positive lookahead to ensure it only matches if <code>22</code> is followed by a space or end of input.</p> <pre><code>\b22(?= |$) </code></pre> <p><strong><a href="https://regex101.com/r/wtEzek/1" rel="nofollow noreferrer">Demo</a></stron...
python|regex|string|replace|numbers
2
1,930
9,387,928
What's the difference between dist-packages and site-packages?
<p>I'm a bit miffed by the python package installation process. Specifically, what's the difference between packages installed in the dist-packages directory and the site-packages directory?</p>
<p><code>dist-packages</code> is a Debian-specific convention that is also present in its derivatives, like Ubuntu. Modules are installed to <code>dist-packages</code> when they come from the Debian package manager into this location:</p> <pre><code>/usr/lib/python2.7/dist-packages </code></pre> <p>Since <code>easy_ins...
python|pip|easy-install|package-managers
260
1,931
9,066,774
Python & OpenERP development environment setup howto?
<p>I downloaded Open ERP server &amp; web, having decided against the thicker gtk. I added the 2 as projects in eclipse, pydev running on Ubuntu 11.10 and started then up. I went through the web client setup &amp; I though the installation had been done. At some point though I had executed a script that tried to copy a...
<p>I feel your pain. I went through the same process a couple of years ago when I started working with OpenERP. The good news is that it's not too hard to set up, and OpenERP runs smoothly in Eclipse with PyDev.</p> <p>Start by looking at the <a href="http://doc.openerp.com/v6.0/developer/1_1_Introduction/index.html" r...
python|eclipse|odoo
3
1,932
52,703,805
Matplotlib figure only shows after second file run
<p>I am doing some basic plotting routine (as below), and after the first file run I will only get <code>&lt;Figure size 640x460 with 1 Axes&gt;</code> appearing in the output area. And then on the second run of the code, the figure will actually be plotted. Ideally it would plot on the first run, as later I want to te...
<pre><code>import matplotlib matplotlib.use('Qt5Agg') </code></pre> <p>Solves the issue and plots first run (not sure why exactly)</p>
python|matplotlib|plot|hydrogen
0
1,933
52,707,213
Module not found with virtual environment
<p>I can run my app from the console that there is in pyCharm but If I try to run my app from a shell my app doesn't find "pymysql" module.</p> <p>The module is installed in my project in a virtual environment. You can see in the next image how is installed this module.</p> <p><a href="https://i.stack.imgur.com/dFg4i...
<p>There are several ways:</p> <ol> <li>activate virtual env: <code>source venv/bin/activate</code>.</li> <li>directly use specific python: <code>venv/bin/python main.py</code></li> <li>Surely you can temporarily add <code>venv/bin</code> to your <code>PATH</code>, that's almost the same as the first option: <code>exp...
python
2
1,934
47,719,249
Python appending empty list
<p>I am very new to Python and trying to learn by trial-and-error, so my question may sound naive for the community.</p> <p>Let's say I have two empty lists with only the first element defined:</p> <pre><code>a = [[]]*20 a[0] = 0 b = [[]]*20 b[0] = 1 </code></pre> <p>I want to use a for loop for creating the other e...
<p>The problem is on this line:</p> <pre><code>a[i] = b[i-1], </code></pre> <p>Notice the comma at the end? That makes python think you're dealing in <a href="https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences" rel="nofollow noreferrer">tuples</a>. Remove it and the error will be gone.</p>
python|for-loop
4
1,935
37,467,850
I cannot append my data to a list
<p>I am trying to append the total area to the attribute table and it runs through without any error message. I am not sure what I'm doing wrong:</p> <pre><code>import os import arcpy import math folderpath = 'C:\Users\Michaelf\Desktop\GEOG M173' arcpy.env.workspace = folderpath arcpy.env.overwriteOutput = True input_...
<p>Firstly: You've got a data type issue when you're adding that list of fields.</p> <p>This code simply adds a field named <code>totarea</code>, and doesn't do anything with the data in the <code>fields</code> list.</p> <pre><code>for field in fields: arcpy.AddField_management(equal_shape, "totarea") </code></pr...
python|arcpy|cursors
0
1,936
72,568,160
Average vectors between two pandas DataFrames
<p>Assume, there are two DataFrame, which are</p> <pre><code>import pandas as pd import numpy as np df1 = pd.DataFrame({'item':['apple', 'orange', 'melon', 'meat', 'milk', 'soda', 'wine'], 'vector':[[12, 31, 45], [21, 14, 56], [9, 47, 3], ...
<p>This answer may be long-winded and not optimized, but it will serve your purpose.</p> <p>First of all, you need to check if the items in df2 is in df1 so that you can add the non existing item into df1 along with the 0s.</p> <pre><code>import itertools for i in set(itertools.chain.from_iterable(df2['grocery'])): ...
python|pandas|dataframe
1
1,937
72,822,846
How do I extract the entire sentence from a job description which consists the number of years of experience in it?
<p>I've been working on a job description parser and I have been trying to extract the entire sentence which consists of the number of years of experience required.</p> <p>I have tried to use regex which provides me the number of years but not the entire sentence.</p> <pre><code>def extract_years(self,resume_text): re...
<p>Try: (\d+(?:-\d+)?+?)\s*(years?).*</p> <p>Though I'm somewhat new to Regex, I believe you can get what you desire using a combination of &quot;.*&quot; to end of your match terms and possibly the beginning if &quot;5-7 years&quot; comes after some characters like &quot;needs 5-7 years of experience&quot;.</p> <p>ju...
python|regex
1
1,938
39,796,252
PCRE Regex (*COMMIT) equivalent for Python
<p>The below pattern took me a long time to find. When I finally found it, it turns out that it doesn't work in Python. Does anyone know if there is an alternative?</p> <p><code>(*COMMIT)</code> Defined: Causes the whole match to fail outright if the rest of the pattern does not match.</p> <p><code>(*FAIL)</code> doe...
<p>This might not be a generic replacement, but for your case you can work with lookaheads, to assert that dog is matched, but park is not: <code>^(?=.*dog)(?!.*park).*$</code></p> <p>Your samples on <a href="https://regex101.com/r/gOY9GT/1" rel="nofollow">regex101</a></p>
python|regex
2
1,939
39,489,539
Access m2m relationships on the save method of a newly created instance
<p>I'd like to send emails (only) when Order instances are created. In the email template, I need to access the m2m relationships. Unfortunatly, its seems like the m2m relations are ont yet populated, and the itemmembership_set.all() method returns an empty list.</p> <p>Here is my code:</p> <pre><code>class Item(mode...
<p>Some of the comments suggested using signals. While you can use signals, specifically the <code>m2m_changed</code> signal, this will always fire whenever you modify the m2m fields. As far as I know, there is no way for the sender model (in your sample, that is <code>ItemMembership</code>) to know if the associated <...
python|django|django-models|m2m
1
1,940
16,549,530
Infoblox WAPI: how to search for an IP
<p>Our network team uses <a href="http://www.infoblox.com/products/ip-address-management" rel="nofollow">InfoBlox</a> to store information about IP ranges (Location, Country, etc.) There is an API available but Infoblox's documentation and examples are not very practical.</p> <p>I would like to search via the API for ...
<p>By using requests.get and json.dumps, aren't you sending a GET request while adding JSON to the query string? Essentially, doing a</p> <pre><code>GET https://10.6.75.98/wapi/v1.0/network?{\"network\": \"10.233.84.0/22\"} </code></pre> <p>I've been using the WebAPI with Perl, not Python, but if that is the way your...
python|api
3
1,941
16,252,035
Django: assigning a foreign key of class that hasn't been created yet
<p>I have the relational database and one of the relations looks like this:</p> <pre><code>Student &lt; --- &gt; Major_enrollments </code></pre> <p>So I need to create a column with a foreign key to the second table in both tables. How can I do so in the view of the fact, that if I define the class e.g. Student first...
<p>You can use the class name (as a string) instead of class itself:</p> <pre><code>class Students(models.Model): nr_album = models.IntegerField() fName = models.CharField(max_length=70) lName = models.CharField(max_length=70) pesel = models.BigIntegerField() address = models.CharField(max_length=...
python|sql|django
6
1,942
31,841,786
Flash only uncategorized messages in Flask app
<p>I want to display <a href="http://flask.pocoo.org/docs/0.10/patterns/flashing/" rel="nofollow">flashed messages</a> with the 'error' category in one section, and uncategorized messages in another section. If I just ask for messages <code>with_categories=False</code>, I get messages with the 'error' category as well...
<p><a href="https://github.com/mitsuhiko/flask/blob/0.10.1/flask/helpers.py#L342" rel="nofollow">All messages have the default category <code>'message'</code>.</a> Get those messages, then get your other messages.</p> <pre><code>{% with messages = get_flashed_messages(category_filter=['message']) %} </code></pre>
python|flask|jinja2
3
1,943
32,091,373
how to manipulate user submitted text and display it with django?
<p>I want to build a very simple webapp that takes a user's text, runs a function on it that alters it and then displays the altered text. I have the code for the function but everything else is unclear. </p> <p>I am very new to django and just need a push in the right direction with this problem. At the very least, t...
<ol> <li><p>Define a form; in forms.py under your app's folder</p> <pre><code>class MyForm(forms.Form): myinput = forms.forms.CharField(max_length=100) </code></pre></li> <li><p>Define a function in your views.py</p> <pre><code>import .forms def handle_form(request): if request.method == 'POST': # If the form...
python|django|django-forms|form-submit
1
1,944
38,646,400
tarfile compressionerror bz2 module is not available
<p>I'm trying to install twisted pip install <a href="https://pypi.python.org/packages/18/85/eb7af503356e933061bf1220033c3a85bad0dbc5035dfd9a97f1e900dfcb/Twisted-16.2.0.tar.bz2#md5=8b35a88d5f1a4bfd762a008968fddabf" rel="nofollow">https://pypi.python.org/packages/18/85/eb7af503356e933061bf1220033c3a85bad0dbc5035dfd...
<p>I don't seem to have any problem with <code>import bz2</code> on my python 3.4 installation. So I did </p> <pre><code>import bz2 print (bz2.__file__) </code></pre> <p>And found that it's located at <code>/usr/lib/python3.4/bz2.py</code> then I did</p> <pre><code>dpkg -S /usr/lib/python3.4/bz2.py </code></pre> <p...
python|linux|django|python-3.x|bz2
4
1,945
40,444,925
Filter elements from list based on them containing spam terms
<p>So I've made a script that scrapes some sites and builds a list of results. Each result has the following structure:</p> <pre><code>result = {'id': id, 'name': name, 'url': url, 'datetime': datetime, } </code></pre> <p>I want to filter results from the list of results ba...
<p>I guess you've got a problem with in-place modifying theList as iterating over it as Jakub suggested.</p> <p>The obious way would be to return a new list. I would split this in two functions for readability:</p> <pre><code>def is_spam(value): spam_terms = ['paid','hire','work','review','survey', ...
python|filter|scraper
1
1,946
40,375,917
How to dynamically make an existing non-abstract django model, abstract?
<p>I think I have a more or less unorthodox and hackish question for you. What I currently have is django project with multiple apps. I want to use a <code>non-abstract model (ModelA)</code> of one app (<code>app1</code>) and use it in another app (<code>app2</code>) by subclassing it. App1's models should not be migra...
<p>Why not, in app1</p> <pre><code>AbstractBaseModelA(models.Model): # other stuff here class Meta: is_abstract=True ModelA(AbstractBaseModelA): # stuff </code></pre> <p>in app2:</p> <pre><code>MobelB(AbstractBaseModelA): # stuff </code></pre> <p>Sorry if I've misunderstood your aims, but ...
python|django|django-models
0
1,947
10,214,003
Can Python win32com use Visio (or any program) without popping up a GUI?
<p>I have a Python script using win32com to open a Visio file and dump each tab as <code>.png</code> files. It briefly flashes the Visio gui up on the screen when it does this. Is there any way to do this in the background without loading the Visio window?</p> <pre><code>import win32com.client visio = win32com.clien...
<pre><code>visio = win32com.client.Dispatch("Visio.InvisibleApp") </code></pre> <p>should create a Visio instance that is invisible.</p> <p>See <a href="http://msdn.microsoft.com/en-us/library/aa201815(v=office.10).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa201815(v=office.10).aspx</a></p>
python|com|visio|win32com
5
1,948
68,029,324
replace string character (') to (-) in pandas and change it to datetime
<p>i have dataset df like below;</p> <pre><code> A June'11 July'12 2018-02-01 </code></pre> <p>anyone can help me to replace (') character to (-) iam confuse to use pandas code</p> <pre><code> df['A'].replace(''', '-', inplace=True) ??? </code></pre> <p>After i have changed the (') string i want to change the A col...
<p>Please try below:</p> <pre><code>&gt;&gt;&gt; df A 0 June'11 1 July'12 2 2018-02-01 &gt;&gt;&gt; df.replace({'\'': '-'}, regex=True) A 0 June-11 1 July-12 2 2018-02-01 </code></pre> <p>OR</p> <p>If its specific to a column <code>A</code> then.</p> <pre><code>&gt;&gt;&gt; df['A']...
pandas|dataframe
0
1,949
26,415,939
Python - Getting error whenever I try to run program "Module cannot be found"
<p>I'm trying to do this little tutorial <a href="http://www.roguebasin.com/index.php?title=Complete_Roguelike_Tutorial,_using_python%2Blibtcod,_part_1" rel="nofollow">http://www.roguebasin.com/index.php?title=Complete_Roguelike_Tutorial,_using_python%2Blibtcod,_part_1</a> </p> <p>A little ways down the page right bef...
<p>I'm assuming you also copied <code>libtcod-VS.dll</code> or <code>libtcod-mingw.dll</code> to the project directory, not just <code>libtcodpy.py</code>. And also <code>SDL.dll</code> and a <code>arial10x10.png</code>. If not, go back and look at the <a href="http://www.roguebasin.com/index.php?title=Complete_Rogueli...
python|python-3.x|pycharm|libtcod
1
1,950
60,323,910
How can I find string with regular expressions in Python
<p>I have html string like that for example</p> <pre><code>&lt;td align="left" nowrap="nowrap"&gt;John 23&lt;/td&gt; </code></pre> <p>I want to find "John 23" between <code>'&lt;td align="left" nowrap="nowrap"&gt;'</code> and <code>'&lt;/td&gt;'</code></p> <p>I want to find with Regular Expressions in python</p> <p...
<p>Use BeautifulSoup to parse HTML. Regex is the wrong tool; it works fine for this example but wouldn't scale well to a full document.</p> <pre><code>&gt;&gt;&gt; from bs4 import BeautifulSoup &gt;&gt;&gt; html = '&lt;td align="left" nowrap="nowrap"&gt;John 23&lt;/td&gt;' &gt;&gt;&gt; BeautifulSoup(html).find("td").t...
python|regex|search|expression
2
1,951
32,293,394
Python guess the number game
<p>I tried to make a guess the number game in python but whenever I guess it repeats 4 times 'your guess is too low'</p> <pre><code>import random number = random.randint(1, 20) guessestaken = 0 print('I am thinking of a number between 1 and 20 ') guess = raw_input('Take a guess and hit enter') while guessestaken &lt; ...
<p>You are asking for the user input before the while loop.</p> <pre><code>guess = int(raw_input('Take a guess and hit enter')) </code></pre> <p>This statement should come within the while block.</p> <p>The function raw_input returns a string, you should convert it to an integer. You can read more about it in the <...
python-2.7
1
1,952
28,312,831
modifying multiple fields in a structured array (Python)?
<p>Let's say I have a structured array as follows:</p> <pre><code>import numpy as np fields = [('f1', np.float32), ('f2', np.float32)] k = np.ones(2, fields) </code></pre> <p>I want to be able to access multiple fields and modify them simultaneously. I'm aware that I can access multiple fields using a view. But what ...
<p>With a <code>dtype</code> like this, there are 2 direct ways of accessing and modifying the data. By field name, e.g. <code>k['f0']</code>, or by elements (rows) in the form of tuples. You are using the 2nd method. If the number of fields isn't that large, and you need to access many elements, then the first is b...
python|arrays|numpy
0
1,953
14,265,223
Process Doesn't End When Closed
<p>I built a web-scraper application with Python. It consists of three main parts:</p> <ol> <li>The GUI (built on tkinter)</li> <li>A Client (controls interface between front- and back-end)</li> <li>Back-end code (various threaded processes).</li> </ol> <p>The problem I have is that when the user hits X to exit the p...
<p>You don't want to set <em><strong>all</strong></em> threads to <code>daemon</code>. You want to set the client thread and the back-end thread to daemon. That way, when the GUI thread dies, the threads with <code>daemon</code> set to <code>True</code> end as well.</p> <p>From the <a href="http://docs.python.org/2/li...
python|tkinter
2
1,954
8,117,719
Can't install matplotlib on OS X with PIP
<p>This is my first time setting up matplotlib.<br> I'm on OS X Lion 10.7 (build 11A511s, so no updates done to the initial release of OS X Lion).<br> I am using virtualenv and pip to do the installation.<br> I'm aware of the incompatibility with libpng 1.5, so I didn't just run "pip install matplotlib"... instead...<b...
<p><strong>Three years later:</strong></p> <p>You should use <a href="http://continuum.io/downloads" rel="nofollow">anaconda</a> to install matplotlib (or numpy or pandas or scipy) if you're new to the process. This suggestion applies for pretty much any platform too.</p>
python|matplotlib|virtualenv|pip
0
1,955
47,087,338
How to create a two dimensional list from imported data from text file
<p>I'm trying to import the info to create a 2D list, and I'm having a hard time filling in the list with the information. I'm stuck trying to import the info to create the list</p> <pre><code>ROW = 3 COLS = 4 myInfo = ('myInfoFile.txt', 'r') name = myInfo.readline().rsrip('\n') while name != '': address = myInfo...
<p>Two Things that are wrong</p> <ul> <li>You are not assigning the data while reading your file</li> <li>You are assigning a closed file descriptor while using your array Try This <code> info=[[]*COLS for i in range(ROWS)] for i in range(ROWS): for j in range(COLS): info[i][j]=filename.readl...
python|arrays|loops|text
0
1,956
47,242,503
tflearn DNN gives zero loss
<p>I am using <code>pandas</code> to extract my <code>data</code>. To get an idea of my <code>data</code> I replicated an example dataset...</p> <pre><code>data = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD')) </code></pre> <p>which yields a dataset of <code>shape=(100,4)</code>...</p> <p...
<p>Your actual output is in range 0 to 100 while the activation softmax in the outermost layer outputs in range [0, 1]. You need to fix that. Also the default loss for tflearn.regression is categorical cross entropy which is used for classification problems and makes no sense in your scenario. You should try L2 loss. ...
python-3.x|numpy|tensorflow|neural-network|tflearn
2
1,957
11,571,656
Flask/Werkzeug debugger, process model, and initialization code
<p>I'm writing a Python web application using Flask. My application establishes a connection to another server at startup, and communicates with that server periodically in the background.</p> <p>If I don't use Flask's builtin debugger (invoking app.run with debug=False), no problem.</p> <p>If I do use the builtin de...
<p>I confirmed this behavior is due to Werkzeug, not Flask proper, and it is related to the reloader. You can see this in Werkzeug's serving.py -- in run_simple(), if use_reloader is true, it invokes make_server via a helper function run_with_reloader() / restart_with_reloader() which does a subprocess.call(sys.executa...
python|flask|wsgi|werkzeug
9
1,958
33,589,871
Function used to check if a variable's string starts with vowel?
<p>I am doing a sort of MadLibs thing and I need to check if three of my variables start with a vowel, and then tack "a" or "an" in front. I have this,</p> <pre><code>def vowelcheck(variable): if variable[0] == "a" or variable[0] == "e" or variable[0] == "i" or variable[0] == "o" or variable[0] == "u": var...
<p>the 'variable' argument of your function is a copy of the words noun1, noun2, nound2. you indeed modify 'variable', but it does not modify nouns.</p> <p>try instead:</p> <pre><code>def vowelcheck(variable): if variable[0] == "a" or variable[0] == "e" or variable[0] == "i" or variable[0] == "o" or variable[0] =...
python
1
1,959
47,015,858
How to set the mouse cursor on QTabWidget tabs
<p>I am dealing with a simple problem I don't succeed to solve. I am working with Python-3.6 and PyQt5.</p> <p>What I wish is to <strong>change the mouse cursor</strong> when the user has the mouse above the <strong>inactive tab</strong> (to understand he can click on it to change the active tab). And this only on the...
<p>You can change the cursor for <strong>all</strong> the tabs by setting it on the <a href="https://doc.qt.io/qt-4.8/qtabwidget.html#tabBar" rel="nofollow noreferrer">tab-bar</a>:</p> <pre><code> self.tabWidget.tabBar().setCursor(QtCore.Qt.PointingHandCursor) </code></pre> <p>However, to change it for <strong>onl...
python|pyqt|qtabwidget|mouse-cursor
1
1,960
46,826,822
Singleton list or normal list?
<p>I'm very new to python and would like to ask some maybe very dumb question about list.</p> <p>I have some list</p> <pre><code>lst = get_lst() element = #some element </code></pre> <p>I want to create a single element list [element] or <code>lst</code>. I can do it like this</p> <pre><code>result_lst = [element] ...
<p>The shortest way to express this might be:</p> <pre><code>result_lst = ([element], lst)[element is None] </code></pre> <p>But I would not necessarily consider it a recommendable pattern or more readable. If the expressions involved get more complex, I'd even drop the ternary operator and use a good old if-else con...
python|python-3.x
3
1,961
67,747,066
create a function with dot: myfunc.print("Hello World") in python
<p>how do you define dotted function?</p> <p>i try this:</p> <pre class="lang-py prettyprint-override"><code>def myfunc.print(value) print(value); </code></pre> <p>but it's said &quot;Invalid syntax&quot;</p>
<p>Here's one way:</p> <pre><code>&gt;&gt;&gt; class myfunc: ... print = print ... &gt;&gt;&gt; myfunc.print(&quot;foo&quot;) foo </code></pre> <p>In this example, <code>myfunc</code> is actually a class, and <code>print</code> is a class attribute (which is initialized to point to the <code>print</code> function)....
python|function
-1
1,962
27,760,001
Unsupported characters in input (Python 2.7.9)
<p>A small question from a newbie. I am trying to do a little function where it randomizes the content of a text. </p> <pre><code>#-*- coding: utf-8 -*- import random def glitch(text): new_text = [''] for x in text: new_text.append(x) random.shuffle(new_text) return ''.join(new_text) </cod...
<pre><code>#-*- coding: utf-8 -*- import random def glitch(text): new_text = [''] for x in text: new_text.append(x) random.shuffle(new_text) return ''.join(new_text) print (glitch(u'Iàäï†n$§&amp;0ñŒ≥Q¶µù`o¢y”—œº')) </code></pre> <p>This should work, through a quick google search of my ow...
python-2.7|utf-8
0
1,963
65,681,284
Valid generic code to index 2D or 1D masked arrays into 1D arrays in Numpy
<p>I would like to have a valid code for either 2D or 1D masked array to extract a 1D array from it. In the 2D case, one column would be entirely masked and should be removed (this can be done as shown <a href="https://stackoverflow.com/questions/19380996/remove-columns-where-every-value-is-masked">in this question for...
<p>You can use <code>a = a[:, ~np.all(a.mask, axis=0)].squeeze()</code> for both cases (1D and 2D).</p> <p>In the 1D case of your example you get <code>b[:, ~np.all(b.mask, axis=0)]</code> which is <code>b[:, True]</code>. It seems that this should throw an indexing error but <code>True</code> behaves like <code>np.new...
python|arrays|numpy|multidimensional-array|dimensions
1
1,964
48,660,309
Add values from columns into a new column using pandas
<p>I have a dataframe:</p> <pre><code>id category value 1 1 abc 2 2 abc 3 1 abc 4 4 abc 5 4 abc 6 3 abc </code></pre> <p>Category <code>1 = best</code>, <code>2 = good</code>, <code>3 = bad</code>, <code>4 =ugly</code></p>...
<p>I think you need join string with column converted to string and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a> with join for second column:</p> <pre><code>d = {1:'best', 2: 'good', 3 : 'bad', 4 :'ugly'} df['new_col'] = 'cat_'+ d...
python|pandas
1
1,965
4,309,599
Fetching language detection from Google api
<p>I have a CSV with keywords in one column and the number of impressions in a second column.</p> <p>I'd like to provide the keywords in a url (while looping) and for the Google language api to return what type of language was the keyword in.</p> <p>I have it working manually. If I enter (with the correct api key): <...
<p>Try to add <code>referrer</code>, <code>userip</code> as described in <a href="http://code.google.com/apis/websearch/docs/reference.html#_intro_fonje" rel="nofollow noreferrer">the docs</a>:</p> <blockquote> <p>An area to pay special attention to relates to correctly identifying yourself in your requests. A...
python|api
1
1,966
48,273,967
ImportError: No module named 'requests.exceptions'
<p>Super new to coding and i'm trying to learn Python. I have used Anaconda to manage packages, etc. I typically update Anaconda/conda in cmd with commands such as <code>conda update conda</code> or <code>conda update anaconda</code></p> <p>As of late, when using these commands, it comes up with a message: "ImportErro...
<p>You should install requests with conda if you plan to use conda as your python environment.</p> <p><code>conda install requests</code></p>
python|anaconda|conda
3
1,967
51,275,928
How to call listener class in robot.api?
<p>I have a bunch of testsuites which are executed using robot.api. </p> <p>For Example,</p> <pre><code>from robot.api import TestSuite,ResultWriter tc_dict = { 'test case #1' : 'Passed' 'test case #2' : 'Failed' } suite = TestSuite('tests_with_listener.robot') for k,v in tc_dict.it...
<p>In the documentation for the <a href="http://robot-framework.readthedocs.io/en/v3.0.4/autodoc/robot.api.html" rel="nofollow noreferrer">robot.api</a> the note following note can be found: </p> <blockquote> <p>APIs related to the command line entry points are exposed directly via the robot root package.</p> </bl...
python|robotframework
2
1,968
51,150,583
How get python subprocess to run regex pattern without adding escape chars?
<p>I am trying to run locate from python3 using a basic regex pattern.</p> <pre><code>subprocess.run( ['locate', '-r', '\.[^\~]$'] ) </code></pre> <p>But subprocess is adding escape characters to the regex string. This seems to cause it to break.</p> <p>The completed process reports that it ran the regex string thus...
<p>So the question was invalid. But the answer, which is an answer to a different question, is instructive.</p> <p>this pattern worked</p> <pre><code>'.*[^~]$' </code></pre> <p>It was not necessary to escape the chars I had escaped in the first place, as @Wiktor says in his comment above.</p> <p>The confusion was o...
regex|python-3.x|subprocess|escaping|locate
1
1,969
73,643,416
Creating a very large 2D array without a major impact to code run time in Python
<p>I've been doing competitive programming (USACO) for a couple of months now, in which there are time constraints you cannot exceed. I need to create a large matrix, or 2d array, the dimensions being 2500x2500, in which each value is [0,0]. Using list comprehension is taking too much time, and I needed an alternative ...
<p><code>grid = [[[0,0] for i in range(2500)] for i in range(2500)]</code></p> <p>takes around 2.1 seconds on my PC, timing with PowerShell's <code>Measure-Command</code>. Now if the data specifications are strict, there is no magical way to make this faster. However, if the goal is to make this representation generate...
python|arrays|list|indexing|list-comprehension
1
1,970
64,318,416
unable to perform search on custom_field(JIRA-Python)
<p>I'm getting the below error when I search on custom_field.</p> <pre><code>{&quot;errorMessages&quot;:[&quot;Field \'customfield_10029\' does not exist or you do not have permission to view it.&quot;],&quot;warningMessages&quot;:[]} </code></pre> <ul> <li>But I have enough permissions(Admin) to access that field. And...
<p>Custom fields in JQL searches are referenced using the abbreviation 'cf' followed by their ID inside square brackets '[id]', so your URL would be:</p> <blockquote> <p>URL = 'https://xyz.atlassian.net/rest/api/2/search?jql=status=&quot;In+Progress&quot;+and+cf[10029]=125&amp;fields=id,key,status'</p> </blockquote> <p...
jira-rest-api|python-jira
2
1,971
69,836,399
Regex expression to apply it on dataframe (convert a string of hour and minutes to sum of minutes) - python
<p>I have a df and a column with strings that looks like following:</p> <pre><code>runtime 1h 38m 20h 4m 5h 45m empty </code></pre> <p>and I am trying to apply a function which will convert it to minutes.</p> <p>So far, I have come up with part of it:</p> <pre><code>def runtime_to_minutes(string): ...
<p>You can use</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({'runtime':['1h 38m','20h 4m','5h','45m','empty']}) df[['hours', 'minutes']] = df['runtime'].str.extract(r'(?=\d+\s*[hm]\b)(?:(\d+)\s*h)?(?:\s*(\d+)\s*m)?').fillna(0) df['minutes'] = df['hours'].astype(int) * 60 + d...
python|regex|dataframe
1
1,972
70,010,586
How to add an additional plot to multiple subplots
<p>I want to generate pairs of lineplots where one of them is used as a benchmark.</p> <p>I can generate a plot like this with the code below.</p> <p><a href="https://i.stack.imgur.com/lERyk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lERyk.jpg" alt="enter image description here" /></a></p> <p>ho...
<ul> <li>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html" rel="nofollow noreferrer"><code>pandas.DataFrmame.plot</code></a>, which, like <code>seaborn</code>, uses <code>matplotlib</code></li> </ul> <pre class="lang-py prettyprint-override"><code># convert the year column to an int ...
python|pandas|matplotlib|seaborn|subplot
1
1,973
72,889,843
Gathering entries in a matrix based on a matrix of column indices (tensorflow/numpy)
<p><strong>A little example to demonstrate what I need</strong></p> <p>I have a question about gathering in tensorflow. Let's say I have a tensor of values (that I care about for some reason):</p> <pre><code>test1 = tf.round(5*tf.random.uniform(shape=(2,3))) </code></pre> <p>which gives me this output:</p> <pre><code>&...
<p>You can use <a href="https://www.tensorflow.org/api_docs/python/tf/gather_nd" rel="nofollow noreferrer"><code>gather_nd()</code></a> for this. It can look a bit tricky to get this working. Let me try to explain this with shapes.</p> <p>We got <code>test1 -&gt; [2, 3]</code> and <code>test_ind_col_ind -&gt; [2, 5]</c...
python|numpy|tensorflow|pytorch
1
1,974
55,893,229
Unable to serve static file from flask server
<p>I have a index.html file, which has the absolute path 'c:\project\web\frontend\index.html'</p> <p>I am trying to return it using the following function</p> <pre><code>@webserver.route('/') def home() return webserver.send_static_file(path) </code></pre> <p>I have verified that the path is correct by accessin...
<p>I had to define the path to be the static_folder, when creating the flask object. Once I defined the folder to be static, the html page was served. </p>
python|flask
1
1,975
61,666,916
MLPRegressor not giving accurate results
<p>I have been given some years data of Ozone, NO, NO2 and CO to work on. The task is to use this data to predict the value of ozone. Suppose i have data of year 2015,2016,2018 and 2019. I need to predict ozone value of 2019 using 2015,2016,2018 data which is with me.</p> <p>Data format is hourly recorded and is pre...
<p>Such questions are actually difficult to answer exactly, since the answer depends crucially on the dataset used, which we don't have.</p> <p>Nevertheless, since your target variable seems to have a rather high dynamic range, you should try scaling it using a separate scaler; you should take care to inverse-transfor...
python|machine-learning|scikit-learn|neural-network
1
1,976
67,290,291
How do I use Python code for moving files
<p>I have 5 files and they exist in 5 different locations</p> <p>I would like to write a piece of code preferably in Python(I am a newbie) and the code should check all these 5 folders and code should check if the file exists, if it does, it should move over all those files from different locations to a single shared d...
<p>Speaking just about principles on how to solve your problem without writing any code:</p> <p>From the code you linked, you have a solution for copying one file at a time. Moving that code inside a function will let you easily re-use it for many different input files, and even more than one destination file. You can ...
python|move|shutil
1
1,977
69,005,945
Problem using CSV to query a website, input isn't right
<p>I am fairly new at python programming but have a column of terms I want to search a website for. The code is as follows:</p> <pre><code>import requests import pandas as pd from bs4 import BeautifulSoup as BS col_list = ['Molecular Formula'] #this is a column title in my csv file Chem = pd.read_csv('single.csv', use...
<p>You can use for-loop to iterate over the values in &quot;Molecular Formula&quot; column. For example:</p> <pre class="lang-py prettyprint-override"><code>import requests import pandas as pd from bs4 import BeautifulSoup as BS col_list = [&quot;Molecular Formula&quot;] # this is a column title in my csv file Chem =...
python-3.x|pandas|csv|web-scraping|beautifulsoup
2
1,978
68,407,029
can't import kornia.augmentation.functional
<p>I have installed kornia and imorting it like,</p> <pre><code>from kornia.color import * import kornia.augmentation.functional as F_k import kornia as K </code></pre> <p>but the second line is giving error</p> <pre><code>ModuleNotFoundError: No module named 'kornia.augmentation.functional'. </code></pre> <p>Also, th...
<p><code>kornia.augmentation.functional</code> was removed in version <a href="https://github.com/kornia/kornia/blob/master/CHANGELOG.md#054---2021-06-11" rel="nofollow noreferrer">0.5.4</a> and the most of the functions are available through <code>kornia.augmentation</code>.</p> <p>Regarding your second question, you ...
python|machine-learning|computer-vision|kornia
1
1,979
59,238,586
Where are stored wheels .whl cached files?
<pre><code>$ python3 -m venv ~/venvs/vtest $ source ~/venvs/vtest/bin/activate (vtest) $ pip install numpy Collecting numpy Cache entry deserialization failed, entry ignored Using cached https://files.pythonhosted.org/packages/d2/ab/43e678759326f728de861edbef34b8e2ad1b1490505f20e0d1f0716c3bf4/numpy-1.17.4-cp36-cp36...
<p>The message</p> <pre><code>Using cached https://files.pythonhosted.org/packages/d2/ab/43e678759326f728de861edbef34b8e2ad1b1490505f20e0d1f0716c3bf4/numpy-1.17.4-cp36-cp36m-manylinux1_x86_64.whl </code></pre> <p>means pip is using the HTTP cache, not the wheel cache (which is only used for locally-built wheels, like...
python|pip|python-wheel
6
1,980
59,371,631
Send automated messages to Microsoft Teams using Python
<p>I want to run a script of Python and in the end send the results in a text format to a couple of employees through MS Teams</p> <p>Is there any already build library that would allow me to send a message in Microsoft Teams through Python code?</p>
<p><strong>1. Create a webhook in MS Teams</strong></p> <p>Add an incoming webhook to a Teams channel:</p> <ol> <li>Navigate to the channel where you want to add the webhook and select (•••) <em>Connectors</em> from the top navigation bar.</li> <li>Search for <strong>Incoming Webhook</strong>, and add it.</li> <li>Clic...
python|microsoft-teams
96
1,981
62,310,477
SQLAlchemy: How to set alias for insert statement?
<p>Need such a request:</p> <pre class="lang-sql prettyprint-override"><code> INSERT INTO public.cm_floor as r (load_date, centre, id_floor, name_floor) VALUES (now(), 'CentreName', 12345678, 'Floor 2') ON CONFLICT ON CONSTRAINT cm_floor_pkey DO UPDATE SET load_date=now(), centre=excluded.na...
<p>my solution to the problem:</p> <pre class="lang-python prettyprint-override"><code>filter = [c != insert_stmt.excluded[c.name] for c in table.c if (not c.primary_key and c.name != "load_date")] do_update_stmt = insert_stmt.on_conflict_do_update(index_elements=primary_keys, set_=update_column, where=or_(*filter)) ...
python|postgresql|sqlalchemy
1
1,982
31,438,147
Saving a string in python associated with an API
<p>it is my first post on stackoverflow so please go easy on me! :) I am also relatively new to python so bear with me :)</p> <p>With all that said here is my issue: I am writing a bit of code for fun which calls an API and grabs the latest Bitcoin Nonce data. I have managed to do this fine, however now I want to be a...
<p>A very simple-minded solution:</p> <pre><code>import time nonce = "some string" while True: latest_nonce = client.block_latest()['nonce'] if latest_nonce != nonce: nonce = latest_nonce time.sleep(2) </code></pre> <p>Ideally you should use something like asyncio for unblocking execution.</p>
python|bitcoin
0
1,983
59,510,166
Tensorflow apparently installs OK but then fails check
<p>I'm using Debian 10.2 (buster) and followed the procedure on <a href="https://www.tensorflow.org/install/pip?lang=python3" rel="nofollow noreferrer">https://www.tensorflow.org/install/pip?lang=python3</a> , using the virtual environment procedure as recommended. Everything works, down to and including:</p> <pre><co...
<p><a href="https://www.tensorflow.org/install/pip" rel="nofollow noreferrer">https://www.tensorflow.org/install/pip</a> says: </p> <blockquote> <p>Starting with TensorFlow 1.6, binaries use AVX instructions</p> </blockquote> <p>My box says "Core i7" on the outside, but my /proc/cpuinfo gives the following flags: f...
python-3.x|tensorflow
1
1,984
30,693,797
How to display new or modified lines between two files using Python
<p>I have two files: file1.txt and file2.txt. I would like to only display the lines in result2.txt that are new / different from those in result1.txt. </p> <p>I do this in bash using the following command:</p> <blockquote> <p>diff file1.txt file2.txt | grep -E "^>" | sed 's/^..//'</p> </blockquote> <p>Is this ach...
<p>See <a href="https://docs.python.org/2/library/difflib.html" rel="nofollow">difflib</a> a Python library for exactly this</p>
python-2.7|diff
1
1,985
30,407,216
Google Fusion Maps Info Window Dynamic Templating
<p>I'm doing some web scraping with Python and the last step is to use Google Fusion maps, but as somebody who has never touched any CSS styling before, I have no idea how to do something probably incredibly simple: <strong>hide a column title in the info window if it's blank.</strong> Not all the data have entries in ...
<p>This question isn't related to CSS, try this:</p> <pre><code>{template .contents} &lt;div class='googft-info-window'&gt; &lt;b&gt;Location:&lt;/b&gt; {$data.value.Location}&lt;br/&gt; &lt;b&gt;Movie Title:&lt;/b&gt; {$data.value['Movie Title']}&lt;br/&gt; &lt;b&gt;Date:&lt;/b&gt; {$data.value.Date}&lt;br/&gt; {if $...
python|css|google-maps|google-fusion-tables
0
1,986
72,296,016
How to change a string to NaN when applying astype?
<p>I have a column in a dataframe that has integers like: <code>[1,2,3,4,5,6..etc]</code></p> <p>My problem: In this field one of the field has a string, like this: <code>[1,2,3,2,3,'hello form France',1,2,3]</code></p> <p>the Dtype of this column is object.</p> <p>I want to cast it to float with <code>column.astype(fl...
<p>You can use <code>pd.to_numeric</code> with <code>errors='coerce'</code></p> <pre><code>import pandas as pd df = pd.DataFrame({ 'all_nums':range(5), 'mixed':[1,2,'woo',4,5], }) df['mixed'] = pd.to_numeric(df['mixed'], errors='coerce') df.head() </code></pre> <p>Before:</p> <p><a href="https://i.stack.imgur...
pandas|jupyter-notebook
1
1,987
50,760,952
How to access python flask application in windows when running it in a linux container?
<p>I am working on a microservice written in python. My microservice works fine on my windows machine and I can easily test it. However, on my Linux container it may work fine too but I cannot test it. Even when optimizing my code for network access as explained <a href="https://stackoverflow.com/a/7027113/1987258">her...
<p>The command</p> <pre><code>docker run -p 5002:5002 docktoflask </code></pre> <p>means that the internal container port 5002 will be exposed as host port 5002 (localhost:5002), even if the internal container port 5002 is not opened yet.</p> <p>You have to change this to </p> <pre><code>docker run -p 5000:5000 doc...
python-3.x|docker|networking|flask
1
1,988
35,256,545
Checking the clickability of an element in selenium using python
<p>I've been trying to write a script which will give me all the links to the episodes present on this page :- <a href="http://www.funimation.com/shows/assassination-classroom/videos/episodes" rel="nofollow">http://www.funimation.com/shows/assassination-classroom/videos/episodes</a></p> <p>As you can see that the link...
<p>You don't need to use <code>BeautifulSoup</code> here at all. Just grab all the links via <code>selenium</code>. Proceed to next page only if the <code>&gt;</code> link is visible. Here is the complete implementation including gathering the links, necessary waits. It should work for any page count:</p> <pre><code>i...
python|python-2.7|selenium|phantomjs
1
1,989
26,848,690
how can I track a specific item presence in hierarchy clustering
<p>I have a question related to hierarchy clustering. I have a relative complex data sets with 2000 items/samples. I cluster the items using scipy and give the clusters different cutoff e.g. from 0.1 -0.9</p> <pre><code>from scipy.cluster import hierarchy as hac Z=hac.linkage(distance, single,'euclidean') results=hac....
<p>Try to build a set of Clusters IDs using <code>set(list(..))</code> to remove duplicates, then go through the elements and filter your data depends on the cluster where they belong. Give it a try, as you didn't give a sample of data to test it. </p> <p>Your code would look like:</p> <pre><code>clusterIDs = set(lis...
python|scipy|hierarchical-clustering|dendrogram
0
1,990
57,871,129
Filter dataframe based on groupby sum()
<p>I want to filter my dataframe based on a groupby sum(). I am looking for lines where the amounts for a spesific date, gets to zero. </p> <p>I have solve this by creating a for loop. I suspect this will reduce performance if the dataframe is large.</p> <p>It also seems clunky.</p> <pre><code>newdf = pd.DataFrame...
<p>Just use basic numpy :) </p> <pre class="lang-py prettyprint-override"><code>import numpy as np df = newdf.groupby(['tdate'])[['tamount']].sum().reset_index() dates = df['tdate'][np.where(df['tamount'] == 0)[0]] newdf[np.isin(newdf['tdate'], dates) == True] </code></pre> <p>Hope this helps; let me know if you h...
python-3.x|pandas-groupby
0
1,991
69,403,518
Python folder paths on synched pcs
<p>I use .py files on two different pcs and synch the files using google drive. As I handle files quite often with subfolders I use the complete path to read csv</p> <pre><code>passport = pd.read_csv(r'C:\Users\turbo\Google Drive\Studium\Master_thesis\Python\Databases\passport_uzb.csv') </code></pre> <p>However, when s...
<p>You can use a <em>relative</em> path to access the CSV instead of an <em>absolute</em> one. The <a href="https://docs.python.org/3/library/pathlib.html" rel="nofollow noreferrer"><code>pathlib</code></a> module is useful for this. For example, assuming your script is directly inside the <code>...Python/Databases</co...
python|file|directory|operating-system
1
1,992
55,238,507
Stop sqlalchemy from managing the connection
<p>I'm trying to initialize SQLAlchemy with existing DB connection, but I would like it to completely stop managing it (opening, closing, rolling back etc). This is because I use it alongside a different ORM (django) and SQLAlchemy is really only a way to perform more complicated queries. It's gonna be used for reads o...
<p>Ok, I think I've found a way that "works":</p> <pre><code>from django.conf import settings from django.db import connection from sqlalchemy.pool import NullPool from sqlalchemy import create_engine as sa_create_engine def do_nothing(dbapi_connection): return def create_engine(db_name='default'): db = sett...
python|sqlalchemy
0
1,993
54,171,922
Machine Learning: Question regarding processing of RGBD streams and involved components
<p>I would like to experiment with machine learning (especially CNNs) on the aligned RGB and depth stream of either an Intel RealSense or an Orbbec Astra camera. My goal is to do some object recognisation and highlight/mark them in the output video stream (as a starting point). </p> <p>But after having read many artic...
<ul> <li>Your assumptions are correct: the data acquisition flow is: <code>sensor -&gt; driver -&gt; camera library -&gt; other libraries built on top of it</code> (see OpenCV support for Intel RealSense)<code>-&gt; captured image.</code> Once you got the image, you can do whatever you want of course.</li> <li>The vari...
opencv|tensorflow|openni|realsense|orbbec
1
1,994
45,369,097
python - binary encoding of column containing multiple terms
<p>I need to do a binary transformation of a column containing lists of strings separated by <code>comma</code>.</p> <p>Can you help me in getting from here:</p> <pre><code>df = pd.DataFrame({'_id': [1,2,3], 'test': [['one', 'two', 'three'], ['three', 'one'], ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.get_dummies.html" rel="nofollow noreferrer"><code>str.get_dummies</code></a>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pop.html" rel="nofollow noreferrer"><code>pop</code></a> for extra...
python|pandas
4
1,995
28,843,441
Printing regression results from python statsmodel into a Excel worksheet
<p>My job requires running several regressions on different types of data and then need to present these results on a presentation - I use Powerpoint and they link very well to my Excel objects such as charts and tables</p> <p>Is there a way to print the results into a specific set of cells in an existing worksheet?</...
<pre><code>import pandas as pd import statsmodels.api as sm dta = sm.datasets.longley.load_pandas() dta.exog['constant'] = 1 res = sm.OLS(dta.endog, dta.exog).fit() df = pd.concat((res.params, res.tvalues), axis=1) df.rename(columns={0: 'beta', 1: 't'}).to_excel('output.xls', 'sheet1') </code></pre>
python|statistics|export-to-excel|statsmodels
1
1,996
15,310,391
Access Python Wrapper from ASP Classic
<p>I have written a python wrapper for a c dll. </p> <p>I now wish to interact with this wrapper from an ASP classic script, served online via IIS7.</p> <p>How would you recommend I do this?</p>
<p>If it's a Python wrapper, you need Python to use it. You can use Python as a scripting language from ASP, I recommend activestate's Python distribution, because it integrates with Windows and IIS by default. </p> <p>You should be able to write an ASP page in Python and load your library in it. <a href="http://docs...
python|iis|asp-classic
0
1,997
53,506,845
Generating a custom ID based on other columns in python
<p>I have a pandas df which looks like this</p> <pre><code> UID DOB BEDNUM 0 1900-01-01 CICU1 1 1927-05-21 CICU1 2 1929-10-03 CICU1 3 1933-06-29 CICU1 4 1936-01-09 CICU1 5 1947-11-14 CICU1 6 1900-01-01 CICU1 7 1927-05-21...
<p>This answer assumes that <code>DOB</code> is <code>datetime</code>:</p> <pre><code>year = df.DOB.dt.year nums = df.UID.astype(str).str.zfill(7) df.assign(TID=[f'{y}-{num}-P' for y, num in zip(year, nums)]) </code></pre> <p></p> <pre><code> UID DOB BEDNUM TID 0 0 1900-01-01 CICU1 1900-0...
python|string|pandas|dataframe
2
1,998
53,555,709
Jupyter notebook fails with "Kernel didn't respond"
<p>I am running into a strange bug related to the sequential execution of Jupyter notebooks (Python 3 kernels). The main loop runs sequentially the following execution of a set of notebooks through <code>nbconvert</code></p> <pre><code>[...] from nbconvert.preprocessors import ExecutePreprocessor [...] class Report: ...
<p>After some digging, I figured out that I could reduce the problem to the following minimal code</p> <pre><code>from nbconvert.preprocessors import ExecutePreprocessor ep = ExecutePreprocessor(kernel_name="python3") km, kc = ep.start_new_kernel() km.shutdown_kernel() </code></pre> <p>On the cloud server, the scrip...
python|jupyter-notebook|conda
1
1,999
55,086,727
After reading csv file, is infinite returns true
<p>I am doing a simple read_csv() on a 1 year stock data downloaded from Yahoo finance.</p> <pre><code> df2 = pd.read_csv(name2, index_col=0, parse_dates=True) </code></pre> <p>This is for stock market prediction algorithm. The problem is, <code>np.isfinite(df2.all()))</code> is returning true for all the columns and...
<p>Actually the function is called isfinite, and it returns TRUE if the data is finite, false if the data is infinite or not a Number. Therefore I really believe the return True is what you would have expected in this case. </p> <p>Please refer to: <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/n...
python|pandas
1