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 |
|---|---|---|---|---|---|---|
9,800 | 65,229,194 | How to get Python to make leap yr function similar to range (start, stop, step)? | <p>I am trying to create a function for leap year and then create a generator that will function like the range(start, stop, step) command. For some reason my code below is not printing whether the written year is a leap year or not. I keep getting False when I type in known leap years and I 'm not sure what I did wron... | <p>You need to return <code>leap</code>. You're setting the variable, but then ignoring it.</p>
<p>Also, your tests are in the wrong order. If the year is divisible by 100, it will also be divisible by 4, so the first <code>if Y % 4 == 0:</code> condition will be true. <code>elif</code> conditions are only tested if al... | python|python-3.x|range|generator | 1 |
9,801 | 71,785,638 | What is the difference between Activation layer and activation keyword argument | <p>guys what is the difference between <code>activation</code> kwarg and <code>Activation</code> layer in tensorflow?</p>
<p>here's an example :</p>
<p><code>activation</code> kwarg :</p>
<pre><code>model.add(Dense(64,activation="relu"))
</code></pre>
<p><code>Activation</code> layer :</p>
<pre><code>model.ad... | <p>In <code>Dense(64,activation="relu")</code>, the <code>relu</code> activation function becomes a part of <code>Dense</code> layer, and will be called automatically whenever this <code>Dense</code> layer is called.</p>
<p>In <code>Activation("relu")</code>, the <code>relu</code> activation functio... | python|tensorflow|keras | 1 |
9,802 | 10,669,933 | When calling recv() the program works very slowly | <p>My code is: <a href="http://ideone.com/nVXIQ" rel="nofollow">http://ideone.com/nVXIQ</a>.</p>
<p><code>recv()</code> functions always idling (it works very slow); it takes several seconds to get the result, and <code>recv()</code> should handle quickly such small amount of data.</p> | <p>Is your question about recv's blocking behavior? If so, then investigate using non-blocking IO with something like a select/poll loop.</p> | response|winsock|python-idle|recv|performance | 2 |
9,803 | 5,559,349 | python regular expression | <p>whats the regular expression in python for any string without the char '/'. Thanks</p> | <p>No need for regular expressions</p>
<pre><code>>>> s = 'asdf'
>>> '/' in s
False
>>> s = 'asd/asdf'
>>> '/' in s
True
</code></pre> | python|regex | 8 |
9,804 | 62,723,857 | How to capture unknown number of words in between a negative lookbehind catch term regex? | <p>I am trying to exclude records which have the word "owner" somewhere preceding the word "dog"</p>
<ul>
<li>the owner has a dog (exclude)</li>
<li>the owner has a black and brown dog (exclude)</li>
<li>John has a dog (include)</li>
<li>John has a black and brown dog (include)</li>
</ul>
<p>Here is... | <p>You can use the following regular expression to verify that the string contains the word "dog" that is not preceded by the word "owner".</p>
<pre><code>^(?:(?!\bowner\b).)*\bdog\b
</code></pre>
<p><a href="https://regex101.com/r/S8OJgx/1/" rel="noreferrer">Start your engine!</a> <sub><sup><</s... | python|regex|data-mining | 5 |
9,805 | 61,796,218 | How to list all files inside the folder of sharepoint using python | <p>I'm currently using shareplum and was able to do the download thing using this code below:</p>
<pre><code>from shareplum import Site
from shareplum import Office365
from shareplum.site import Version
import csv
authcookie = Office365('https://bboxxeng.sharepoint.com/', username='---', password='---').GetCookies()... | <p>I understand you want to list all files in a folder so that you can download or do other modification via the file name. If so, you can get it via below attrbutes:</p>
<p><a href="https://shareplum.readthedocs.io/en/latest/objects.html#files" rel="nofollow noreferrer">files</a></p>
<pre><code>folder = site.Folder(... | python|python-3.x|sharepoint|office365 | 4 |
9,806 | 64,323,157 | Issue while converting object type to int | <p>I have a lengthy python code in which I was changing the data types of few of the columns from object to int or float using below method</p>
<pre><code>df['a'] = df['a'].astype('int')
df['b'] = df['b'].astype('int')
</code></pre>
<p>However I got below error after this conversion</p>
<pre><code>int() argument must b... | <p>You got that error because that column has at least one python <code>method</code> object in it. Its likely the whole column is filled with a method. Now I have to speculate because you haven't given us enough information, but this is easy to do accidently if you misapply a <code>ufunc</code> by neglecting to call i... | python|dataframe|object|type-conversion|integer | 0 |
9,807 | 11,435,102 | Is there a good way to produce documentation for swig interfaces? | <p>I'd like to know if there are any good techniques for constructing/maintaining
documentation on the interface.</p>
<p>I'm building an interface from c++ code to python using swig; mostly I'm just
%including the c++ header files. I'm dealing with at least dozens of classes
and 100's of functions, so automated tools... | <p>To get your doxygen comments into the python files there exists a python tool called doxy2swig.py on the web as described <a href="http://www.enricozini.org/2007/tips/swig-doxygen-docstring/" rel="noreferrer">here</a>.</p>
<p>Create xml documentation from your code. Then use the tool:</p>
<blockquote>
<p>doxy2sw... | python|documentation|swig | 9 |
9,808 | 56,563,876 | How to Identify two or three pattern in a string and delete all the elements from the first identification to last? | <p>My test text <code>u = ' Danish Phone is the work number Contact Type'</code>.</p>
<p>The regex pattern i used to identify three words <code>(Phone|Contact|Type)</code>.</p>
<p>This is perfectly identifying the words, Now I want to replace all the words from <strong>Phone</strong> to <strong>type</strong> with... | <pre><code>import re
u = ' Danish Phone is the work number Contact Type'
u = re.sub('Phone.*?Type', '', u).strip()
</code></pre>
<p><code>.*</code> is to match all characters between <code>Phone</code> and <code>Type</code>.</p>
<p>The <code>?</code> is used for non-greedy searches. </p>
<blockquote>
<p>the n... | regex|python-3.x | 2 |
9,809 | 56,609,075 | Why is multiprocessing not working with python dash framework - Python3.6 | <p>I'm trying to implement multiprocessing library for splitting up a dataframe into parts, process it on multiple cores of CPU and then concatenate the results back into a final dataframe in a python dash application. The code works fine when I try it outside of the dash application (when I run the code standalone wit... | <p>Okay I've figured it out now!. The problem is that the function calc_tfidf was not defined as a global function. I changed the function to be a global function and it worked perfect.</p>
<p>Simple checks when left unsolved at times might lead to days of redundant efforts! :(</p> | python-3.x|multiprocessing|plotly-dash | 1 |
9,810 | 56,803,330 | How to properly authenticate using Python requests via a POST request | <p>I am using the REST API for iObeya, I wish to use Python Requests but currently I cannot authenticate with the server. The documentation states that you can authenticate using a POST request and upon return, you should get a cookie called 'JSESSIONID' when the auth is correct.</p>
<p>So far I have this:</p>
<pre><... | <p>It just wants you to make a normal POST with <code>username</code> and <code>password</code>.</p>
<pre><code>auth_url = 'https://link-to.com/iobeya/j_spring_security_check'
session = requests.Session()
auth = session.post(auth_url, data={'username': username, 'password': password})
</code></pre> | python|rest|python-requests | 2 |
9,811 | 18,162,452 | How to implement smooth tile based movement | <p>The player in my game is centered in the screen, and I 'scroll' the background to move around.</p>
<p>I get a list of keys pressed with <code>pygame.key.get_pressed()</code>, if the player's move cooldown is over, I call a move function. This function scrolls the map in the direction of movement for one tile.</p>
... | <p>Animations and movement are all about what you perceive rather than what's actually happening. In a grid system, you can abstract the visual movement of the player away from the actual mechanics by taking the drawing part of the code and updating the draw position independently of the gameplay position. </p>
<p>The... | python|pygame | 1 |
9,812 | 18,137,241 | string match in Python | <p>I have 300K strings stored in the list, and the length of each string is between 10 and 400. I want to remove the ones that are substring of other strings (the strings with shorter length have higher probability to be the substring of others). </p>
<p>Currently, I first sort these 300K strings based on length, then... | <p>You could use a <a href="http://en.wikipedia.org/wiki/Suffix_tree" rel="nofollow">suffix tree</a>. It will get you to O(mn) where m is the length of the strings. It's still quadratic, but since m << n in your case, it would provide a noticeable improvement.</p>
<p><a href="http://www.csse.monash.edu.au/~lloyd... | python|algorithm|string-matching | 2 |
9,813 | 60,841,716 | Is there a way to save data in named Excel cells using Python? | <p>I have used openpyxl for outputting values in Excel in my Python code. However, now I find myself in a situation where the cell locations in excel file may change based on the user. To avoid any problems with the program, I want to name the cells where the code can save the output to. Is there any way to have Python... | <p>For a workbook level defined name</p>
<pre class="lang-py prettyprint-override"><code>import openpyxl
wb = openpyxl.load_workbook("c:/tmp/SO/namerange.xlsx")
ws = wb["Sheet1"]
mycell = wb.defined_names['mycell']
for title, coord in mycell.destinations:
ws = wb[title]
ws[coord] = "Update"
wb.save('upd... | python|excel|openpyxl | 1 |
9,814 | 60,800,612 | Matplotlib Read in time as value from CSV | <p>I am new to python coding but have been playing for a while
I build out a reader that takes Amp readings from my circuit breaker box and want to graph it</p>
<p>I am trying to graph date from a CSV file using matplotlib.
I am reading in a CSV file like this:(this is a small sample I take a reading every minute)</p>... | <p>You can try something like the following code:</p>
<pre><code>import matplotlib.pyplot as plt
import pandas as pd
csv_data = pd.read_csv('bob1.csv', index_col= 'Time')
data = pd.DataFrame(csv_data)
plt.xlabel('Time')
wathever = plt.plot(data['Unnamed: 1'], 'k', label='')
plt.title('')
plt.legend(title='')
plt.sho... | python|numpy|matplotlib|time | 0 |
9,815 | 66,062,836 | How to substract columns in pandas df based on condition | <p>I have a dataset which looks like this. In my new dataset, I want to subtract the amount column(s) with principal column(s) and remainder(s) column.</p>
<p>For instance, if the <code>amount</code> column is 4, the <code>principal</code>column is 2 and <code>remainder</code> is 3, then the first amount column must be... | <p>You can use <code>defaultdict</code> to group common suffixes, then apply a reducing function (<code>np.subtract.reduce</code>) to get your output:</p>
<pre><code>from collections import defaultdict
mapping = defaultdict(list)
for column in df:
if column[-1] != 4:
mapping[f"newamount{column[-1]}&qu... | python|pandas | 0 |
9,816 | 66,148,055 | Super column from multiple columns | <p>I have five columns in a dataframe as below :</p>
<pre><code>Name, address, phone_number, height, weight
</code></pre>
<p>I want these columns to have a higher level column such as personal details having name, address and phone_number and physical parameters having height and weight.</p>
<p>How can this be done?</p... | <p>Since your data has only five columns, you can try:</p>
<pre><code>df.columns = pd.MultiIndex.from_tuples([('personal details', 'name'),
('personal details', 'address'),
('personal details', 'phone_number'),
... | python|pandas|dataframe | 0 |
9,817 | 69,042,685 | How to highlight the hyperlinked cell in the openpyxl | <p>I want to highlight the cell which is hyperlinked, that means when you click the cell is sheet1 and it hyperlinks to sheet2 the sheet2 cell must highlight.</p> | <p>You can add the content below in the cell, then you can click hyperlink "sheet2" and navigate to sheet2 A3 cell</p>
<pre><code>=HYPERLINK("#Sheet2!A3", "sheet2")
</code></pre> | python|openpyxl | -1 |
9,818 | 68,131,434 | Pytorch custom model automatically stored in cuda | <p>I built a custom NN model like so:</p>
<pre class="lang-py prettyprint-override"><code>class MyNNet(torch.nn.Module):
def __init__(self, inp_dim, n_classes):
super(MyNNet, self).__init__()
self.flat = torch.nn.Flatten()
self.l1 = torch.nn.Linear(inp_dim * inp_dim, 32)
self.l2 = torch.nn.Linear(3... | <p>Unlike <code>Module</code>s (where <code>.to(...)</code> works in-place), when moving <code>Tensor</code>s to a device, you need to reassign them:</p>
<pre class="lang-py prettyprint-override"><code>s = s.to(device)
c = c.to(device)
</code></pre> | machine-learning|deep-learning|computer-vision|pytorch | 0 |
9,819 | 68,222,213 | How to group, sum up and calculate a mean of every other element in a column? | <p>In my dataframe I have a number of names (string), dates (datetime64), and amount of observations (num).</p>
<pre><code>In [8]: df
Out[8]:
name date num
0 a 1 3
1 a 2 4
2 a 3 9
3 b 1 6
4 b 2 8
5 b 3 3
</code></pre>
<p>What I want is to calculate for ... | <p>Use <code>groupby</code> with <code>expanding</code> and <code>mean</code>:</p>
<pre><code>df['avg'] = df.groupby('name')['num'].expanding().mean().reset_index(level=0, drop=True)
</code></pre>
<p>Output:</p>
<pre><code> name date num avg
0 a 1 3 3.000000
1 a 2 4 3.500000
2 a 3 ... | python|pandas | 3 |
9,820 | 59,081,754 | benefit of Django REST Framework when using django with API like calls? | <p>reading <a href="https://stackoverflow.com/questions/24402017/django-how-to-integrate-django-rest-framework-in-an-existing-application/24402271">This question</a> it looks like I can setup DRF within an existing django project.</p>
<p>That got me thinking... I have a django application that uses ajax calls which re... | <p>The bottleneck of the DRF is in Serializers. So the hardest part is for serializing the model and deserializing the request. That's why if you are using it only for this type of small snippet, then I would not suggest using DRF. You'd better use it only if you have more than 10 API views.</p> | python|django|django-rest-framework | 2 |
9,821 | 59,416,197 | Forming a list of tuple from unequal length of elements inside a dictionary | <p>I have a dictionary with unequal length of values. </p>
<p>Example:</p>
<pre><code>d= {'190': ['229'], '192': ['205'], '193': ['259'], '194': ['196', '204', '242', '249', '254', '266', '299', '302', '346'], '195': ['218', '273', '275', '306', '328'], '196': ['204', '249', '254', '266', '285', '330', '346'], '197':... | <p>You use the same iterator twice, hence that means every value in the original list is yielded once.</p>
<p>You can for example work with <code>islice</code> of <code>itertools</code>, to refer both to the list, and its "tail". In the case the length of the list is one, it is probably the simplest to wrap that value... | python|list|dictionary | 0 |
9,822 | 59,398,319 | Bbox malfunction on both axis | <p>I am making a test for a Tkinter project, which will have some mini-games in the software (sort of like Mario paint). For this test, I have 2 boxes, one colored red and the other is blue but when it is next to or inside the red box it turns green.</p>
<p>Here is the code.</p>
<pre class="lang-py prettyprint-overri... | <p>You can use <a href="http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.find_overlapping-method" rel="nofollow noreferrer">Canvas.find_overlapping()</a>
to test if moving rectangle overlaps other objects.</p>
<pre><code>a = Test.bbox(Move)
#b = Test.bbox(Hitd)
if Hitd in Test.find_overlapping(*a):
Test.i... | python|tkinter|tkinter-canvas | 1 |
9,823 | 72,967,947 | Issue with using os.system to call another script | <p>I am working on another issue which requires me to use os.system() to call another python script. I know that subprocess is the better solution but for what I'm trying to do but I can't use that and am stuck with os.system(). I set up a small test program as follows to try and figure out os.system():</p>
<p>sript1.p... | <p>Thanks to the above comments, the solution is that script1.py should read</p>
<pre><code>os.system("py C:/Users/user/Documents/code/test/called_script.py")
</code></pre>
<p>Because Windows does not know what to do with a .py file otherwise.</p> | python|printing|os.system | 1 |
9,824 | 72,909,710 | Separation of the dataframes by row values | <p>I want to split my dataframe based on the first row to generate four separate dataframes (for subgroup analysis). I have a 172x106 Excel file, where the first row consists of either a 1, 2, 3, or 4. The other 171 lines are radiomic features, which I want to copy to the ''new'' dataset. The columns do not have header... | <p>First of all, after importing the dataframe, sort the value of the first row in order</p>
<pre><code>df
Out[26]:
0 1 2 3
0 0 1 0 1
1 1 2 5 8
2 2 3 6 9
3 3 4 7 0
df = df.sort_values(by = 0, axis = 1)
Out[30]:
0 2 1 3
0 0 0 1 1
1 1 5 2 8
2 2 6 3 9
3 3 7 4 0
</code></pre>... | python|pandas|dataframe | 0 |
9,825 | 62,905,120 | Why doesn't my callback in Dash take any output? | <p>After many tries and research, I can't figure out why, but any target for this callback's output will return a key_error.</p>
<p><strong>layout :</strong></p>
<pre><code>...
app = DjangoDash('liste_app', serve_locally=True)
app.layout = ...
...
...
html.Div(className='card-body',
children=[
... | <p>I finally found out what I did wrong : If there is only one Outpput, it must not be in a list.</p>
<p>This is my code, returning key_error :</p>
<pre><code>@app.expanded_callback(
[Output('sorted_storage', 'data')],
[Input('insert', 'n_clicks')],
[State('tabs', 'value')]
)
</code></pre>
<p>This is correct code worki... | python|plotly-dash | 1 |
9,826 | 63,221,941 | Python not getting called(?) in React/Flask Project | <p>Summary: I am trying to teach myself Flask and React with the tools I have at hand during the pandemic. I am hampered by the lack of a good React editor for remote files, I suspect I may not be seeing error messages such an editor would be showing me, and I suspect that the python script I am trying to invoke is n... | <p>You may be seeing an infinite loop, where state is not having a chance to update.</p>
<p>Try this:</p>
<pre><code>@app.route('/time')
def get_current_time():
print( time.time() )
return {'time': time.time()}
</code></pre>
<p>Is <code>/time</code> getting hits? Because your <code>useEffect()</code> code will... | python|python-3.x|reactjs|flask | 1 |
9,827 | 63,251,437 | FutureWarning get_params from scikit-learn | <p>I am getting the warning</p>
<pre><code>File "[...]\lib\threading.py", line 890, in _bootstrap
self._bootstrap_inner()
File "[...]\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Program Files\JetBrains\PyCharm 2019.1.3\plugins\python\helpers\pydev\_pydevd_bundle\pyd... | <p>I think, I was able to find the answer by luck. As described in scikit-learn's <a href="https://scikit-learn.org/stable/developers/develop.html#instantiation" rel="nofollow noreferrer">documentation</a>, the initialization <em>must</em> look like</p>
<pre><code>def __init__(self, param1=1, param2=2):
self.param1... | python|scikit-learn|warnings | 5 |
9,828 | 35,492,703 | Importing sklearn from a local directory | <p>I am using anaconda distribution over a server with no root access. In order to use sklearn latest version I installed it into my home directory [/hone/ram] and it is installed at <code>/home/ram/local/lib/python27/site-packages/</code></p>
<p>Now I want to use this version of sklearn instead of the default versio... | <p>make sure that your custom folder appears before system ones in <code>sys.path</code>. I guess, you need to use <a href="https://docs.python.org/2/tutorial/datastructures.html#more-on-lists" rel="nofollow">sys.path.insert(0, "/my/path")</a> instead of <code>sys.path.append</code></p> | python|python-2.7|import|ipython|package | 0 |
9,829 | 58,857,899 | Softmax or sigmoid for multiclass problem | <p>I am using VGG16 model and fine tuned them on my data. I am predicting ethnicity of images (faces) .i have 5 output classes like white, black,Asian, Sub-continent and others. Should i use softmax or sigmoid. And why?? </p> | <p>Sigmoid:</p>
<p><a href="https://i.stack.imgur.com/8J3FG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8J3FG.png" alt="enter image description here"></a></p>
<p>Softmax:</p>
<p><a href="https://i.stack.imgur.com/umqR1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/umqR1.pn... | python|image-processing|deep-learning|data-science | 1 |
9,830 | 58,664,419 | Is it necessary to use StandardScaler on y_train and y_test? If yes, cases? | <p>Have read multiple cases where StandardScaler is used on y_train and y_test and also where it is not used. Is there any specific rules where it should be used on them?</p> | <p>Quoting from <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html" rel="nofollow noreferrer">here</a>:</p>
<blockquote>
<p>Standardization of a dataset is a common requirement for many machine
learning estimators: they might behave badly if the individual
featur... | python|python-3.x|pandas|scikit-learn|data-science | 1 |
9,831 | 73,355,137 | Inputting data from a webscraped page using Python | <p>I have looked through stackoverflow and am unable to find the answer I am looking for, or understand if the answer given by another post is the answer I am looking for.</p>
<p>So what I would like to do is pull from a webpage, that has an input box, enter data into that input box, and get the return result.</p>
<p>W... | <p>This is one way of inputting the caseid into that page, and clicking Submit, using Selenium:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.su... | python|html|web-scraping|input|beautifulsoup | 0 |
9,832 | 25,049,498 | Failed to catch syntax error python | <pre><code>try:
x===x
except SyntaxError:
print "You cannot do that"
</code></pre>
<p>outputs</p>
<pre><code> x===x
^
SyntaxError: invalid syntax
</code></pre>
<p>this does not catch it either</p>
<pre><code>try:
x===x
except:
print "You cannot do that"
</code></pre>
<p>Other errors like ... | <p>You can only catch <code>SyntaxError</code> if it's thrown out of an <code>eval</code>, <code>exec</code>, or <code>import</code> operation.</p>
<pre><code>>>> try:
... eval('x === x')
... except SyntaxError:
... print "You cannot do that"
...
You cannot do that
</code></pre>
<p>This is because, no... | python|error-handling | 54 |
9,833 | 60,200,244 | Why does setting hue in seaborn plot change the size of a point? | <p>The plot I am trying to make needs to achieve 3 things.</p>
<ol>
<li>If a quiz is taken on the same day with the same score, that point needs to be bigger.</li>
<li>If two quiz scores overlap there needs to be some jitter so we can see all points.</li>
<li>Each quiz needs to have its own color</li>
</ol>
<p>Here i... | <p>It doesn't work because when you are using <code>hue</code>, seaborn does two separate scatterplots and therefore the size argument you are passing using <code>scatter_kws=</code> no longer aligns with the content of the dataframe.</p>
<p>You can recreate the same effect by hand however:</p>
<pre><code>x_col = 'Da... | python|plot|seaborn | 2 |
9,834 | 60,181,745 | Packaging python project with multiple directories | <p>I need some explanation on working with <code>setuptools</code> and <code>find_packages</code> function.
I have a project structure like this:</p>
<pre><code>├── project_dir_1
│ ├── module.py
│ ├── __init__.py
├── my_project
│ ├── cli.py
│ ├── subdir1
│ │ ├── __init__.py
│ │ ├── module.py
│ ├── co... | <p><code>find_packages</code> will resolve paths relative to current working directory, so calling it outside of the project root dir will effectively install nothing (check whether you see any sources installed by e.g. running</p>
<pre><code>$ pip show -f my_project
</code></pre>
<p>, I bet nothing will be listed). ... | python|setuptools|packaging|setup.py|project-structure | 1 |
9,835 | 60,017,995 | Python recursive function doesn't return random choice | <p>I am trying to get random work in python using <code>random</code> module. My function is as below:</p>
<pre><code>import random
word_file = "/usr/share/dict/words"
WORDS = open(word_file).read().splitlines()
def get_random_word(max_length=None):
word = random.choice(WORDS)
print(word)
if not max_le... | <p>You didn't assign the return value in your function.</p>
<pre><code> get_random_word(max_length)
return word
</code></pre>
<p>should be:</p>
<pre><code> if len(word) > max_length:
word = get_random_word(max_length)
return word
</code></pre> | python|recursion|random | 0 |
9,836 | 2,639,915 | Why the "mutable default argument fix" syntax is so ugly, asks python newbie | <p><sup>Now following <a href="https://stackoverflow.com/questions/2634091/python-some-newbie-questions-on-sys-stderr-and-using-function-as-argument/2635912#2635912">my series of "python newbie questions"</a> and based on <a href="https://stackoverflow.com/questions/575196/python-variable-scope-and-function-calls/57533... | <p>This is called the 'mutable defaults trap'. See: <a href="http://www.ferg.org/projects/python_gotchas.html#contents_item_6" rel="noreferrer">http://www.ferg.org/projects/python_gotchas.html#contents_item_6</a></p>
<p>Basically, <code>a_list</code> is initialized when the program is first interpreted, not each time ... | python|mutable|names | 11 |
9,837 | 5,953,988 | How to call a method from an inherit class | <p>I'm working on a project wich consist on testing a board connection with a JTAG connector and OpenOCD server.</p>
<p>Here is the connection class I've coded, it's simply using pexpect :</p>
<pre><code>"""
Communication with embedded board
"""
import sys
import time
import threading
import Queue
import pexpect
im... | <p>The problem was the syntax of my class definition :</p>
<pre><code>class ModTelnet:
</code></pre>
<p>And not :</p>
<pre><code>class ModTelnet():
</code></pre>
<p>wich is a useless because I don't inherit from an other class ... :D </p>
<p>Thanks anyway !</p> | python|serial-port|jtag | 0 |
9,838 | 6,024,212 | What's the preferred method in the community for having python 2.x and 3.x in the same codebase? | <p>I am starting a project in Python 3.x, (I'm quite new to Python) and there exists the possibility that I will need to use say Thrift or any other library that is not yet ported to Python 3.x.</p>
<p>I don't mind about devoting some (substantial) amount of time to convert an external library to Python 3.x if with th... | <p>I suggest supporting Python 2.x and Python 3.x simultaneously from the same code base, using <a href="http://codespeak.net/tox/" rel="nofollow">tox</a>. Check out the <a href="http://blip.tv/file/4879179" rel="nofollow">Supporting All Versions of Python All The Time With Tox </a> talk from Pycon 2011.</p> | python|python-2.7|python-3.x | 2 |
9,839 | 30,290,293 | Using threading.timer to delay sub-procedure | <pre><code>def emailCheck(self):
n=0
(retcode, messages) = mail.search(None, '(UNSEEN)')
if retcode == 'OK':
for num in messages[0].split() :
n=n+1
typ, data = mail.fetch(num,'(RFC822)')
for response_part in data:
if isinstance(response_part, tuple):
original = e... | <p>t = threading.Timer(10.0, self.emailCheck)</p> | python-3.x|pyqt4|self | 0 |
9,840 | 64,051,795 | Plotly-Dash: Dropdown options work but won't plot data | <p>I am new to Dash. I am trying to plot a simple line plot and add a dropdown to change the data which comes from a dataframe (which is nested in a dictionary with other dataframes). Here is the dataframe:</p>
<pre><code>df_vals['corn']
time 2m_temp_prod 2m_temp_area total_precip_prod total_precip_area
0 ... | <p>You definitely seem to be close to a solution here. Iactually think that you've only forgotten to <code>import plotly.express as px</code>. I took the time to make a proper data sample out of the data you provided in the question. And without any information of your imports I just had to go for my standard plotly an... | python|plotly|plotly-dash|plotly-python | 2 |
9,841 | 43,015,460 | Issue reading .txt files (from dropbox) in JavaScript for Raspberry Pi Weather station | <p>How exactly would I go by reading .txt files in JavaScript from a dropbox file? I recently got a weather sensor for my raspberry pi, and I want to save the current weather data every hour to a .txt file in dropbox (code seen below). However, I am a bit stuck on linking the data from a dropbox file to my web page so ... | <blockquote>
<p>linking the data from a dropbox file to my web page</p>
</blockquote>
<p>As far as i know you cannot simply load a local file into your browser javascript. What you can do is setup a simple webserver like pythons <a href="https://docs.python.org/2/library/simplehttpserver.html" rel="nofollow noreferr... | javascript|python|dropbox | 0 |
9,842 | 66,483,115 | Field 'id' expected a number but got 'bidding' | <p>I'm building a html page from a model. Added to the page is a a form that somehow seems to interfere with the model I'm using to build the page.</p>
<p>I get this error message:
Exception Type: ValueError at /bidding
Exception Value: Field 'id' expected a number but got 'bidding'.</p>
<p>HTML (listing.html)</p>
<pre... | <p>You should swap the patterns, such that if you access <code>bidding/</code>, then it first will look at the path for the <code>bidding</code> view, and only if the path does not match look further, so:</p>
<pre><code>urlpatterns = [
# ↓ first bidding
path(<b>'bidding/'</b>, views.bidding, nam... | python|html|django|forms | 3 |
9,843 | 50,844,366 | How can I calculate pct_change() in pandas across two columns, row by row? | <p>I have this: </p>
<pre><code>df['new'] = df[['col1', 'col2']].pct_change(axis=1)
</code></pre>
<p>I want the percent change across rows in col1 and col2. However I am getting the error: </p>
<pre><code>ValueError: Wrong number of items passed 2, placement implies 1
</code></pre>
<p>What am I doing wrong? </p> | <p>The percent change function is returning a pandas DataFrame object with two columns! This is why you see the ValueError where 1 item is expected instead of two.</p>
<pre><code>import numpy as np
x = np.range(1,11)
y = x*3
df = pd.DataFrame()
df['col1'] = x
df['col2'] = y
df
col1 col2
0 1 3
1 2 6... | python|pandas | 9 |
9,844 | 50,947,780 | ArrayType of mixed data in spark | <p>I want to merge two different array list into one. Each of the array is a column in spark dataframe. Therefore, I want to use a udf </p>
<pre><code>def some_function(u,v):
li = list()
for x,y in zip(u,v):
li.append(x.extend(y))
return li
udf_object = udf(some_function,ArrayType(ArrayType(StringType()))... | <p>If you have <code>dataframe</code> and <code>schema</code> as </p>
<pre><code>+------------------------------------------------+----------------------------------------+
|features |name |
+------------------------------------------------+----... | python|apache-spark|pyspark|user-defined-functions | 0 |
9,845 | 3,241,754 | Only allow 1 instance of a python script | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/380870/python-single-instance-of-program">Python: single instance of program</a> </p>
</blockquote>
<p>What is the best way to insure that only 1 copy of a python script is running? I am having trouble with p... | <p>Try:</p>
<pre><code>import os
os.open("lock", os.O_CREAT|os.O_EXCL)
</code></pre>
<p>The documentation for <a href="http://docs.python.org/library/os.html#os.open" rel="nofollow noreferrer">os.open</a> and <a href="http://docs.python.org/library/os.html#open-constants" rel="nofollow noreferrer">its flags</a>.</p> | python | 3 |
9,846 | 50,257,387 | Trained Tensorflow give different result at same input value but not same structure | <p>I'm trying to run the trained Tensorflow model. But Trained Model give me different result at same input.</p>
<p>I tried several test about the model</p>
<ol>
<li>save test input data and run trained model with them in training .py file</li>
<li>restore trained model(different .py file) and run with saved test inp... | <p>I found what was the problem...</p>
<p>the problem was layer normalization.</p>
<p>I used the code below to training</p>
<pre><code># Layer 1
HL1 = tf.add(tf.matmul(X, w1), b1)
# Layer Normalize
mean1, var1 = tf.nn.moments(HL1,[0])
HL1_hat = (HL1 - mean1) / tf.sqrt(var1 + epsilon)
scale1 = tf.Variable(tf.ones([n_... | python|tensorflow | 1 |
9,847 | 50,289,743 | Print individual split strings | <p>The following code takes a string such as abcd#1234, removes the '#' and splits it into abcd and 1234</p>
<pre><code>import sys
import re
print("User ID: {0}").format(sys.argv[1])
print("User Type: {0}").format(sys.argv[2])
sub = re.sub('[#]', '', sys.argv[1])
split = re.match(r"([a-z]+)([0-9]+)", sub, re.I)
prin... | <pre><code>split.group(1) # --> 'abcd'
split.group(2) # --> '1234'
</code></pre>
<p><a href="https://docs.python.org/3/library/re.html#re.match.group" rel="nofollow noreferrer">https://docs.python.org/3/library/re.html#re.match.group</a></p> | python|string|split | 1 |
9,848 | 50,645,113 | Scrollable Dynamic Gridlayout in Kivy | <p>What I have:<br>
- A dynamic TextWrapper(GridLayout) that includes Images and Labels made from the "description" text out of the SpeciesView.data<br>
- A RecycleView that lets me click through the different texts</p>
<p>The problem is though, that I can't seem to find a way to scroll through the GridLayout (TextWra... | <h1>SpeciesText - Using RstDoc</h1>
<p>The following example illustrates <a href="https://kivy.org/docs/api-kivy.uix.rst.html" rel="nofollow noreferrer">Kivy RstDcoument</a>. It supports long text, <a href="http://docutils.sourceforge.net/docs/ref/rst/directives.html#image" rel="nofollow noreferrer">images</a>, and th... | python-3.x|kivy | 2 |
9,849 | 35,087,360 | How to make googlemaps python library detect SSL certificates? | <p><strong>The problem</strong></p>
<p>Make to work:</p>
<pre><code>import googlemaps
gmaps = googlemaps.Client(key='AIza...')
# Geocoding an address
geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA')
</code></pre>
<p><strong>Tried so far ...</strong></p>
<p>I fixed all reque... | <p>Thanks to Liam Horne for his answer here: <a href="https://stackoverflow.com/a/34665344/552621">https://stackoverflow.com/a/34665344/552621</a></p>
<blockquote>
<p>I found a solution. There seems to be a major issue in the version of
<code>certifi</code> that was running. I found this out from this (very long)
... | python|google-maps|ssl|google-maps-api-3|python-requests | 2 |
9,850 | 35,111,478 | python expected an indented block | <p>i don't know why that appears when i try to run. i tried to fix but i can't. is there any errors?</p>
<pre><code>import math
print(" Hello....\n This program will ask you to enter 3 numbers \n (a, b and c) that will be used in the quadratic formula to \n calculate the roots of an equation ")
a=float(input("Enter ... | <p>First: In Python, indenting is a must. It is a syntactically feature to have nested code indented instead of spamming the source with paranthesis'.</p>
<p>Second: Obviously, you copy pasted HTML code from somewhere. Get rid of <code><br /></code>.</p> | python | 0 |
9,851 | 64,830,622 | PValueError while am comparing string is in a pandas dataframe | <p>I Get ValueError:</p>
<p>The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</p>
<p>def translate_complaints(my_dataframe):</p>
<pre><code>for index, row in my_dataframe.iterrows():
desc = my_dataframe.loc[index, 'description']
if desc != '':
resp = translat... | <p>For some reason, within your translate function, the Text=desc is getting a series and not a value. The index AND description columns are being passed and it only wants the description.</p>
<p>maybe try .at instead of .loc</p>
<pre><code>desc = my_dataframe.at[index, 'description']
</code></pre>
<p>Also, you may wan... | pandas|amazon-web-services|boto3 | 0 |
9,852 | 61,336,726 | Tracking and bluring faces in multiple 360 images via python opencv | <p>Is there a way to track down and nicely blur faces or part of face (like hair) for multiple 360 degree images via python opencv. ? I'am using Windows OS and python3.8</p> | <p>Two methods with opencv and python</p>
<ol>
<li>Using a Gaussian blur to anonymize faces in images and video streams</li>
<li>Applying a “pixelated blur” effect to anonymize faces in images and video</li>
</ol>
<p>The method is well explained <a href="https://www.pyimagesearch.com/2020/04/06/blur-and-anonymize-fac... | python|opencv | 1 |
9,853 | 61,420,329 | I received the following error: TypeError: unsupported operand type(s) for +: 'float' and 'str' | <p>I received the following error: TypeError: unsupported operand type(s) for +: 'float' and 'str'</p>
<p>I copied the code exactly as written from the book: "Python Programming: An Introduction to Computer Science", page 44-45. (see below). Where did I go wrong?</p>
<pre><code># investment calculator
def main():
... | <p>You need to convert some of these values into integers, as input is taken as a string. To change this, you can wrap the inputs in the <code>int()</code> function like this:</p>
<pre><code>principal = int(input("Enter the initial principal: "))
apr = int(input("Enter the Annual Interest rate: "))
</code></pre>
<p>I... | python | 0 |
9,854 | 61,596,161 | python3: read two text files and print each file in vertical split so easy to log for comparing | <p>I am thinking is it possible to achieve the below in python3</p>
<p>I have two text files </p>
<p>File 1 </p>
<pre><code>===========================================================================
0100 - Request Message RSC Transaction ID :N80L2G
===============================================================... | <p>It's possible</p>
<pre><code>separator = " "
file1 = open("f1")
file2 = open("f2")
con1 = file1.readlines()
con2 = file2.readlines()
file1.close()
file2.close()
max_length = max(len(con1), len(con2))
for i in range(max_length):
print(con1[i].rstrip() + separator + con2[i].rstrip() + "\n")
</code></pre> | python-3.x | 1 |
9,855 | 57,846,441 | count words of text file in python3 | <p>I am learning python and I want to create a program which counts total number of words from textfile.</p>
<pre class="lang-py prettyprint-override"><code>fname = input("Enter file name: ")
with open(fname,'r') as hand:
for line in hand:
lin = line.rstrip()
wds = line.split()
print(w... | <p>You need to initialize <code>wordCount = 0</code> and then inside the <code>for loop</code> you need to add to wordCount every time you iterate. Something like this:</p>
<pre><code>wordCount = 0
for line in hand:
lin = line.rstrip()
wds = lin.split()
print(wds)
wordCount += len(wds)
print(wordCount)... | python | 1 |
9,856 | 56,382,682 | Change list to set without changing order of elements | <p>I want to remove those element from list which has repetition more than one it's like set but order should not be change </p>
<pre><code>[4,6,2,6,1,2] should become [4,6,2,1]
</code></pre>
<p>I'am looking for any inbuilt method or list comprehension</p> | <p>This should do it: use <code>lambda</code> function and remove duplicates using <code>set</code>. Tested on Python 2.7</p>
<pre><code>mylist = [4,6,2,6,1,2]
reduce(lambda r, v: v in r[1] and r or (r[0].append(v) or r[1].add(v)) or r, mylist, ([], set()))[0]
</code></pre> | python|list | 0 |
9,857 | 18,704,340 | webhost webfaction: site navigation | <p>I'm new to webfaction and I want to run a cherrypy app I've developed. It runs fine on my localhost and I'm trying to put it on a website so it seems like all I need to do is copy and paste the code to the site.py file that was created when I created a cherrypy app at webfaction.</p>
<p>This is a really beginner qu... | <p>You need to use SSH or FTP, then from go to <code>webapps/NAME_OF_YOUR_APP/</code></p>
<p>This is the documentation on <a href="http://docs.webfaction.com/user-guide/access.html" rel="nofollow">how to access your data on webfaction</a>.</p> | python|cherrypy|webfaction | 1 |
9,858 | 18,613,447 | How much ram can python use? | <p>If I use python (32 bit version) on a machine with for example 64Gb ram , will it be able to use these 64Gb of ram. Or does this depend on the Operating System ?</p> | <p>Python does not itself use any mechanisms for extending past the per-process userspace memory limit of the operating system. There are however modules for and means of doing so. So the answer is "depends on how much work you're willing to do".</p> | python | 8 |
9,859 | 69,308,566 | Using case when statements in Python | <p>Hi so I come from more of a a sql background, and I'm having hard time using what ever would be the equivalent of a case when statement. I have a column site visits which has range of 0-1000. I want to break it down into 0-299 = small, 300-599 = medium, 600-1000 = large. Here is what I have</p>
<pre><code>df['compan... | <p>Define a function to make it readable if there are many cases.</p>
<pre><code>def size_name(size):
if size < 300:
return 'Small'
if size < 600:
return 'Medium'
return 'Large'
df['company_size'] = df['site_visits'].apply(size_name)
</code></pre> | python|pandas|dataframe | 0 |
9,860 | 69,381,429 | Multi-label classification return more than 1 class in each label | <p>How to train a Multi-label classification model when each label should return more than 1 class?
Example:
Image classification have 2 label: style with 4 classes and layout with 5 classes.
An image in list should return 2 style and 3 layout like [1 0 1 0] [1 1 0 0 1]</p>
<p>My sample net:</p>
<pre><code>class MyMode... | <p>I am not sure what you referring label to but it seems you have a multi output model predicting on one hand <em>style</em>, and on the other <em>layout</em>. So I am assuming you are dealing with a multi-task network with two "independent" outputs which are supervised separately with two-loss terms.</p>
<p... | deep-learning|pytorch|image-classification | 1 |
9,861 | 54,120,928 | Convert python date format (%Y) to java (yyyy) | <p>I have a bunch of time formats in the following format:</p>
<pre><code>"%Y-%m-%d %H:%M:%S"
</code></pre>
<p>Is there a quick way or a library to convert these to:</p>
<pre><code>YYYY-MM-DD HH:MM:SS
</code></pre>
<p>My current method to do so is using a string replace, but perhaps I'll be missing some edge cases.... | <p>One way would be to use the <code>%</code> format as a template and then provide a mapping, e.g.:</p>
<pre><code>In []:
from string import Template
mapping = {'Y': 'yyyy', 'm': 'MM', 'd': 'dd', 'H': 'HH', 'M': 'mm', 'S': 'ss'}
Template("%Y-%m-%d %H:%M:%S".replace('%', '$')).substitute(**mapping)
Out[]:
'yyyy-MM-dd... | python | 14 |
9,862 | 45,622,266 | Tkinter Focus lost after askstring | <p>I am currently implementing a program that uses many tkinter frames and while subframe is being opened I want the superframe to be locked for the user (otherwise things will not work out). After some research I found the grab_set and grab_release method which worked quite fine.</p>
<p>However once the subframe (ins... | <p>According to the notes in the tkinter library:</p>
<blockquote>
<p>A grab directs all events to this and descendant widgets in the application.</p>
</blockquote>
<p>I am not able so far to find any documentation that would explain why the <code>grab_set()</code> is falling off after you finish submitting your <c... | python|tkinter|focus | 1 |
9,863 | 45,308,552 | Python returning key value pair from JSON object | <p>I'm trying to return the 'publisher' and 'title' values of the first entry in this JSON object.</p>
<pre><code>{
"count": 30,
"recipes": [{
"publisher": "Closet Cooking",
"f2f_url": "htt//food2forkcom/view/35171",
"title": "Buffalo Chicken Grilled Cheese Sandwich",
"source_ur... | <p><code>recipe['recipes']</code> is a list of objects, thus you can iterate over it:</p>
<p>To return the 'publisher' and 'title' values of the first entry in this JSON object you can use list comprehension and get the first element of the resulting collection:</p>
<pre><code>recipes = [{element['publisher']: elemen... | python|json|python-requests | 0 |
9,864 | 56,880,993 | Python - Not repeating code with if statements, is there another way? | <p>Looking to improve my python and coding skills. I have a function that adds a particular timeframe to a time.
I pass in:</p>
<p><code>1M, 7D, 6M, 2H, M</code> etc .. and return the value. I feel like I am repeating myself. Is there a more pythonic approach to this?</p>
<pre class="lang-py prettyprint-override"><c... | <p>I usually avoid lots of ifs by using dictionaries. I map each condition to a dictionary and execute. Here is my first take:</p>
<p>I created a function for adding months as timedelta does not have it. I then use <code>re</code> to get digit and letter as tuples. So '4M' would be ('4','M'). Then I would map M to mo... | python|refactoring | 1 |
9,865 | 57,036,505 | How to create a custom function inside django model? | <p>I have a django model</p>
<pre><code>class UserInfluencerGroupList(models.Model):
list_name = models.CharField(max_length=255)
influencers = models.ManyToManyField(Influencer, blank=True)
user = models.ForeignKey(MyUser, on_delete = models.CASCADE)
def __str__(self):
return self.list_name
<... | <p>You should consider to use <a href="https://www.django-rest-framework.org/" rel="nofollow noreferrer">Django Rest Framework</a> if you want to return a json of your own choice or/and if you're about to create your own rest api.</p>
<p>Alternative is to create the json all manually, i.e build the dictionary and then... | python|django|python-3.x|django-models|django-views | 1 |
9,866 | 25,825,946 | Generating smooth line graph using matplotlib | <p>Following is the python script to generate a plot using matplotlib. </p>
<pre><code>#!/usr/bin/python
import matplotlib.pyplot as plt
import time
import numpy as np
from scipy.interpolate import spline
# Local variables
x = []
y = []
# Open the data file for reading lines
datafile = open('testdata1.txt', 'r')
se... | <p>I got this working! Thanks for the comments. Here is the updated code.</p>
<pre><code>#!/usr/bin/python
import matplotlib.pyplot as plt
import time
import numpy as np
from scipy.interpolate import spline
# Local variables
x = []
y = []
# Open the data file for reading lines
datafile = open('testdata1.txt', 'r')
... | python|matplotlib|smoothing | 39 |
9,867 | 24,065,575 | Byte formatting in python 3 | <p>I know this question has been asked before, but couldn't get it working for me though.
What I want to do is sent a prefix with my message like so:</p>
<pre><code>msg = pickle.dumps(message)
prefix = b'{:0>5d}'.format(len(msg))
message = prefix + msg
</code></pre>
<p>This gives me</p>
<pre><code>AttributeError:... | <p>You can't <code>format</code> a <a href="https://docs.python.org/3/library/stdtypes.html#bytes-and-bytearray-operations" rel="nofollow noreferrer"><code>bytes</code> literal</a>. You also can't concatenate <code>bytes</code> objects with <code>str</code> objects. Instead, put the whole thing together as a <code>str<... | python|formatting | 5 |
9,868 | 24,212,724 | Running Python from PHP on one.com | <p>I am trying to run a python script on one.com after a user completes an action on my website. If I run it using a shell file (every couple of minutes) when I run it in the background and end the ssh session it ends the script. I have tried running if from php using <code>shell_exec</code> and <code>system</code> but... | <p>I know this post i old but for future reference, as I assume you have moved on... I can inform that after I read your question I contacted One.com (12 jan 2016) and they said that they do not support Python and are not planning to do so in the near future.</p> | php|python | 5 |
9,869 | 72,080,839 | "COPY failed: " While Building a Python Docker Image | <p>I'm trying to create a Docker image using the following Dockerfile.</p>
<pre><code># syntax=docker/dockerfile:1
FROM python:latest
WORKDIR /project4
COPY pythonCode1.py /project4/pythonCode1.py
COPY requirements.txt /project4/requirements.txt
RUN pip3 install -r requirements.txt
CMD ["python3 ", "pyth... | <p>The problem is that by using</p>
<pre class="lang-sh prettyprint-override"><code>docker build - < Dockerfile
</code></pre>
<p>the Build Context does not include the whole dicrectory therefore the file <code>pythonCode1.py</code> is unknown to the Docker Engine.</p>
<p>Use the following docker build command instea... | python|docker|dockerfile|docker-build | 2 |
9,870 | 35,842,873 | Is there a way to download a video from a webpage with python? | <p>I would like to pull the video from this website.
<a href="http://www.jpopsuki.tv/video/Meisa-Kuroki---Bad-Girl/eec457785fba1b9bb35481f438cf35a7" rel="noreferrer">http://www.jpopsuki.tv/video/Meisa-Kuroki---Bad-Girl/eec457785fba1b9bb35481f438cf35a7</a></p>
<p>I can access it with python and get the whole html. But ... | <p>Found the function below <a href="https://stackoverflow.com/questions/16694907/how-to-download-large-file-in-python-with-requests-py">here</a></p>
<p>I think this'll do it:</p>
<pre><code>import requests
def download_file(url):
local_filename = url.split('/')[-1]
# NOTE the stream=True parameter
r = r... | python|video | 13 |
9,871 | 46,209,272 | Recursive Py Program Returning j=none when j==1? | <p>Recursive Py Program Returning j=None when j==1? This does not make sense as base case specified j must equal 1 and does not call function again. </p>
<pre><code>import sys
y=10
def decrease(j):
if j==1:
print('j =' + str(j) + '(1)')
print('returning j')
return j
else:
prin... | <p>You forget to <code>return decrease(j)</code> at the end of the second branch.</p>
<p>Usually when you encounter unexpected <code>None</code> returned from function, check first that all the branches end with a <code>return</code> statement. Without it, the function returns <code>None</code></p> | python|recursion | 1 |
9,872 | 61,099,269 | flask is not picking parameters supplied for post request | <p>I created a resource containing post method which takes user_name, client_dict, order_detail_dict as arguments/parameters as below</p>
<pre class="lang-css prettyprint-override"><code>class CreateOrder(Resource):
def post(self, user_name, client_dict, order_detail_dict):
</code></pre>
<p>and I registered resou... | <p>For every argument that you supply in your <code>post</code> definition, you must also pass in a value for it like so:</p>
<pre class="lang-py prettyprint-override"><code>def post(self, user_name, client_dict, order_detail_dict):
pass
</code></pre>
<p>You need a url with all these parameters:</p>
<p><code>/cr... | python|flask | 2 |
9,873 | 49,433,427 | Extracting weights from an LSTM neural network using Keras | <p>I have trained a recurrent neural network (LSTM) in keras but now I am struggling to put all the pieces together. Specifically, I cannot understand how to recompose the matrices of weights.</p>
<p>I have one input, one hidden and one output layer, as follows:</p>
<pre class="lang-python prettyprint-override"><co... | <p>Sequential is a model in Keras, not an input layer.
An input layer in a neural network is simply passing the inputs to the hidden layer and it does not need a bias neuron .
In your case, the model.get_weights() returns these arrays<br><br><br>
(15, 400) <br>
(100, 400) <br>
(400,)<br>
(100, 5)<br>
(5,)<br><br><br>
... | tensorflow|keras|lstm|recurrent-neural-network | 0 |
9,874 | 49,374,080 | pandas to_csv alters data by adding \n line break or Storing numpy arrays in dataframe cell | <p>I am generating a pandas dataframe with some data (some are numpy arrays) and saving the data with the pandas.to_csv function. </p>
<p>However, when reading the csv file to a dataframe again with pandas.read_csv I notice that pandas added line breaks within the numpy array like so (see last output) </p>
<pre><code... | <p>This is how we resolved the issue. </p>
<pre><code>array_list = np.array([])
for i in array:
data_tmp = np.fromstring(i[1:-1],dtype=np.float,sep=' ')
array_list = np.concatenate([array_list, data_tmp])
array_list = array_list.reshape((1,-1))
print(array_list)
</code></pre>
<p>[OUT] </p>
<p>[[0. 0. 0. 0. ... | python|pandas|csv|dataframe | 1 |
9,875 | 21,026,726 | Convert a string of numbers to a list of integers. Python | <p>I am trying to convert the string str1 to a list of numbers so that I could sum them up. First I use the split() function to make sense of the numbers in str1, I cast the string into a list (lista) and after that I use the map() function in order to convert the strings in the new list to integers:</p>
<pre><code> ... | <p>Using <code>split()</code> will not split up <code>str1</code>, as without the <code>sep</code> argument the default separator is a space <code>' '</code>. Hence:</p>
<pre><code>str2 == ["13,22,32,4,5"]
</code></pre>
<p>you need to specify that <code>split</code> should use a comma <code>','</code>. In fact, you c... | string|list|python-2.7 | 2 |
9,876 | 62,642,210 | How do I keep my values the same each time I go around the while loop? | <p>I am making a two-person dice game where there are five rounds, but I want to keep the scores the same from the previous rounds, how do I do that?</p>
<p>The rules of the game are as follows:</p>
<p>• The points rolled on each player’s dice are added to their score.
• If the total is an even number, an additional 10... | <pre><code>def writeUp(score_1,score_2,nameoffile):
with open(f"{nameoffile}.txt","a") as logz:
print(f"score1 {score_1}\nscore2 {score_2}",file=logz)
def readUp(nameoffile):
with open(f"{nameoffile}.txt","r") as data:
lines = data.readlines()... | python|loops|while-loop|project | 1 |
9,877 | 53,650,727 | ID card and wrapping it identification | <p>I have the following ID, and I want to detect it, and warp it.
Main problems</p>
<ol>
<li><p>That method doesn't work with all kind of images dataset, I can't find the best contour, please suggest better ways for preprocessing it? </p></li>
<li><p>I get two contours, one for the background and one for the ID, I wa... | <p>You can use Hough-transform to detect the rectangle of the i.d.
You first need to use some edge detection operator (I see you are already using Canny). Then run the Hough transform for lines on the edges image. Then just draw the top lines the transform has found. Ones you got the lines surrounding the i.d, it is ea... | python|opencv|image-processing|computer-vision | 3 |
9,878 | 54,924,655 | Unable to find output file in ubuntu generated by python | <p>I am currently working on python 3.6 using spider. I have written a code which in theory works in windows but it does not on ubuntu 18.04. My problem is that I want to write my results on a text file but it is nowhere to be found. </p>
<p>I write the following: </p>
<pre><code>with open('Vx1.txt', 'w+') as fv1:
... | <p>Could it be indentation issues?</p>
<pre><code>with open('Vx1.txt', 'w+') as fv1:
for itemv1 in var:
fv1.write("%s\n" % itemv1)
</code></pre> | python|linux|ubuntu|spyder | 0 |
9,879 | 33,074,978 | Apply a value to all instances of a number based on conditions | <p>I have a df like this:</p>
<pre><code> ID Number
1 0
1 0
1 1
2 0
2 0
3 1
3 1
3 0
</code></pre>
<p>I want to apply a 5 to any ids that have a 1 anywhere in the number column and a zero to those that don't. For example, if the number ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#transformation" rel="nofollow"><code>transform</code></a> to add a column to your df as a result of a <code>groupby</code> on 'ID':</p>
<pre><code>In [6]:
df['Total'] = df.groupby('ID').transform(lambda x: 5 if (x == 1).any() else 0)
df
Out[6]:
... | python|python-3.x|pandas | 2 |
9,880 | 73,623,019 | How to mock connection for airflow's Livy Operator using unittest.mock | <pre><code>@mock.patch.dict(
"os.environ",
AIRFLOW_CONN_LIVY_HOOK = "http://www.google.com",
clear= True
)
class TestLivyOperator(unittest.TestCase):
def setUp(self):
super().setUp()
self.dag = DAG(
dag_id = "test_livy",
default_a... | <p>As per the Airflow doc
<a href="https://airflow.apache.org/docs/apache-airflow/stable/howto/connection.html#storing-connections-in-environment-variables" rel="nofollow noreferrer">https://airflow.apache.org/docs/apache-airflow/stable/howto/connection.html#storing-connections-in-environment-variables</a>
The naming c... | airflow|livy|python-unittest.mock | 0 |
9,881 | 40,034,246 | How to replace a dot with a string in a python list | <pre><code>my_list = ['b','.','.']
expected_list = ['b','.','w']
</code></pre>
<p>May be simple, moving into python recently so any suggestions would be fine</p> | <blockquote>
<p>You can do this by using list comprehension also</p>
</blockquote>
<pre><code>l = ['w' if i == '.' else i for i in my_list]
</code></pre> | python|python-2.7 | 1 |
9,882 | 8,751,900 | Python CGI not executing on Mac OSX 10.6.7 | <p>Recently I started reading Mark Lutz's "Programming Python - Fourth Edition". I am a mac user, using ActivePython and OSX 10.6.7. Anyways, everything was going fine until the first instance of CGI in the book. The code example creates a form, and uses a POST method for finding someone's name:</p>
<pre><code><htm... | <p>You need to configure and run a webserver, then access the file through that webserver with a url like <a href="http://localhost:8080/cgi/foo.py" rel="nofollow">http://localhost:8080/cgi/foo.py</a>, and not the local path to the file.</p> | python|macos|cgi | 2 |
9,883 | 8,704,919 | Checking if a value is in a list based on indexes | <p>If I have a list that is made up of indexes from a list of lists, how would I use an index collected from a value in that list and find out which list it is in? </p>
<p>Here is an example:</p>
<pre><code>listolists = [
[0, 8, 4, 0, 7],
[3, 6, 0, 9, 0],
[4, 0, 3, 7, 0],
[7, 0, 7, 0, 6]
]
section... | <p>I have fixed up some typoes, avoided the scroll bar, shown the contents of <code>section</code> and <code>section2</code>, and added a print statement:</p>
<pre><code>table = [
[0, 8, 4, 0, 7],
[3, 6, 0, 9, 0],
[4, 0, 3, 7, 0],
[7, 0, 7, 0, 6]
]
section1 = [table[0][0], table[0][1], table[1][0],... | python | 0 |
9,884 | 58,928,184 | How to use TCP transport in pysnmp-4.4.6 version | <p>I am using PySNMP 4.4.6 and I want to change carrier to TCP.</p>
<p>That means I want to poll SNMP data using TCP protocol.</p>
<p>I'm getting the following error when I switch carrier to TCP:</p>
<pre><code>File "send-trap-over-ipv4-and-ipv6.py", line 76, in <module>
transportDispatcher.runDispatch... | <p>Unfortunately, pysnmp 4.x does not presently offer TCP transport support. There is an ongoing work on that matter, though. Odds are to have streaming transport support in <a href="https://github.com/etingof/pysnmp/projects/1" rel="nofollow noreferrer">pysnmp 5.x</a>.</p> | python|tcp|snmp|pysnmp | 0 |
9,885 | 52,084,719 | Index error list page out of range on danbooru twitter bot | <p>i am using a code that i found in github, i had to modify somethings, it works, but sometimes (even when working) it gives Index error page out of range and then stop working. </p>
<blockquote>
<p>File "bot.py", line 36, in module<br>
imageSource = pageTable[arrayNum]["file_url"]<br>
IndexError: list inde... | <p>It seems the response you get maybe empty sometimes. I've tried (which can be a possibility within your random range)</p>
<p><a href="https://danbooru.donmai.us/posts.json?tags=shimakaze_(kantai_collection)%20rating:s&limit=1000&page=796" rel="nofollow noreferrer">https://danbooru.donmai.us/posts.json?tags=... | python | 0 |
9,886 | 36,497,008 | Merge dicts from a list of dicts based on some key/value pair | <p>I have a list of dicts shown below , I want to merge some dicts into one based some key/value pair.</p>
<pre><code> [
{'key': 16, 'value': 3, 'user': 3, 'id': 7},
{'key': 17, 'value': 4, 'user': 3, 'id': 7},
{'key': 17, 'value': 5, 'user': 578, 'id': 7},
{'key': 52, 'value': 1, 'user': 3, 'id': 4... | <p>Let <code>dicts</code> be your original list of dictionaries. This idea maps unique combinations of user and id to <code>defaultdict(list)</code> objects. The final result will be the list of values from that dictionary.</p>
<pre><code>from collections import defaultdict
tmp = defaultdict(dict)
for info in dicts:
... | python|dictionary | 2 |
9,887 | 19,341,481 | Flask Server running wrong program | <p>I am learning Flask. </p>
<p>I was able to run the Hello World tutorial as shown here </p>
<p>Then I tried to build the Flaskr program following the tutorial <a href="http://flask.pocoo.org/docs/tutorial/introduction/" rel="nofollow">http://flask.pocoo.org/docs/tutorial/introduction/</a></p>
<p>I ran into an iss... | <p>If you're testing or working on multiple projects at the same time, please run each one in a dedicated virtual environment and serve at a different port because by default flask serves at 127.0.0.1:5000.</p>
<p>Use something like this below:</p>
<pre><code>if __name__ == "__main__":
app.run(host='0.0.0.0',port=800... | python|flask | 0 |
9,888 | 19,580,844 | Accessing Running Python program from another Python program | <p>I have the following program running</p>
<pre><code>collector.py
data=0
while True:
#collects data
data=data+1
</code></pre>
<p>I have another program cool.py which wants to access the current data value. How can I do this?</p>
<p>Ultimately, something like:</p>
<p>cool.py</p>
<pre><code>getData()
</... | <p>You can use memory mapping.
<a href="http://docs.python.org/2/library/mmap.html" rel="nofollow">http://docs.python.org/2/library/mmap.html</a></p>
<p>For example you open a file in tmp directore, next u mapping this file to memory in both program and write u data to this file.</p> | python | 0 |
9,889 | 13,227,970 | How to effectively remove a line in the middle of a large file? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/2329417/fastest-way-to-delete-a-line-from-large-file-in-python">Fastest Way to Delete a Line from Large File in Python</a><br>
<a href="https://stackoverflow.com/questions/8868499/how-to-edit-a-line-in-middle-of-... | <p>I don't know if a way to change the file in place, even using low-level file system commands, but you don't need to load it into a list, so you can do this without a large memory footprint:</p>
<pre><code>with open('input_file', 'r') as input_file:
with open('output_file', 'w') as output_file:
for line ... | python|file|python-2.7 | 6 |
9,890 | 22,361,155 | how to get a float from a matrix in python numpy | <p>let's say that I have a matrix in python like this:</p>
<pre><code>>>> xn
matrix([[ 1.99995048],
[ 3.99999329],
[ 2. ]])
</code></pre>
<p>and now I would like to get the element [2][0]
then </p>
<pre><code>>>> z=xn[2][0]
>>> z
matrix([[ 2.]])
</code></pre>
<p>the... | <p>This is one of the many reasons you shouldn't use <code>matrix</code>. (Or at least be very aware of why you're using it if you choose to.) </p>
<p>Using a <code>numpy.matrix</code> forces everything to be 2D.</p>
<p>Also, <code>matrix</code> overloads the <code>**</code> operator to be a matrix power (e.g. <code... | python|numpy|matrix|int|pow | 2 |
9,891 | 16,611,991 | Comparing two tuples from different lists | <p>I have this basic code in which I'm just trying to compare each tuple in the first list (list1) with the corresponding tuple in the second list (list 2). If the tuple in list 2 is = to the corresponding tuple in list1 minus the <code>'.vbproj'</code> then take both tuples and return them.</p>
<p>Then I need to pr... | <p>Use <code>==</code> to test for equality. <code>is</code> tests for <em>identity</em>, the two sides being the <em>same object</em>. Also, your inputs <code>string</code> and <code>string2</code> are not functions, so you cannot call them. Just compare <code>x</code> and <code>y</code> directly:</p>
<pre><code>if x... | python|list|tuples | 1 |
9,892 | 16,698,415 | Reference previous row when iterating through dataframe | <p>Is there a simple way to reference the previous row when iterating through a dataframe?
In the following dataframe I would like column B to change to 1 when <code>A > 1</code> and remain at 1 until <code>A < -1</code>, when it changes to -1.</p>
<pre><code>In [11]: df
Out[11]:
A B
2000-... | <p>This is what you are trying to do?</p>
<pre><code>In [38]: df = DataFrame(randn(10,2),columns=list('AB'))
In [39]: df['B'] = np.nan
In [40]: df.loc[df.A<-1,'B'] = -1
In [41]: df.loc[df.A>1,'B'] = 1
In [42]: df.ffill()
Out[42]:
A B
0 -1.186808 -1
1 -0.095587 -1
2 -1.921372 -1
3 -0.772836 -1
4 ... | python|pandas | 1 |
9,893 | 43,527,597 | Python- How to compare new value with previous value on for-loop? | <p>My function needs to find the character with the highest speed in a dictionary. Character name is the key and value is a tuple of statistics. Speed is index <code>6</code> of the value tuple. How do I compare the previous highest speed to the current value to see if it is higher? Once I get the speed, how can I take... | <p>The <code>sorted</code> function can do this quite easily:</p>
<p><strong>Code:</strong></p>
<pre><code>from operator import itemgetter
def fastest_type(db):
fastest = sorted(db.values(), reverse=True, key=itemgetter(6))[0]
return fastest[1], fastest[2]
</code></pre>
<p>This code sorts by key <code>6</co... | python|python-3.x|dictionary|for-loop|iteration | 1 |
9,894 | 43,632,400 | How to convert list into dictionary in python? | <p>I'm fetching value from database and I want to convert that value into dictionary.To fetch i have done in the following way</p>
<pre><code>[dict((query.description[i][0], value) for i, value in enumerate(row)) for row in query.fetchall()]
</code></pre>
<p>I'm getting output as </p>
<pre><code>[{'defrosting': 32.0... | <p>If you only need one result, any reason not to use <code>query.fetchone()</code>, it avoids getting all the results and discarding all but the first one:</p>
<pre><code>{query.description[i][0]: value for i, value in enumerate(query.fetchone())}
</code></pre> | python | 2 |
9,895 | 43,748,209 | Python function to wrap some exceptions code | <p>I am catching two exceptions in Python in such way:</p>
<pre><code>#ex1
try:
#some code
except:
#some code to e.g. print str
#ex2
try:
#some code
except:
#some code to e.g. print str or exit from the program.
</code></pre>
<p>if ex1 raises an exception then I want to skip ex2.
if ex1 does not r... | <p>EDIT: This will work as you described:</p>
<pre><code>try:
msg = make_msg_fancy(msg)
msg = check_for_spam(msg)
except MessageNotFancyException:
print("couldn't make it fancy :(")
except MessageFullOfSpamException:
print("too much spam :(")
</code></pre>
<p>When an exception occurs, it skips the res... | python|function|exception | 2 |
9,896 | 52,738,170 | Using values of a list stored in DataFrame cell in Pandas | <p>I have a CSV file with each cell value a two element list(pair).</p>
<pre><code> | 0 | 1 | 2 |
----------------------------------------
0 |[87, 1.03] | [30, 4.05] | NaN |
1 |[34, 2.01] | NaN | NaN |
2 |[83, 0.2] | [18, 3.4] | NaN |
</code></pre>
<p>How do I acc... | <p>First of all, beware that storing lists in DataFrames dooms you to Python-speed loops. To take advantage of fast Pandas/NumPy routines, you need to use native NumPy dtypes such as np.float64 (whereas, in contrast, list require "object" dtype).</p>
<p>That being said, here is my code i wrote just to show how to do i... | python|pandas|list|dataframe | 3 |
9,897 | 52,546,940 | AttributeError: type object has no attribute | <p>This is a working multilevel Inheritence program. when I run it it says "AttributeError: type object 'starts' has no attribute 'maths'". I have checked the association of the classes and they inherit. I am a beginner so it will really help me in going forward. </p>
<pre><code>class starts:
def __init__(self, a... | <p>Your <code>operations</code> class inherits the <code>maths</code> class, which inherits the <code>starts</code> class, so all the instance variables initialized by the <code>__init__</code> method of the parent class are available to the child class if you simply call <code>super().__init__()</code>:</p>
<pre><cod... | python-3.x | 0 |
9,898 | 37,345,723 | How to plot the same graph in iGraph two times with two different colorings | <p>I use iGraph in combination with python.<br>
I calculated communities on my graph with two different algorithms. To compare them visually I want to plot the graph with a specific layout, i.e. in my case fruchterman–reingold and color the vertices according to the first community structure.<br>
Then I want to change ... | <p>Set seed for the same value for two plots. The algorithm is random, but after setting seed for the same value, it will output the same result two times. I tried it with R and igraph and it works, so I believe it works also for Python.</p>
<p>It will be something like that:</p>
<pre><code>random.seed(123)
plot1
ran... | python|graph|igraph | 4 |
9,899 | 34,384,400 | Mod function fails in python for large numbers | <p>This python code</p>
<pre><code>for x in range(20, 50):
print(x,math.factorial(x),math.pow(2,x), math.factorial(x) % math.pow(2,x) )
</code></pre>
<p>calculates fine up to x=22 but the mod when x>22 is always 0.</p>
<p>Wolframalpha says the results for x>22 are nonzero.
For example, when <a href="http://www... | <p>You are running into floating point limitations; <code>math.pow()</code> returns a floating point number, so both operands are coerced to floats. For <code>x = 23</code>, <code>math.factorial(x)</code> returns an integer larger than what a float can model:</p>
<pre><code>>>> math.factorial(23)
258520167388... | python-2.7|math | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.