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 |
|---|---|---|---|---|---|---|
900 | 27,180,283 | Using Beautiful Soup to get specific tr meta data | <p>I have a bizarre problem. I am using python to scrape a page using beautiful soup. One value I need is in the tr meta-data which I have been able to print to my screen using the following command:</p>
<pre><code>meta = tr.findNext('td', {'class':'field1'})
attr_dict = meta.a.attrs
print(attr_dict)
</code></pre>
<... | <p>The unexpected order is causing by <code>'\r'</code> character or carriage return. replace it with <code>''</code> or <code>' '</code>and then process your string.</p>
<pre><code>str(attr_dict['title']).replace('\r', '')
</code></pre>
<p>Consider the string:</p>
<pre><code>st = "This is SO\rThat"
</code></pre>
... | python|html|regex|beautifulsoup|metadata | 2 |
901 | 27,236,945 | language detection code in python | <p>So, we have built a language detection program in python that just detects different languages. Our code seems fine; there is no error but I am not getting the desired result. Whenever I run it on Eclipse, it runs and terminates giving us the running time and an "OK". It is supposed to print the language of the text... | <p>Unlike in some other languages, <code>main()</code> is just like any other function in Python. If you want it to run, you have to explicitly call it:</p>
<pre><code>def main():
...
main()
</code></pre> | python|language-detection | 4 |
902 | 12,428,089 | Get files and put into list in another method | <p>I have a directory with files, I need to get a listing of these files to put into another method. It is in the context of webassets(https://github.com/miracle2k/webassets) so it looks like this, the specific case:</p>
<pre><code>app_css = Bundle('app_assets/css/base.css',
'app_assets/css/layout.css... | <p>If you want to get a list of all <code>css</code> files in a directory you can use the <code>glob</code> module:</p>
<pre><code>my_files = glob.glob('path_to_the_directory/*.css')
</code></pre>
<p>Basically <code>glob</code> will expand like the filenames in the shell. You can also use it for directories. For exam... | python|file|directory | 0 |
903 | 12,468,707 | Retrieving Variable & Processing List from Tastypie URL | <p>Let's say my override_urls is like so:</p>
<pre><code>def override_urls(self):
return [
url(r"^(?P<resource_name>%s)/(?P<user__username>\w{4,30})%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('dispatch_list'), name="api_dispatch_list"),
]
</code></pre>
<p>I'd li... | <p>The user_username argument is passed in kwargs through the dispatching process not in request.GET.</p>
<p>You probably would want to override the
<a href="https://github.com/toastdriven/django-tastypie/blob/master/tastypie/resources.py#L1116" rel="nofollow">get_list method</a> and process the additional argument in... | python|django|tastypie | 1 |
904 | 682,923 | Dynamically change the choices in a wx.ComboBox() | <p>I didn't find a better way to change the different choices in a wx.ComboBox() than swap the old ComboBox with a new one. Is there a better way?</p>
<p>Oerjan Pettersen</p>
<pre><code>#!/usr/bin/python
#20_combobox.py
import wx
import wx.lib.inspection
class MyFrame(wx.Frame):
def __init__(self, *args, **kwa... | <p><a href="http://docs.wxwidgets.org/stable/classwx_combo_box.html" rel="noreferrer">wx.ComboBox</a> derives from <a href="http://docs.wxwidgets.org/stable/classwx_item_container.html" rel="noreferrer">wx.ItemContainer</a>, which has methods for <a href="http://docs.wxwidgets.org/stable/classwx_item_container.html#a8f... | python|wxpython|wxwidgets | 36 |
905 | 47,119,364 | Python/MyPy: How to annotate a method that can return one of several different types of objects? | <p>How should I annotate the return type of a method that can return multiple different types of objects?</p>
<p>Specifically this is the method I'm having trouble with:</p>
<pre><code>def _bin_factory(self) -> Any:
"""
Returns a bin with the specificed algorithm,
heuristic, and dimensions
"""
... | <p>Here's a solution using <code>typing.Generic</code></p>
<pre><code>from typing import Generic, TypeVar
T = TypeVar('T', 'Guillotine', 'Sheet', 'MaximalRectangle')
class Guillotine:
pass
class Sheet:
pass
class MaximalRectangle:
pass
class Algo(Generic[T]):
def __init__(self, algorithm: str) -&g... | python|python-3.x|oop|types|mypy | 1 |
906 | 11,772,051 | Ending a process when a tcp connection is closed | <p>I am developing a client-server application where whenever a new client connects to the server, the server spawns a new process using the <code>multiprocessing</code> module. Its target function is a function where it takes the socket and does I/O. The problem I have is once the TCP connection is closed between th... | <p>You need to check the return value of <code>recv</code>. If it returns zero then the connection is closed nicely, if negative then there was an error.</p>
<p>And the <code>join</code> call should be in the process that creates the sub-process. However, be carefull because <code>join</code> without argument will blo... | python|sockets|tcp|process | 1 |
907 | 33,959,386 | Django - getting objects by field value (model is unknown) | <p>I'm trying to a view in Django that creates an object which contains a generic foreign key, and I want to write it in a way that would allow me to create it without specifying the type of the object for that generic FK, just the ID of the object.</p>
<p>For instance if I have this:</p>
<pre><code>class Foo1 (model... | <p>I don't belive you can fetch an object from an SQL database, without searching each table it might be in. </p>
<p>However you can write a method in Django that does this for you:</p>
<pre><code>def get_by_uuid(uuid):
for Model in [Foo1, Foo2, Foo3]:
try:
return Model.objects.get(uuid=uuid)
... | python|django|object|generics|django-queryset | 0 |
908 | 47,001,980 | Flask testing client picking up wrong view function with method | <p>I have some view functions within a Blueprint. They are like following:</p>
<pre><code>@app.route('/panel/<int:id>', methods=['GET'])
def get_panel(id):
panel = Panel.query.filter_by(id=id).first()
return jsonify(panel.getJson())
@app.route('/panel/<int:id>', methods=['POST'])
def post_panel(i... | <p>This is not correct way to handle different request type for same API endpoint. Try below approach</p>
<pre><code>from flask import request
@app.route('/panel/<int:id>', methods=['GET', 'POST'])
def get_panel(id):
if request.method == 'GET':
panel = Panel.query.filter_by(id=id).first()
... | python|flask|python-unittest|werkzeug | 1 |
909 | 46,956,567 | JavaScript event on Odoo's header button | <p>I'm trying to have a JavaScript event fired on a header button (the workflow button).</p>
<p>This is my js</p>
<pre><code>var _t = instance.web._t, QWeb = instance.web.qweb;
instance.web.FormView.include({
init: function() {
this._super.apply(this, arguments);
},
events: ... | <p>first of all add your js file following code : </p>
<pre><code>odoo.define('Modulename.filename', function (require) {
"use strict";
var form_widget = require('web.form_widgets');
var core = require('web.core');
var _t = core._t;
var QWeb = core.qweb;
form_widget.WidgetButton.include({
on_click: function() {
... | javascript|python|openerp|odoo-8 | 0 |
910 | 46,756,780 | Azure Batch Pool: How do I use a custom VM Image via Python? | <p>I want to create my Pool using Python. I can do this when using an image (Ubuntu Server 16.04) from the marketplace, but I want to use a custom image (but also Ubuntu Server 16.04) -- one which I have prepared with the desired libraries and setup.</p>
<p>This is how I am creating my pool:</p>
<pre><code>new_pool =... | <p><strong>Required Minimum Azure Batch SDK</strong></p>
<p>The <a href="https://pypi.org/project/azure-batch/" rel="nofollow noreferrer">azure-batch</a> Python SDK v4.0.0 or higher is required. Typically with <code>pip install --upgrade azure-batch</code> you should just get the newest version. If that doesn't work y... | python|azure|azure-batch | 2 |
911 | 37,771,434 | mac - pip install pymssql error | <p>I use Mac (OS X 10.11.5). I want to install module <code>pymssql</code> for python.
In <code>Terminal.app</code>, I input <code>sudo -H pip install pymssql</code>, <code>pip install pymssql</code>, <code>sudo pip install pymssql</code> . But error occur.</p>
<blockquote>
<p>The directory <code>/Users/janghyunsoo/Lib... | <p>The top voted solution did not work for me as brew did not link the older version of freetds on its own. I did this to solve the problem:</p>
<pre><code>brew unlink freetds;
brew install freetds@0.91;
brew link --force freetds@0.91
</code></pre> | python|macos|python-2.7|pymssql | 60 |
912 | 67,823,882 | How to align labels? Python | <p>So I have this program where I am supposed to receive certain information from a file and then I must separate it into groups like in a table.</p>
<pre><code>Like this:
Name Sales #Items
Randy 85 5
Charli 100 10
</code></pre>
<p>I know how to print it I would usually do this:</p>
<pre><code>print ("{... | <p>You should never use keywords as a variable. Also, the variable to be assigned should always be on the left.</p>
<pre><code>lists=[('Randy',85,5),('Charli',100,10)]
print ("{:<10} {:<10} {:<10}".format('Name', 'Sales', '#Items'))
for name, sales, item in lists:
value=name, sales,item
print... | python|label | 0 |
913 | 67,759,125 | when opened a new frame and then going back to the home page, the home page messes up | <p>when I sign in everything is fine and it takes me to the home page, when I click on view menu and then click the back button it takes me back to the home page, everything is still fine and the way I want <strong>however</strong> when I click on order menu and then press the back button to go back to the home page, ... | <p>You have to indent the methods under the class Goode Brothers</p> | python|tkinter | 0 |
914 | 29,879,520 | Import Django json into iPhone App | <p>I am looking to import some Django json into my iphone app. The following Django code:</p>
<pre><code>def jsonfixture(request):
data = StraightredFixture.objects.filter(fixturematchday=12)
json_data = serializers.serialize('json', data, use_natural_foreign_keys=True)
return HttpResponse(json_data, con... | <p>Your JSON data is an <em>array</em> of dictionaries, not a dictionary. <em>You have to cast the deserialization result as an NSArray instead of an NSDictionary.</em></p>
<p>Change this line:</p>
<pre><code>var dict = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as NSDictionary
</code></p... | python|ios|json|django|swift | 0 |
915 | 29,869,484 | UnicodeDecodeError in a pandas dataframe created from JSON file | <p>I have a piece of code running on an iPython notebook that downloads a JSON file and then parses the content into a Pandas DF. However, if I try to inspect the DF, then I get an encoding error.</p>
<pre><code>output = r.json()
columns_map = {'/people/person/date_of_birth': 'birth_date',
'/people/perso... | <p>After some research, I found that this is a problem with Python version < 3.0. For some weird reason, the quick fix is to import sys and relaod sys. This worked for me:</p>
<pre><code>import sys
reload(sys)
sys.setdefaultencoding('utf8')
</code></pre> | python|json|encoding|utf-8|ipython-notebook | 7 |
916 | 61,211,313 | unable to filter on a specific string pattern and unable to change the index in pandas | <p>I have a dataframe as below:</p>
<pre><code>customer_data =
Account ID Account Name Account Status gb
1-ABC ABC Customer Active 90
2-XYZ XYZ Customer Inactive 100
1-CBA CBA Indirect - Active 50
2-GHC ... | <p>If your dataframe looks like</p>
<pre><code>Account ID | Account Name | Account Status | gb
</code></pre>
<p>but <code>customer_data.columns</code> only contains <code>['gb']</code>, then your other columns are in a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.html" rel="no... | python|pandas | 1 |
917 | 61,517,883 | json dumps all returns index instead of attribute | <p>I am trying to grab data from my mysql database. </p>
<pre><code>from flask_mysqldb import MySQL
cur = mysql.connection.cursor()
cur.execute(SELECT id FROM users)
mysql.connection.commit()
data = cur.fetchall()
return jsonify({"result": data})
</code></pre>
<p>Right now my code returns: {result: [[1]]} However,... | <p>The cursor object has <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-description.html" rel="nofollow noreferrer"><code>description</code></a> property, which gives you information about columns in a result set. It's a list of tuples, the first element being the column name.</... | python|flask | 0 |
918 | 27,731,670 | Scrapy ImportError: No module named project.settings when using subprocess.Popen | <p>I have scrapy crawler scraping thru sites. On some occasions scrapy kills itself due to RAM issues. I rewrote the spider such that it can be split and run for a site.</p>
<p>After the initial run, I use subprocess.Popen to submit the scrapy crawler again with new start item.</p>
<p>But I am getting error </p>
<p>... | <p>Looks like the settings in not being loaded properly. One solution would be to build an egg and deploy it in the env before starting the crawler.</p>
<p>Official docs, <a href="http://doc.scrapy.org/en/0.7/topics/scrapyd.html#deploying-your-project" rel="nofollow">Eggify scrapy project</a></p> | python|scrapy|popen | 2 |
919 | 72,284,929 | Difference in placement of "return" | <p>I'm currently learning how to code and I've encountered an issue with the following use of the return function:</p>
<pre><code> unionFind = UnionFind(n)
for A, B in edges:
if not unionFind.union(A, B):
return False
return True
</code></pre>
<p>When I put return True with no inden... | <p>It is not how the return statement behaves. It is about the code scopes.
When you're putting the statement without indents, then the <code>return True</code> is outside the <code>for</code> loop scope, and it will be reached only after looping through all the <code>A</code> and <code>B</code> couples and only if the... | python|return | 0 |
920 | 72,180,701 | One of many recursive calls of a function found the correct result, but it can't "tell" the others. Is there a better fix than this ugly workaround? | <p>Recently, I was experimenting with writing a function to find a primitive value anywhere within an arbitrarily deeply nested sequence, and return the path taken to get there (as a list of indices inside each successive nested sequence, in order). I encountered a very unexpected obstacle: the function was finding t... | <p>Your first attempt is almost perfect, the only mistake is that you return the result of searching through the first list/tuple at the current depth, <em>regardless</em> of whether the <code>item</code> was found or not. Instead, you need to check for a positive result, and only return if it is one. That way you keep... | python|algorithm|recursion | 4 |
921 | 43,424,886 | How to make a text file into a list of arrays (array-in-array) and remove spaces/newlines | <p>For example I have a txt file:</p>
<pre class="lang-none prettyprint-override"><code>3 2 7 4
1 8 9 3
6 5 4 1
1 0 8 7
</code></pre>
<p>On every line there are 4 numbers and there are 4 lines. At end of lines there's \n (except the last one). The code I have is:</p>
<pre><code>f = input("Insert file name: ")
file =... | <p>Once you opened the file, use this one-liner using <code>split</code> as you mentionned and nested list comprehension:</p>
<pre><code>with open(f, encoding="UTF-8") as file: # safer way to open the file (and close it automatically on block exit)
result = [[int(x) for x in l.split()] for l in file]
</code></pr... | python|arrays|python-3.x|file | 4 |
922 | 36,885,866 | Python set decimal precision | <p>I'm writting a small code for encode with arithmetic encoding. I need to set a determinate precision but I must be doing something wrong. This is the code : </p>
<pre><code>def encode(string, probabilities):
getcontext().prec = 28
start = 0.0
width = 1.0
for ch in string:
d_start, d_width = ... | <p>The problem is that <code>getcontext().prec</code> is only used for <code>decimal.Decimal</code> variables... and you define <code>start</code> and <code>width</code> as float.</p>
<p>You should force usage of Decimal, for example that way (assuming a <code>from decimal import *</code>)</p>
<pre><code>def encode(s... | python|python-3.x | 5 |
923 | 48,616,051 | Web-element is visible and enabled but .click() fails in python selenium with phantomJS | <p>I want to click on the <code>Next</code>-button at <code>https://free-proxy-list.net/</code>. The XPATH selector is <code>//*[@id="proxylisttable_next"]/a</code> </p>
<p>I do this with the following piece of code:</p>
<pre><code>element = WebDriverWait(driver, 2, poll_frequency = 0.1).until
(EC.visibility_of_eleme... | <p>As far as I see there could be two possible causes:</p>
<ol>
<li><p>The click was not registered, though this is highly unlikely. You can look at other ways to click like JavascriptExecutor's click. </p></li>
<li><p>(Most likely) The find elements are queried right after the click is performed and before the Page 2... | python|selenium|web-scraping|phantomjs|screen-scraping | 1 |
924 | 19,894,708 | Can't Start Carbon - 12.04 - Python Error - ImportError: cannot import name daemonize | <p>I am really hoping someone can help me as I have spent at-least 15 hours trying to fix this problem. I have been given a task by a potential employer and my solution is to use graphite/carbon/collectd. I am trying to run and install carbon / graphite 0.9.12 but I simply can't get carbon to start. Every time I try an... | <pre><code>pip install 'Twisted<12.0'
</code></pre>
<p>As you can see in the <a href="https://github.com/graphite-project/carbon/blob/master/requirements.txt">requirements.txt</a>, the newer version of Twisted does not seems to play well with it</p> | python|bash|caching|macos-carbon | 46 |
925 | 19,985,818 | Python 3: Pickling and UnPickling class instances returning "no persistent load" error | <p>I am trying to make a program that collects together lots of data about when certain Players in a band are available for busking this Christmas, and I'm struggling to get the pickle function to do what I want... The data is stored in class instances of the class below, <code>Player</code>:</p>
<pre><code>import pic... | <p>You first read the list with <code>.readlines()</code>:</p>
<pre><code>print("File contains: "+str(file.readlines()))
</code></pre>
<p>then try to read it again:</p>
<pre><code>CheckForPlayers=file.read()
</code></pre>
<p>This won't work; the file pointer is now at the end of the file. Rewind or reopen the file:... | python|persistence|pickle | 3 |
926 | 20,177,086 | How to delete unwanted quotation marks in dictionary | <p>I have this file:</p>
<pre><code>shorts: cat, dog, fox
longs: supercalifragilisticexpialidocious
mosts:dog, fox
count: 13
avglen: 5.6923076923076925
cat 3
dog 4
fox 4
frogger 1
supercalifragilisticexpialidocious 1
</code></pre>
<p>I want to convert this into a dictionary with the keys as shorts,longs,most... | <p>Try out JSON, it is a standard library onboard. Your file would look like this.</p>
<pre><code>'{"shorts": ["cat", "dog", "fox"], "longs": "supercalifragilisticexpialidocious", "mosts": ["dog", "fox"], "count": 13, "avglen": "5.6923076923076925", "cat": 3, "dog": 4, "fox": 4, "frogger": 1, "supercalifragilisticexpi... | python|dictionary|python-3.3 | 0 |
927 | 4,263,421 | Django modeling problem, need a subset of foreign key field | <p>I intend to create an app for categories which will have separate category sets (vocabularies) for pages, gallery, product types etc. So there will need to be two models, vocabulary and category.</p>
<p>The categories/models.py code might be something like this:</p>
<pre><code>class Vocabulary(models.Model):
t... | <p>Filtering of selection like this is done in the form <a href="http://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.ModelChoiceField.queryset" rel="noreferrer">using a queryset</a>, or in the admin interface with <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignK... | python|django|django-models | 7 |
928 | 69,532,571 | Sum using the last two elements of a dictionary's tupled key | <p>I have lists</p>
<pre><code>A = [(i,j,k,l,m)]
B = [(l,m,k)]
</code></pre>
<p>and dictionaries</p>
<pre><code>C = {(i,j,k,l,m): val}
D = {(l,m,k): other_val}
</code></pre>
<p>I would like to create a dictionary of <code>E</code> such that</p>
<pre><code>E = {(i,j,k): C[(i,j,k,l,m)]*D[(l,m,k)]}
</code></pre>
<p>Assume... | <pre><code>from collections import defaultdict
b = set(B) # O(#B)
E = defaultdict(float)
for i,j,k,l,m in A: # O(#A)
if (l, m, k) in b:
E[i,j,k] += C[i,j,k,l,m] * D[l, m, k]
</code></pre>
<p>This approach has <code>O(#A + #B)</code> complexity.
The naive implementation, leaving correctness issues aside, i... | python|sum | 1 |
929 | 51,244,981 | Neo Smart Contract boa.blockchain module | <p>i want to build a smart contract with neo-python and in my sc i want to have this module:</p>
<pre><code>from boa.blockchain.vm.Neo.Storage import GetContext, Get, Put, Delete
</code></pre>
<p>but i get<br>
<code>No module named boa.blockchain</code>
How can i get this module linked?</p> | <p>you forgot to put <code>from</code>, and also did you install it with <code>pip install neo-boa</code> ?</p>
<pre><code>from boa.blockchain.vm.Neo.Storage import GetContext, Get, Put, Delete
</code></pre> | python | 0 |
930 | 17,313,558 | Form for multiple models | <p>Suppose I have two models:</p>
<pre><code>class Topic(models.Model):
title = models.CharField()
# other stuff
class Post(models.Model):
topic = models.ForeignKey(Topic)
body = models.TextField()
# other stuff
</code></pre>
<p>And I want to create a form contains two fields: <code>Topic.title</c... | <p>You can create two separate forms having the required fields, for each model. Then show both forms in the template inside one html element. Both forms will get rendered and then submitted individually. You can then process the forms separately in the view.</p>
<pre><code>class TopicForm(ModelForm):
class Meta... | python|django | 2 |
931 | 64,425,892 | Can't execute Python with VBA to create a file using xlwings | <p>I would like to run a Python script from Excel. The Python script has the task to create a file. As a help I used the quickstart "Call Python from Excel" as you can see here:</p>
<p><a href="https://docs.xlwings.org/en/stable/quickstart.html" rel="nofollow noreferrer">https://docs.xlwings.org/en/stable/qui... | <p>You need to save the workbook for anything to be created</p>
<p><a href="https://docs.xlwings.org/en/stable/api.html#xlwings.Book.save" rel="nofollow noreferrer">https://docs.xlwings.org/en/stable/api.html#xlwings.Book.save</a></p>
<p>In your second example, you're not specifying a full path - The working directory ... | python|excel|vba|xlwings | 1 |
932 | 69,967,552 | Creating subplot for multiple columns using loop | <p>I have a DataFrame whose list of columns look like this.</p>
<pre><code> df.columns
['dr1', 'r1', 'dr9', 'r9', 'dr21', 'r21', 'dr26', 'r26',
'dr32', 'r32', 'dr37', 'r37', 'dr49', 'r49', 'dr52', 'r52',
'dr105', 'r105', 'dr118', 'r118']
DF=
dr1 r1 dr9 r9 ... | <p>You can use <code>pd.wide_to_long</code> to turn your data into long form, then plot with pandas' groupby:</p>
<pre><code>long_data = pd.wide_to_long(df.reset_index(), ['r','dr'], i='index', j='type').reset_index()
long_data.groupby('type').plot(x='r',y='dr')
</code></pre>
<p>Or with seaborn's FacetGrid:</p>
<pre><c... | python|pandas|matplotlib|seaborn | 1 |
933 | 69,811,310 | Actual data from KFold split indices | <p>Suppose I have the following data:</p>
<pre><code>y = np.ones(10)
y[-5:] = 0
X = pd.DataFrame({'a':np.random.randint(10,20, size=(10)),
'b':np.random.randint(80,90, size=(10))})
X
a b
0 11 82
1 19 82
2 15 80
3 15 86
4 14 82
5 18 87
6 13 83
7 12 83
8 10 82
9 18... | <p>As you understand, <code>KFold().split(data)</code> returns the selected indices by fold.
To select Pandas.DataFrame rows with indices list, the easiest way is the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer">loc method</a>.</p>
<pre><code>for train_idx, ... | python|machine-learning|scikit-learn|cross-validation|k-fold | 1 |
934 | 69,875,073 | Confusion Matrix ValueError: Classification metrics can't handle a mix of binary and continuous targets | <p>I'm currently trying to make a confusion matrix for my neural network model, but keep getting this error:</p>
<pre><code>ValueError: Classification metrics can't handle a mix of binary and continuous targets.
</code></pre>
<p>I have a peptide dataset that I'm using with 100 positive and 100 negative examples, and th... | <p>The model outputs the predicted probabilities, you need to transform them back to class labels before calculating the classification metrics, see below.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.... | python|tensorflow|machine-learning|keras|neural-network | 4 |
935 | 73,024,448 | How to plot groups of stacked bars from a dataframe | <p>I am creating the plots this way:</p>
<pre><code>fig, ax = plt.subplots(figsize=(8,6))
df = pd.concat((data.assign(source=name) for data, name in zip([train_ss_freq_df, train_ss_freq_df], ['train', 'blind'])))
df[df['source']=='train'].plot(kind='bar', stacked=True, color=sns.color_palette("cres... | <ul>
<li>If the plot must be grouped and clustered, there is this <a href="https://stackoverflow.com/a/22845857/7758804">answer</a>. However, it's easier to set a multi-index and plot individual bars.</li>
<li>Plot directly with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html" rel="nofo... | python|pandas|matplotlib|data-visualization|bar-chart | 3 |
936 | 50,072,787 | Add extra footer to sphinx_rtd_theme | <p>I am attempting to add an extra footer to the <code>sphinx_rtd_theme</code> in Sphinx, running on my local machine. I have created a file <code>footer.html</code> and stored it in <code>source/_templates</code>. The file contents are given here:</p>
<pre><code>{% extends '!footer.html' %} {% block extrafooter %} {{... | <p>The problem was that the Html was embedded in an Html comment. Removing the comment made it start working. The comment was there because I took the fragment verbatim from another post.</p> | python-sphinx | 1 |
937 | 64,805,225 | SWIG wrapper adding new_ prefix to the class name and unable to get class method | <p>I have written wrapper for simple C++ void function that takes 2 string parameters.
For some reasons when I try to create an object of my class, I'm getting the name error that "name 'my class name' is not defined".
When I tried create object and specify new_ prefix before class name the object was created... | <p>Used pybin11 instead of SWIG. For my task that was much easier solution than with swig.</p> | python|c++|swig | 0 |
938 | 68,645,645 | Sorting selected multiple columns based on list in Pandas | <p>The objective is to sort a given multiple columns based on multiples list in pandas as below. Thanks to <a href="https://stackoverflow.com/a/68645254/6446053">sammywemmy</a> for the hint.</p>
<p>However, the suggestion produced a column of <code>nan</code> for the other columns that not being considered.</p>
<pre><c... | <p>Instead of passing <code>df.columns</code> pass the column names that you want to include:</p>
<pre><code>categories = {col : pd.CategoricalDtype(categories=cat, ordered=True)
for col, cat
in zip(['a','b','c'], [sort_a, sort_b, sort_c])}
</code></pre>
<p>Finally pass <code>by</code> param... | python|pandas|sorting | 2 |
939 | 68,706,719 | How to write an array to a file and then call that file and add more to the array? | <p>So as the title suggests I'm trying to write an array to a file, but then I need to recall that array and append more to it and then write it back to the same file, and then this same process over and over again.</p>
<p>The code I'm have so far is:</p>
<pre><code>c = open(r"board.txt", "r")
curr... | <p><strong>A few ways to do this:</strong></p>
<p>First, use newline as a delimiter (simple, not the most space efficient):</p>
<pre class="lang-py prettyprint-override"><code># write
my_array = ['d2d4', 'd7d5']
with open('board.txt', 'w+') as f:
f.writelines([i + '\n' for i in my_array])
# read
with open('board.t... | python | 5 |
940 | 71,764,809 | Dropdown Element with option text values in ul list - Element is not currently visible and may not be manipulated | <p><a href="https://i.stack.imgur.com/SAbCn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SAbCn.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/36p4O.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/36p4O.png" alt="enter image description h... | <p>Here's the solution that worked for me:</p>
<pre><code>#Identify the element
element = browser.find_element_by_xpath("//span[contains(text(),'Most Recent')]")
#Apply Javascript of click action
browser.execute_script("arguments[0].click();", element)
</code></pre> | python|selenium-webdriver | 0 |
941 | 60,426,647 | RSA Encryption using the user-defined keys in python | <p>I am trying to encrypt a small amount of data using RSA algorithm using python. The problem is I have the public and private RSA key. Both are stored in .pem and .ppk respectively. I am not able to find any help in google which will help me encrypt it using my keys. All the code and examples I saw generates its own ... | <p>You can use the rsa module .</p>
<pre><code>import rsa
with open('public.ppm','r') as key_pub_file:
key_pub = key_pub_file.read()
message = "hello".encode('utf8')
enc_msg = rsa.encrypt(message, key_pub)
print(enc_msg)
</code></pre> | python|python-3.x|encryption|rsa|public-key-encryption | 1 |
942 | 70,085,285 | Web scraping 2020 data from IPL website. Getting an IndexError | <p>Can someone please help me proceed with this web scraping of IPL 2020 data?
My code is as follows:</p>
<pre><code>import json
import pandas as pd
from bs4 import BeautifulSoup
from urllib.request import urlopen
scrape_url="https://www.iplt20.com/stats/2020/most-runs"
page_connect = urlopen(scrape_url)
pag... | <p>This means there is no element that it finds from <code>page_html.findAll(name='div class="js-table"')</code></p>
<p>Also, when you say <code>.string</code>, are you looking for the text of the element? If so, use <code>.text</code></p>
<p>If you are looking for a div with a certain class, I would recommen... | python|web-scraping | 0 |
943 | 66,274,589 | How to deploy Java Lambda jar using Python CDK code? | <p>Can any one help me with syntax to deploy a Java Lambda using Python CDK code? Below is the python CDK code snippet Iam using to deploy Python written Lambda.</p>
<pre><code>handler = lmb.Function(self, 'Handler',
runtime=lmb.Runtime.PYTHON_3_7,
handler='handler.handler',
code=lmb.Code.from_a... | <p>We need these imports</p>
<pre><code>from aws_cdk import (
core,
aws_lambda,
)
</code></pre>
<p><code>code</code>: jar file path
<code>handler</code>: mainClassName::methodName</p>
<pre><code> aws_lambda.Function(
self, "MyLambda",
code=aws_lambda.Code.from_asset(path='javaProjec... | python|python-3.x|amazon-web-services|aws-lambda|aws-cdk | 2 |
944 | 66,005,217 | groupby.mean function dividing by pre-group count rather than post-group count | <p>So I have the following dataset of trade flows that track imports, exports, by reporting country and partner countries. After I remove some unwanted columns, I edit my data frame such that trade flows between country A and country B is showing. I'm left with something like this:</p>
<p>[My data frame image] <a href=... | <p>In pandas, we can <code>groupby</code> multiple columns, based on my understanding you want to group by partner, country and year.</p>
<p>The following line would work:</p>
<pre class="lang-py prettyprint-override"><code>df = df.groupby(['partner_code', 'location_code', 'year'])['import_value', 'export_value'].mean(... | python|pandas|group-by|pandas-groupby | 0 |
945 | 59,096,804 | I am unable to import psycopg2 from Jupyter notebook or Jupyter Lab on Mac. I have a clean install of Catalina | <p>A similar report was posted, but the suggested solutions do not work. </p>
<pre><code>---- from Jupyter ----
Import psycopg2
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-2-7d2da0a5d979> in <module>
----> 1 import psycopg2
ModuleNotFoundError: No module ... | <p>try installing the package using: pip install psycopg2-binary. This should work.
For more information, visit: <a href="https://www.psycopg.org/docs/install.html" rel="nofollow noreferrer">https://www.psycopg.org/docs/install.html</a></p> | python|python-3.x|jupyter-notebook|psycopg2|jupyter-lab | 2 |
946 | 63,118,891 | Calculating a formula with pandas objects | <p>I am facing a following problem. I have a DataFrame</p>
<pre><code>my_df = pd.DataFrame({'a.b': [1, 2, 3], 'c': [5, 6, 7], 'd': [8, 9, 10]})
</code></pre>
<p>I am reading the following string from a config data</p>
<pre><code>some_text = "-a.b + c - d"
</code></pre>
<p>is there a possibility to calculate t... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.eval.html" rel="nofollow noreferrer"><code>pd.eval</code></a> but you need to change the column names:</p>
<pre><code>my_df.columns=my_df.columns.str.replace('.','_')
my_df.eval(some_text.replace('.','_'))
0 -4
1 -5
2 -6
dtype: int6... | python|pandas | 3 |
947 | 58,627,409 | How to convert TimeStamp to string to save figures? | <pre><code>df.index
DatetimeIndex(['2019-01-25 17:00:00', '2019-01-25 17:01:00',,
'2019-01-25 17:08:00', '2019-01-25 17:09:00',
...
'2019-02-15 07:44:00', '2019-02-15 07:45:00',
'2019-02-15 07:52:00', '2019-02-15 07:53:00'],
</code></pre>
<p>I want to save ... | <p>Use the <code>strftime</code> method of datetime objects:</p>
<pre class="lang-py prettyprint-override"><code>timestamps = df.index.strftime("%Y-%m-%d %H:%M:%S")
</code></pre>
<p>If you just want the hour, then you can simply get that (as an int) via an attribute of the datetime index:</p>
<pre class="lang-py pre... | python-3.x|pandas|matplotlib|timestamp|save | 0 |
948 | 30,662,819 | How to only add item from list if item in different list is not 0 keeping same index? | <p>I am working with Excel (using xlsxwriter and openpyxl) and I am trying to populate cells of one column from one list based on if the cell in the adjacent column has a 0 in it or not. If said adjacent column cell has a 0 in it, the code should ignore whatever number is in the second list and replace that with a 0 i... | <p>You should probably use <code>zip</code> to loop over the two lists in parallel. Also, don't try and create cell coordinates programmatically using the "A1" syntax. Both openpyxl and xlsxwriter allow the use of numeric row and column indices for this kind of thing.</p> | python|excel|list|openpyxl|xlsxwriter | 1 |
949 | 72,174,758 | Getting a disk I/O error when running an optimization with OpenMDAO | <p>I'm getting this error when running an optimtization inside a local respository using the ScipyOptimizeDriver and recording the result file. It worked flawlessly, however all of a sudden, I got this error:</p>
<pre><code> File "C:\Users\xxx\Anaconda3\envs\xxx\lib\site-packages\openmdao\recorders\sqlite_recorde... | <p>Id suggest you post this as a bug report to the <a href="https://Id%20suggest%20you%20post%20this%20as%20a%20bug%20report%20to%20the%20OpenMDAO%20issue%20tracker." rel="nofollow noreferrer">OpenMDAO issue tracker</a>. since it seems like a potentially a bug, and likely you'd need to give details about OpenMDAO vers... | python|openmdao | 1 |
950 | 45,175,029 | conditional regex in python string matching | <pre><code>pattern=re.compile(r'item (?(1)2|3)')
n=re.findall(pattern, 'item 2 item 3')
</code></pre>
<p>The output is:
['item 2', 'item 3']
But i want it to be just item 2 in case it's present in the string or item 3 in case item 2 is not present.
An explanation of my error along with the solution would be helpful.</... | <p>Is this what you are looking for?</p>
<pre><code>import re
itemlist = ["pickles", "item 2", "item3"]
text = "item 3 item 2"
for item in itemlist:
if re.search(item, text):
print (item)
break
</code></pre>
<p>Iterating over the ordered list, if a match is found break out.</p>
<pre><code>item ... | python|regex|conditional | 0 |
951 | 42,447,373 | OpenCV-Python installation - CMake error missing vtkRenderingOpenGL [Ubuntu 16.04] | <p>I'm trying to install <code>Python-OpenCV</code> in Python3 on my LTS system following <a href="http://www.pyimagesearch.com/2016/10/24/ubuntu-16-04-how-to-install-opencv/" rel="nofollow noreferrer">this</a> guide.</p>
<p>When I try to run CMake:</p>
<pre><code>cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_P... | <p>Taking advice given from the OpenCV community forum (<a href="http://answers.opencv.org/question/130153/python-opencv-installation-cmake-error-missing-vtkrenderingopengl-ubuntu-1604/" rel="nofollow noreferrer">post</a>).</p>
<p>Add this to CMake options:</p>
<pre><code>-D WITH_VTK=OFF -D BUILD_opencv_viz=OFF
</cod... | python|python-3.x|opencv|cmake|ubuntu-16.04 | 1 |
952 | 57,259,551 | ZeroMQ: set LINGER=0 does not work as expected | <p>I'm using Python bindings for ZeroMQ. My <code>libzmq</code> version is 4.2.5 and my <code>pyzmq</code> version is 17.1.2.</p>
<p>I'm trying to let a "producer" transmit a large amount of data to a "consumer". The code of the "producer" is :</p>
<pre><code># producer.py
import zmq
import time
import os
ctx = zmq.... | <blockquote>
<p><strong>Q</strong> : "<em>ZeroMQ: set <code>LINGER=0</code> does not work as expected</em>"</p>
</blockquote>
<h2>ZeroMQ set <code>LINGER=0</code> does IMHO work as expected <em>( as documented )</em>:</h2>
<p>ZeroMQ documentation is clear in stating that all the <strong><code>zmq_setsockopt()</code... | python|multithreading|message-queue|zeromq|pyzmq | 3 |
953 | 57,127,474 | How do I take time away from a time in datetime? | <p>I am working on a project that can take on time away from another time and tell me the waiting time. Eg:</p>
<p>10:43:56 - 10:39:46 = 4 minutes 10 seconds.</p>
<p>I've tried to use multiple libraries which of none have worked. After that I resorted to online tutorials with datetime as it seemed to be the closest o... | <p>As first step is necessary to convert the strings to <code>datetime</code> objects using <code>datetime.strptime</code> function (<a href="https://docs.python.org/3.6/library/datetime.html#datetime.datetime.strptime" rel="nofollow noreferrer">doc</a>). Then you can subtract these two times:</p>
<pre><code>import da... | python-3.7 | 0 |
954 | 25,750,652 | Python-handler-socket (pyhs) update function example | <p>I'm using the Python client library for the HandlerSocket MySQL plugin (<a href="https://bitbucket.org/excieve/pyhs/overview" rel="nofollow">https://bitbucket.org/excieve/pyhs/overview</a>). I can make insert and find requests, but I can't find example of how to call manager.update() function. I've read through the ... | <p>I used code example for the find function (<a href="http://python-handler-socket.readthedocs.org/en/latest/usage.html#high-level" rel="nofollow">http://python-handler-socket.readthedocs.org/en/latest/usage.html#high-level</a>) to make the update function call</p>
<pre><code># UPDATE mydb.test1 SET Cnt=5 WHERE Id=1 ... | python|mysql|handlersocket | 0 |
955 | 29,341,708 | Anaconda : IPython not running | <p>I am a newbie to python and needed to set up IPython for some project-work. I followed the Anaconda Installation Directions . Currently I am having a lot of problem in running IPython : </p>
<blockquote>
<ul>
<li>First I installed Anaconda in my home directory : <code>\home\pranav</code></li>
<li>Next I ran t... | <p>What was required was just a clean install of IPython :</p>
<blockquote>
<ul>
<li><code>pip install ipython</code></li>
<li><code>pip install 'ipython[all]'</code></li>
</ul>
</blockquote>
<p>Works like a charm :)</p> | python|python-2.7|ipython|anaconda | 1 |
956 | 19,731,346 | "The pydev nature is not configured on the project" while adding a new Python module in Eclipse | <p>I get the <strong>"The pydev nature is not configured on the project"</strong> error while adding a new Python module in Eclipse. </p>
<p>Any ideas how to fix it? How to configure the pydev nature?</p>
<p>My configuration:</p>
<ul>
<li>Mac OS X 10.9.</li>
<li>Eclipse SDK Version: 4.3.1 Build id: M20130911-1000</l... | <p>The quick solution for this problem is to uninstall PyDev and install it again. To do so: </p>
<ol>
<li>Open Eclipse.</li>
<li>Go to "Help — Install New Software..."</li>
<li>Click "What is already installed?"</li>
<li>Select "PyDev for Eclipse" and press Uninstall...</li>
<li>Go through all dialogs and repeat thes... | python|eclipse|pydev | 1 |
957 | 39,317,437 | set 'x-message-ttl' in pika python | <p>I want to set the TTL to 1 sec for a Rabbitmq queue using pika.
I tried the following code</p>
<pre><code>import ctypes
int32=ctypes.c_int
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
this=channel.queue_declare(queue='hello',
... | <pre><code>connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
this=channel.queue_declare(queue='hello',
arguments={'x-message-ttl' : 1000}
)
</code></pre>
<p>you don't need the cast</p> | python-2.7|rabbitmq|pika | 12 |
958 | 37,227,264 | sort list of lists by specific index of inner list | <p>I am trying perform some operation on a file and convert its lines to list. However the integer values are also taken as string</p>
<pre><code>l1 = [['test', 'hello', '60,'], ['why', 'to', '500,'], ['my', 'choice', '20,']]
</code></pre>
<p>because of this I am unable to sort the list of list based on these integer... | <p>Use a custom sort key, to convert the last element to an integer just when sorting:</p>
<pre><code>sorted(l1, key=lambda l: int(l[2].rstrip(',')))
</code></pre>
<p>The <code>key</code> is used to produce the value on which to sort, for each element in the list. So the <code>lambda</code> function is called for eac... | python|list|sorting|python-3.x | 2 |
959 | 37,504,470 | Tensorflow crashes when using sess.run() | <p>I'm using tensorflow 0.8.0 with Python v2.7. My IDE is PyCharm and my os is Linux Ubuntu 14.04</p>
<p>I'm noticing that the following code causes my computer to freeze and/or crash:</p>
<pre><code># you will need these files!
# https://www.kaggle.com/c/digit-recognizer/download/train.csv
# https://www.kaggle.com/... | <p>I suspect the problem arises because <code>mull[0, 2]</code>—despite its small apparent size—depends on a very large computation, including multiple convolutions, max-poolings, and a large matrix multiplication; and therefore either your computer becomes fully loaded for a long period of time, or it runs... | python|crash|tensorflow | 1 |
960 | 28,256,067 | Typecast "340" to int results in '34' losing the last zero | <p><strong>Scenario1:<br></strong>
input: <code>"1-0:1.7.0(00.471*kW)"</code>
<br>regex: <code>"[0-9]-[0-9]:1.7.0\([0]{1,}(.*)\\*kW\)"</code>
<br>output: <strong>471</strong> (as it should be)</p>
<p><strong>Scenario2:<br></strong>
input: <code>"1-0:1.7.0(00.470*kW)"</code>
<br>regex: <code>"[0-9]-[0-9]:1.7.0\([0]... | <p>You only want the digits after the <code>.</code>:</p>
<pre><code>s = "1-0:1.7.0(00.471*kW)"
print(int(re.findall(":1.7.0\([0]+\.(\d+)\\*kW\)",s)[0]))
471
s = "1-0:1.7.0(00.470*kW)"
print(int(re.findall(":1.7.0\([0]+\.(\d+)\\*kW\)",s)[0]))
470
</code></pre>
<p>Or simply:</p>
<pre><code>print(int(re.findall("\(... | python|regex | 1 |
961 | 44,076,370 | Any way to make matplotlib's Nbagg backend faster, or Inline backend higher resolution? | <p>I love using Jupyter notebooks, but can't seem to find the correct backend for visualizing plots: <code>%matplotlib inline</code> generates really low-resolution, bitmap images, but fast, and <code>%matplotlib nbagg</code> or <code>%matplotlib notebook</code> are slow, but high-resolution vector graphics.</p>
<p>Cou... | <p>As often happens, I found the answer right after posting the question. Just use</p>
<pre><code>%config InlineBackend.figure_format = 'retina'
%matplotlib inline
</code></pre>
<p>for high-resolution bitmap, or for vector graphics,</p>
<pre><code>%config InlineBackend.figure_format = 'svg'
%matplotlib inline
</code></... | python|matplotlib|jupyter-notebook|backend | 2 |
962 | 37,922,514 | Getting the md5 from .tar file | <p>I have seen answers for this but didn't get the right way to do it. Our package has been created in .tar format by some other team. How can i get the checksum of the contents of the files in tar ball using Python?
People have suggested to create md5 file while archiving but that is not the way we do. Can anybody su... | <p>The <code>tar</code> format does not contain any file integrity information on the file contents themselves. The format only contains a checksum of each header block, which contains the file metadata, but that doesn't guarantee the integrity of the file contents. </p>
<p>You can read <a href="http://www.gnu.org/s... | python-2.7|shell|md5|tarfile | 1 |
963 | 51,205,924 | pip packages not available for new user | <p>I have installed several packages as sudoer using <code>sudo pip install package_name</code> command. The packages are installed and work well in this user.
Afterwards, I have defined a new user. My problem is that the packages are not available in the new user and when trying to import them this error is appeared: ... | <p>The environment variables must be defined for the new user again.Try setting the environment variables for python and pip for the new user</p> | python|python-2.7|ubuntu|pip|ubuntu-16.04 | 0 |
964 | 51,515,569 | In Tensorflow I can't use any MultiRNNCell instance in dynamic decode, but a single RNNCell instance can work on it | <p>I make a seq2seq model using tensorflow and meet a problem that my program throws an error when I use MultiRNNCell in tf.contrib.seq2seq.dynamic_decode.</p>
<p>The problem happens over here:</p>
<pre><code>defw_rnn=tf.nn.rnn_cell.MultiRNNCell([
tf.nn.rnn_cell.LSTMCell(num_units=self.FLAGS.rnn_units,
... | <p>Well……I've figured out.The problem happened because I only sent the final state of the encoder to a decoder.</p> | python-3.x|tensorflow|nlp|deep-learning|seq2seq | 0 |
965 | 48,485,255 | How can access Uploaded File in Google colab | <p>I'm new in python and I use <code>Google Colab</code> . I uploaded a <code>train_data.npy</code> into google Colab and then I want to use it . According to this link <a href="https://stackoverflow.com/questions/47212852/how-to-import-and-read-a-shelve-or-numpy-file-in-google-colaboratory">How to import and read a sh... | <p>Here's an adjustment to your snippet that will save any uploaded file in the current directory using the uploaded file name.</p>
<pre><code>from google.colab import files
uploaded = files.upload()
for name, data in uploaded.items():
with open(name, 'wb') as f:
f.write(data)
print ('saved file', name)
</c... | python|google-colaboratory | 5 |
966 | 4,835,050 | Custom dictionary through **kw | <p>I have a library function that makes use of <code>**kw</code>, but I want to pass a dictionary-like class so that I can override <code>__getitem__</code> to track its accesses to data in the dictionary. For example, in the code below calling libfn does not print Accessed but libfn2 does.</p>
<pre><code>class Dtrac... | <p>You can't, without changing Python itself. It's converted to a <code>dict</code> at a lower level.</p> | python | 5 |
967 | 4,373,141 | Dealing with huge (potentially over 30000x30000) images in Python? | <p>I'm trying to use a python script called deepzoom.py to convert large overhead renders (often over 1GP) to the Deep Zoom image format (ie, google maps-esque tile format), but unfortunately it's powered by PIL, which usually ends up crashing due to memory limitations. The creator has said he's delving into VIPS, but ... | <p>I had a very similar problem and I ended up solving it by using netpbm, which works fine on windows. Netpbm had no problem with converting huge .png files and then slicing, cropping, re-combining (using pamcrop, pamdice, and pamundice) and converting back to .png without using much memory at all. I just included t... | python|image|python-imaging-library | 3 |
968 | 4,394,483 | How lambdas work? | <p>I'm learning python using the tutorial on the official python website and came across <a href="http://docs.python.org/tutorial/controlflow.html#lambda-forms" rel="nofollow">this example</a>:</p>
<pre><code>>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)... | <p>Consider this. <code>f</code> is the object created by the <code>make_incrementor</code> function.</p>
<p>It is a lambda, an "anonymous function".</p>
<pre><code>>>> f= lambda x: x+42
>>> f(10)
52
</code></pre>
<p>The value for <code>x</code> showed up when we applied <code>f</code> to a value.... | python|lambda | 5 |
969 | 73,788,187 | Python terminal Freeze but don't throw error | <p>can someone help me in working with python and i found a bug where the python just Freeze and but not crashing nor throw error
It's just Freeze.</p>
<p>It worked fine for a while but when it's been running for like 1-2 hours it freezed</p>
<p>i try to add print("something") to see if the loop still working... | <p>Write at the end of your code , at the exception in the while : sys.exc_info()</p> | python | 0 |
970 | 64,805,533 | Simple repeating level system | <p>Trying to prototype a simple leveling system where you can add or subtract xp, every time the user levels up the xp needed to level up again should increase by 100 and the users xp should go back down keeping any xp over the needed amount. So far all of those things mentioned sort of work however it seems if I go pa... | <p>If you're looking for other ways to improve your code, <strong>modularity</strong> is often a big one</p>
<pre class="lang-py prettyprint-override"><code># a function which returns the amount of xp needed to pass a level
def xp_per_level(level):
return (level + 1) * 100
# a function which wraps around the xp an... | python | 1 |
971 | 63,763,884 | Having Trouble Making a RESTful API with Flask-RestX: "No operations defined in spec!" and "404"s | <p>In summary, I have been following the flask restx tutorials to make an api, however none of my endpoints appear on the swagger page ("No operations defined in spec!") and I just get 404 whenever I call them</p>
<p>I created my api mainly following this <a href="https://flask-restx.readthedocs.io/en/latest/... | <h2>TL;DR</h2>
<p>I made a few mistakes in my code and test:</p>
<ol>
<li>Registering api before declaring the routes.</li>
<li>Making a wierd assumption about how the arguments would be passed to the <code>post</code> method.</li>
<li>Using a model instead of request parser in the <code>expect</code> decorator</li>
<l... | python|python-3.x|flask-restx | 3 |
972 | 72,077,490 | Django multiple relations in one model | <p>I have been trying to create a model that could represent the form as it is, tried creating an <code>EntryForm</code> model which is linked to <code>EntryFormTable</code> where then each column in the table is a model class all linked to the table, but then this proved to be a long way and one that doesn't even work... | <p>It is recommended to model the "things" as they are in real life, and not as they would appear on the screen. So don't create a model called <code>EntryForm</code>, <code>EntryFormTable</code> or <code>EntryFormColumn</code>, but rather name them what they are. Example based on your image:</p>
<pre><code>c... | python|django|django-models | 0 |
973 | 68,666,152 | change a specific value in yaml file with lot of indentation using python | <pre><code>kind: Deployment
apiVersion: apps/v1
metadata:
name: websitemanager
namespace: white
selfLink: /apis/apps/v1/namespaces/white/deployments/websitemanager
generation: 89
labels:
app: websitemanager
app.kubernetes.io/instance: websitemanager
backup: kube-noah
annotations:
deployment.... | <p>You were just missing that the level at key <code>"containers"</code> is a list, so the zeroth index must be used to get to the <code>image</code> key:</p>
<pre class="lang-py prettyprint-override"><code>import yaml
with open('deployment.yaml', 'r') as fin:
content = yaml.load(fin, Loader=yaml.FullLoa... | python|yaml | 1 |
974 | 62,029,517 | Visualising geospatial .tiff images with Rasterio | <p>I am trying to visualise a .tiff image in Jupiter Notebook using Rasterio. I am a Junior Data Scientist for an AgriTech company and we just got access to 8 data layers (NDVI etc.) for two farms in .tiff format.</p>
<p>Here is the metadata for one image:</p>
<pre><code>{'driver': 'GTiff', 'dtype': 'float32', 'nodat... | <p>here are a couple solutions that might help visualize multiple-band rasters with clarity. In both examples, <code>raster</code> is a <a href="https://rasterio.readthedocs.io/en/latest/api/rasterio.io.html" rel="nofollow noreferrer"><code>rasterio.DatasetReader</code></a> with multiple bands (<a href="https://rasteri... | python|jupyter-notebook|visualization|geospatial|rasterio | 2 |
975 | 67,354,339 | How stop re-writing log data during program re-run / Python | <p>I having an issue with logging. Every time when i re-run my program it overwrites log data in file as I need to store previous data as well. I have created if statements when there is file it doesn't create a new one as i thought, but it doesn't solved my problem. Maybe someone knows the issue? Thank you in advance!... | <p>Not quite understand your problem. But if you don't want to overwrite log files, change the <a href="https://docs.python.org/3/library/logging.html#logging.basicConfig" rel="nofollow noreferrer"><code>filemode</code></a> to <code>'a'</code> which will append new log to your log files.</p> | python|audit-logging | 3 |
976 | 68,306,000 | How the iter() method work in the str class? | <p>Why when you call the <code>__next__()</code> method on <code>str</code> it says it does not have this method ...</p>
<pre><code>b = 'hello'
b.__next__() # give AttributeError: 'str' object has no attribute '__next__'
a = iter(b)
a.__next__() # output == 'h'
</code></pre>
<p>Does not the <code>__iter__()</code... | <p><a href="https://www.programiz.com/python-programming/methods/built-in/iter" rel="nofollow noreferrer"><code>iter</code></a> only returns its argument if the value is an iterator. <code>str</code> is <em>not</em> an iterator; it is an iterable whose <code>__iter__</code> method returns a <code>str_iterator</code> ob... | python | 6 |
977 | 59,796,619 | "errorMessage": "local variable 'action' referenced before assignment", "errorType": "UnboundLocalError" | <p>I tried to make the variable action global but it didn't work. It seems that any variable inside the else statement is isolated from the rest of the code, although they are in the same block of code in the for loop.</p>
<pre><code>for group in auto_scaling_groups:
if servers_need_to_be_started(group):
p... | <p>The error is saying "after executing the "then" block of the if statement, <code>action</code> is not set but is used on the error line". The fix is to ensure <code>action</code>, <code>min_size</code>, <code>max_size</code>, and <code>desired_capacity</code> are assigned when the "then" block of the if statement i... | python | 2 |
978 | 59,686,521 | Explain curious behavior of Pandas.Series.interpolate | <pre><code>s = pd.Series([0, 2, np.nan, 8])
print(s)
interp = s.interpolate(method='polynomial', order=2)
print(interp)
</code></pre>
<p>This prints:</p>
<pre><code>0 0.0
1 2.0
2 NaN
3 8.0
dtype: float64
0 0.000000
1 2.000000
2 4.666667
3 8.000000
dtype: float64
</code></pre>
<p>Now if I add... | <p><strong>You are actually interpolating two different functions!</strong> <br></p>
<p>In the first case you look for a function that goes thorugh the following points: <br>
(0,0), (1,2), (<strong>3</strong>,8) <br>
But in the second case you look for a function that goes through the following points: <br... | pandas|numpy|scipy|interpolation | 1 |
979 | 25,166,626 | How to set the <title> tag for IPython notebook HTML output? | <p>I'm using an IPython notebook to store mixed documentation/examples for a project. I am using <code>ipython nbconvert notebook.ipynb</code> to render HTML output (uses <code>pandoc</code> internally). The problem I have is that <code>nbconvert</code> insists on giving the HTML output an ugly blank title tag:</p>
<p... | <p>The template which is being used is in:
<a href="https://github.com/jupyter/nbconvert/blob/master/nbconvert/templates/html/full.tpl#L11" rel="noreferrer">https://github.com/jupyter/nbconvert/blob/master/nbconvert/templates/html/full.tpl#L11</a></p>
<p>In particular, the line I've highlighted defines the html title.... | python-2.7|ipython-notebook | 7 |
980 | 42,658,331 | Python 3 on macOS: how to set process affinity | <p>I am trying to restrict the number of CPUs used by Python (for benchmarking & to see if it speeds up my program).</p>
<p>I have found a few Python modules for achieving this ('os', 'affinity', 'psutil') except that their methods for changing affinity only works with Linux (and sometimes Windows). There is also ... | <p>Not possible. See <a href="https://developer.apple.com/library/content/releasenotes/Performance/RN-AffinityAPI/" rel="nofollow noreferrer">Thread Affinity API Release Notes</a>:</p>
<blockquote>
<p>OS X does not export interfaces that identify processors or control thread placement—explicit thread to processor b... | python|macos|ipython|affinity | 3 |
981 | 57,509,250 | dataframe into to list of dictonaries without the index | <p>I have a dataframe as below </p>
<pre><code> NY FL IL GA CA
80.0 30.0 60.0 NaN NaN
90.0 NaN NaN 10.0 20.0
</code></pre>
<p>
When i do as below</p>
<pre><code>df.apply(lambda x : x.dropna().to_dict(),axis=1)
</code></pre>
<p>i get </p>
<pre><code>0 {'NY': 80.0, ... | <p>Try this: <code>[{k:v for (k,v) in d.items() if not np.isnan(v)} for d in df.to_dict(orient="rows")]</code></p> | python|pandas | 1 |
982 | 57,611,567 | Stripe API PaymentIntent and Billing with Python | <p>I try to use the new Stripe's PaymentIntent system to be ready when SCA will be launched in EU.</p>
<p>I only use one-time payment.</p>
<p>I succeed to make the payment with the PaymentIntent <a href="https://stripe.com/docs/payments/checkout/server#billing-address-collection" rel="nofollow noreferrer">following S... | <p>Your code is creating one-time charges via Checkout. What you are looking for is the email receipt feature as documented here <a href="https://stripe.com/docs/receipts" rel="nofollow noreferrer">https://stripe.com/docs/receipts</a></p>
<p>This lets you email your customer after a successful charge on your account w... | python|django|stripe-payments | 0 |
983 | 44,554,904 | How to compute the mean for each channel in an image in tensorflow | <p>What is the proper way to compute the mean for each channel in an image in tensorflow?</p>
<p>Any help is much appreciated!!</p> | <p>Just use <a href="https://www.tensorflow.org/api_docs/python/tf/reduce_mean" rel="nofollow noreferrer"><code>tf.reduce_mean()</code></a> and specify the axis:</p>
<blockquote>
<p>axis: The dimensions to reduce. If None (the default), reduces all
dimensions.</p>
</blockquote> | image|tensorflow|mean|channel | 2 |
984 | 66,542,847 | Socket receiving incomplete data | <p>I have a p2p network and my socket sends are either sending incomplete data or are breaking before they send the complete data. I'm not exactly sure which is happening or if something else is wrong here. Below is my sending code where I loop and send till the entire msg is sent. I notice that in my listener code fur... | <p>Welp, I figured it out. Since I'm using select as my non blocking listener, it is basically one dedicated piece of code to handle EVERY socket connection and so recvs need not be from one node. Instead of on buffer string, I now use a buffer map that maps a client socket to its own buffer so that it doesn't intermix... | python|sockets|tcp | 0 |
985 | 65,210,680 | Python tkinter Grid Manager doesn't place button on left with sticky = tk.W or sticky = 'w' | <p>With two frames within a frame, button placed in top frame, sticky=tk.W doesn't seem to have any effect.</p>
<pre><code>import tkinter as tk
def _exit():
raise SystemExit
root = tk.Tk()
frame = tk.Frame(root,width = 1200, height = 650, bg = 'Yellow')
top_frame = tk.Frame(frame, width = 1200, height = 50, bg = ... | <p>When you place a button inside of <code>top_frame</code>, it will shrink to fit the button. The button <em>is</em> to the left of <code>top_frame</code>, but <code>top_frame</code> is only as wide as the button and is centered in its space. Therefore it appears that the button isn't on the left, but it is. The butto... | python|tkinter|grid|sticky | 2 |
986 | 68,470,432 | How to change PyDev version | <p>For Python 3.9, I've installed the latest PyDev updates on Eclipse, but on my projects it does not list python 3.9 as a grammar version. What is the problem here, is there any way to select latest PyDev version on project properties?</p> | <p>The Python grammar for 3.8 and 3.9 is the same (thus, you can just use the Python 3.8 grammar for 3.9).</p>
<p>I'll update the UI in PyDev so that this is clearer...</p> | python|eclipse|pydev|python-3.9 | 0 |
987 | 68,795,096 | Use Apache beam `GroupByKey` and construct a new column - Python | <p>From this question: <a href="https://stackoverflow.com/questions/68794856/how-to-group-data-and-construct-a-new-column-python-pandas/68794973#68794973">How to group data and construct a new column - python pandas?</a>, I know how to groupby multiple columns and construct a new unique id by using <code>pandas</code>,... | <p>Assigning consecutive integers to a set is not something that's very amenable to parallel computation. It's also not very stable. Is there any reason another identifier (e.g. the tuple <code>(postcode, house_number)</code> or its hash would not be suitable?</p> | python|json|csv|apache-beam|apache-beam-io | 0 |
988 | 71,745,071 | Cannot update a Django user profile | <p>I have a react app interacting with django to create and update user profiles. I am encountering this error message when I try to update a user profile, specifically the first name and last name properties I get a response that indicates that my user profile has not been updated</p>
<pre><code>{"username":... | <p>Edit <code>urls.py</code> like this</p>
<pre><code>path('update_profile/<int:pk>/', views.UpdateProfileView.as_view(), name='update_profile'),
</code></pre>
<p>I hope this will work</p> | python|django | 0 |
989 | 62,659,725 | How do i set up the range for y axis? | <p>Im having i bit of a hard time figuring out how to plot this graph correctly, so what im doing is:</p>
<pre><code> names = ['Graves', 'Fallecidos', 'Moderados', 'Asintomaticos', 'Leves']
values = [str(df_2035_Gra), str(df_2035_fal), str(df_2035_Mod), str(df_2035_Asin), str(df_2035_leve)]
#Values: 69, 85, ... | <p>Ivan :)</p>
<p>You can use <code>plt.ylim(0, 27572)</code></p>
<p>You can check the documentation <a href="https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.ylim.html?highlight=ylim#matplotlib.pyplot.ylim" rel="nofollow noreferrer">here</a></p>
<p>I hope it helps!</p> | python|matplotlib | 0 |
990 | 70,273,868 | pandas: replace with a dictionary does not work with string of sentences | <p>I have a dataframe as follows:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'text':['Lary Page is visiting today',' His boss, Maria Jackson is here.']})
</code></pre>
<p>I have extracted the names in the list below. and used faker library to create fake names equal to the len of the person_name list, and cr... | <p>Use callback with lambda for <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>Series.str.replace</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.replace.html" rel="nofollow noreferrer"><co... | python|pandas|list|dictionary|replace | 1 |
991 | 63,621,597 | Replace part of pandas dataframe column based on the first two letters | <p>I have a pandas dataframe where I need to conditionally update the value based on the first two letters. The pattern is simple and the code below works, but it doesn't feel pythonic. I need to extend this to other letters (at least 11-19/A-J) and, while I could just add additional rows, I'd really like to do this th... | <p>I would try to make a look up dictionary and use <code>map</code> to speed things up.</p>
<p>To make the look up dictonary you could use:</p>
<pre><code>lu_dict = dict(zip([str(i) for i in range(11,20)],[chr(i) for i in range(65,74)]))
</code></pre>
<p>which returns:</p>
<pre><code>{'11': 'A',
'12': 'B',
'13': 'C'... | python|pandas|dataframe | 0 |
992 | 60,772,650 | Getting the Import error when trying to import EntityRecognizer from spacy.language package | <p>ImportError: cannot import name 'EntityRecognizer' from 'spacy.language'. </p>
<p>getting the when try importing the packages in spyder,
import spacy </p>
<p>from spacy.gold import GoldParse </p>
<p>from spacy.language import EntityRecognizer </p>
<p>spyder version: 3.3.6</p>
<p>conda version: 4.8.3</p> | <p>Try:
from spacy.pipeline import EntityRecognizer</p> | python|nlp|spacy | 4 |
993 | 68,110,133 | Assigned dimension to values in Python | <p>I tried:</p>
<pre><code>x = xr.DataArray(x, coords=[ lat_line, lon_line], dims=[ 'lat','lon'])
</code></pre>
<p>with x is array, (array([1.47937608e-01, 6.56879655e-01, ..., 2.91481077e-01); lat, lon, lat_line, lon_line is already defined with the same elements. But it still does not work.</p> | <p>I guess your x should be 2D if you declare 2 dimensions.
I think it could work if you remove the dims declaration part.
lat and lon will then be coordinate but not dimensions.</p>
<p>But it will be easier to handle if you have lat & lon as dimensions (if you want to average by coordinate bins or like that). I do... | python|python-xarray | 0 |
994 | 35,413,687 | How to Bind Event to CheckBox in UltimateListCtrl? | <p>I have been trying to figure out how to use wx.UltimateListCtrl in Python to create a customized widget. Based on some internet examples I have this basic script but i'm stuck in how to bind events inside the widget in order to get the stringtext from column 1 if checkBox in column two is selected.
This is the code:... | <p>First of all: Try not to name the ULC list as this masks the Python list.</p>
<p>There are of course multiple ways to do what you want. One solution is to keep a reference of the checkbox and link it with the index of the item. This way you can identify the item.</p>
<p>I hope this helps.</p>
<pre><code>import sy... | python|user-interface|wxpython | 1 |
995 | 25,281,612 | Celery: log each task run to it's own file? | <p>I want each job running to log to it's own file in the logs/ directory where the filename is the taskid.</p>
<pre><code>logger = get_task_logger(__name__)
@app.task(base=CallbackTask)
def calc(syntax):
some_func()
logger.info('started')
</code></pre>
<p>In my worker, I set the log file to output to by usi... | <p>Seems like I am 3 years late. Nevertheless here's my solution inspired from @Mikko Ohtamaa idea. I just made it little different by using Celery Signals and python's inbuilt logging framework for preparing and cleaning logging handle.</p>
<pre><code>from celery.signals import task_prerun, task_postrun
import logging... | python|logging|celery | 7 |
996 | 50,314,634 | How to fix "ValueError: An initializer for variable conv2d/kernel of is required" when opencv and tensorflow is used | <p>I am writing a program which is supposed to use tensorflow and opencv to
perform sign language recognition with use of Convolutional Neural Networks.
I used examplary code for MNIST classifier which can be found <a href="https://github.com/tensorflow/tensorflow/blob/r1.8/tensorflow/examples/tutorials/layers/cnn_mnis... | <p><code>[-1, 12 * 12 * 64]</code> - given the padding and maxpool layers, this should be <code>[-1, 15 * 15 * 64]</code>, because 60 / 2 / 2 = 15</p>
<p>That said, I'm not sure that's the actual or only problem, because I don't have a way to reproduce your problem.</p> | python|opencv|tensorflow|machine-learning|conv-neural-network | 0 |
997 | 61,510,868 | IBM Watson with pyqt5 window is freezing in the while loop | <p>My window freezing in the while loop how can i fix it or how to wait for input into loop if i add input("") something program is not freezing anymore but i doesnt want use console.</p>
<pre><code>from ibm_watson import AssistantV2
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
import sys
from PyQt5... | <p>You don't have to run time consuming tasks since they freeze the GUI, if a task is very time consuming then you should run it in another thread and send the result to the GUI thread using signals as shown in the following example:</p>
<pre class="lang-py prettyprint-override"><code>import threading
import sys
from... | python|pyqt5|ibm-watson | 0 |
998 | 69,343,943 | How to remove leading and trailing whitespace from each line in an MD file while preserving empty lines? | <p>I have Markdown text stored in a variable which I later write to an <code>MD</code> file. The Markdown contains trailing and leading whitespace and lines with only whitespace. I have tried to remove the whitespace from the variable as well as from the <code>MD</code> file but to no avail.</p>
<p>Please note:</p>
<ul... | <p>You could split on the line break character - <code>'\n'</code> and rejoin all the entries with the leading and trailing spaces stripped -</p>
<pre><code>print(repr(markdown))
#' ## This is a headline\n\n [1] This is the first paragraph\n \n [2] This is the second paragraph\n \n \n a. This is the third paragrap... | python|markdown | 1 |
999 | 53,808,491 | Can I delete the record where cursor is pointing not using SQL? | <pre><code>conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='123456', db='jd', charset='utf8')
cur = conn.cursor()
sql = "select * from user where username = 'XXX'"
cur.execute(sql)
</code></pre>
<p>After this piece of code has been executed,the cursor should pointing to the record I've selecte... | <p>A cursor points at a row of data returned by a <code>SELECT</code> statement, which is not the same thing as an actual row in a table.</p>
<p>A SELECT statement can perform many manipulations on its results, such as joining two or more tables together, ordering the results by a specific field, gathering only distin... | python|sql|database|pymysql | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.