Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
1,500
29,157,876
Python won't assign the right value in simple "if" statement
<p>I have a <a href="https://www.djangoproject.com/" rel="nofollow">Django</a> project where users can create reservations. I am using <strong>Tastypie</strong> for the API to which I submit simple <code>POST</code> request to in order to create a reservation in the database. </p> <p>Let's say we have a <code>request...
<p>It may be that you are not converting <code>passenger_number</code> to an integer so the comparison operators are comparing between a string and an integer.</p> <pre><code>&gt;&gt;&gt; "5" &lt; 8 False &gt;&gt;&gt; "5" &gt; 8 True </code></pre> <p>So try something like <code>num_passengers = int(instance.passenger...
python|django|django-admin|tastypie|django-signals
2
1,501
8,992,865
django admin sort foreign key field list
<p>Is there an option in the django admin view for ordering of foreign key fields? i.e. I have a foreign key to a "School" model, which shows as a dropdown, sorted on pk-- I would like it to be sorted alphabetically.</p>
<p>Sure - you can...</p> <ul> <li><a href="https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey" rel="noreferrer">ModelAdmin specific ordering via formfield_for_foreignkey</a></li> <li><a href="https://stackoverflow.com/questions/6541477/ordering-choices-in-...
python|python-3.x|django|foreign-keys|django-admin
75
1,502
52,068,066
How do you use "NextToken" in AWS API calls
<p>I've run into a little issue that I am really struggling to understand how it works. I have a tool I am writing that basically does a describe-organization to collect all the accounts in our AWS organization. Per the documentation <a href="https://boto3.readthedocs.io/en/latest/reference/services/organizations.html...
<p>Don't take the boto3 examples literally (they are not actual examples). Here is how this works:</p> <p>1) The first time you make a call to <code>list_accounts</code> you'll do it without the <code>NextToken</code>, so simply </p> <pre><code>getListAccounts = org_client.list_accounts() </code></pre> <p>2) This wi...
python|amazon-web-services|boto3|aws-organizations
30
1,503
52,022,970
IMDB web crawler - Scrapy - Python
<pre><code>import scrapy from imdbscrape.items import MovieItem class MovieSpider(scrapy.Spider): name = 'movie' allowed_domains = ['imdb.com'] start_urls = ['https://www.imdb.com/search/title?year=2017,2018&amp;title_type=feature&amp;sort=moviemeter,asc'] def parse(self, response): urls = res...
<p>I believe the issue is with </p> <pre><code>nextpg = response.css('div.desc &gt; a::attr(href)').extract_first() </code></pre> <p>On this page <a href="https://www.imdb.com/search/title?year=2017,2018&amp;title_type=feature&amp;sort=moviemeter,asc" rel="nofollow noreferrer">https://www.imdb.com/search/title?year=2...
python-3.x|scrapy|python-3.6|scrapy-spider
4
1,504
52,213,981
how do you write out "A is greater than B, C, and D" in an efficient matter?
<p><img src="https://i.stack.imgur.com/eM9Ti.png" alt="Image of code"></p> <p>How can I make this statement shorter?</p>
<p>A simple solution is to combine <code>B</code>, <code>C</code> and <code>D</code> into one "value" <a href="https://docs.python.org/3/library/functions.html#max" rel="nofollow noreferrer">using <code>max</code></a>, so you only perform one explicit test. For example, instead of:</p> <pre><code>if A &gt; B and A &gt...
python
4
1,505
51,567,190
macOS vim locale different than shell
<p>In my macOS environment, my locale environment variables include an encoding</p> <pre><code>$ locale LANG="en_US.UTF-8" LC_COLLATE="en_US.UTF-8" LC_CTYPE="en_US.UTF-8" LC_MESSAGES="en_US.UTF-8" LC_MONETARY="en_US.UTF-8" LC_NUMERIC="en_US.UTF-8" LC_TIME="en_US.UTF-8" LC_ALL="en_US.UTF-8" </code></pre> <p>However, i...
<p>Disregard, it looks like I had some settings in vimrc that were clobbering the environment settings. Everything is OK once I remove the following from vimrc</p> <pre><code>try lang en_US catch endtry </code></pre>
python|macos|shell|vim|encoding
1
1,506
59,694,696
Why this does not add the recursive values?
<p>I learned I can fix this problem making c global. But I still do not understand why c does not add the values when the fuction is called from inside the function.</p> <pre><code>def a(b,c): for n in b: #print n c += str(n) #c += "\n" if type(n)is tuple: a(n,c) ...
<p>Assuming the other logic is correct, you're discarding the recursive return results</p> <p>You can fix that with <code>c = a(n,c)</code></p>
python
1
1,507
36,680,944
Make a dictionary from two functions (Python)
<p>I need to make a dictionary from two functions (ZoekAccesieCode + ZoekOrganisme). The function ZoekAccesieCode returns lines like "Q6GZX2" and ZoekOrganisme like "Frog virus 3 (isolate Goorha)". ZoekAccesieCode need to be the key and ZoekOrganisme need to be the value. Here is my code:</p> <pre><code>import re file...
<p>Going off your barely readable code.</p> <pre><code>def make_dict(a, b): return {a:b} </code></pre>
python|dictionary
1
1,508
19,734,104
How can I catch the resulting page of a post request using requests?
<p>I'm using Python with Requests and I'm trying to send data to a form for a website that shortens links. I want to store the link to their shortened link in a variable once I use requests.post.</p> <p>I've read about status codes, but I don't quite know how to used them. Here's what the form for input looks like.</p...
<p>The easiest way would be to indeed use Requests.post and then pass this post result to <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">beautifulsoup</a> and parse the result.</p> <p>For instance: </p> <pre><code>import request from bs4 import BeautifulSoup as BS response = request.get('http...
python|python-requests
3
1,509
19,804,000
How to output in different directory?
<p>I have this:</p> <pre><code>from os import path base_path = "C:\\texts\\*.txt" for file in files: with open (file) as in_file, open(path.join(base_path,"%s_tokenized.txt" % file), "w") as out_file: data = in_file.readlines() for line in data: words = line.split() str1 = ','....
<p>Is this what you're looking for:</p> <pre><code>import os import glob source_pattern = 'c:/texts/*.txt' output_directory = 'c:/texts/tokenized' # Iterate over files matching source_pattern for input_file in glob.glob(source_pattern): # build the output filename base,ext = os.path.splitext(os.path.basename...
python
0
1,510
13,300,339
Python 3: End of File error with no message
<p>I'm having some trouble figure out how to create an EOFError without printing something after it. </p> <p>This is the section of the program I'm having trouble with:</p> <pre><code>def main(): try: k = float(input("Number? ")) newton(k) print("The approximate square root of", k,"is:",newton(k)) ...
<pre><code>def main(): try: k = float(input("Number? ")) newton(k) print("The approximate square root of", k,"is:",newton(k)) print("The error is:",(newton(k))-(math.sqrt(k))) except EOFError: pass </code></pre> <p>As a separate note, I noticed that you are using 2 s...
python|eoferror
2
1,511
13,550,949
libvlc and dbus interface
<p>I'm trying a to create a basic media player using libvlc which will be controlled through dbus. I'm using the gtk and libvlc bindings for python. The code is based on the official example from the <a href="http://git.videolan.org/?p=vlc/bindings/python.git;a=blob_plain;f=examples/gtkvlc.py;hb=HEAD" rel="nofollow">v...
<p>I can't see your implementation of your event loop, so it's hard to tell what might be causing commands to not be recognized or to be dropped. Is it possible your threads are losing the stacktrace information and are actually throwing exceptions?</p> <p>You might get more responses if you added either a psuedo-cod...
python|linux|gtk|dbus|libvlc
0
1,512
22,047,398
Configuring Flask to correctly load Bootstrap js and css files
<p>How can you use the "url_for" directive in Flask to correctly set things up so a html page that uses Bootstrap and RGraph works ?</p> <p>Say my html page looks like this (partial snippet) :-</p> <pre><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; ...
<p>Put the <code>scripts</code> directory in your <code>static</code> subdirectory, then use:</p> <pre><code>&lt;link href="{{ url_for('static', filename='scripts/bootstrap/dist/css/bootstrap.css') }}" rel="stylesheet"&gt; </code></pre> <p>The pattern here is:</p> <pre><code>{{ url_for('static', filename='path/insid...
python|flask
14
1,513
22,017,600
OpenCV darken oversaturated webcam image
<p>I have a (fairly cheap) webcam which produces images which are far lighter than it should be. The camera does have brightness correction - the adjustments are obvious when moving from light to dark - but it is consistently far to bright. </p> <p>I am looking for a way to reduce the brightness without iterating over...
<p>I forgot Raspberry Pi is just running a regular OS. What an awesome machine. Thanks for the code which confirms that you just have a regular cv2 image.</p> <p>Simple vectorized scaling (without playing with each pixel) should be simple. Below just scales every pixel. It would be easy to add a few lines to normalize...
python|opencv|camera|webcam
2
1,514
43,593,118
Need help for scrapy with CrawlSpider
<p>I am new to scrapy and stucked when I try to extract data from multiple websites by using CrawlSpider.</p> <p>Here is my codes:</p> <pre class="lang-py prettyprint-override"><code>class ivwSpider(CrawlSpider): name = "ivw-online" allowed_domains = ["ausweisung.ivw-online.de/"] start_urls = ["http://au...
<p>While the start_url is already a detail page where I could not find a list to other competitors I went up in the website hierarchy on level to the url <code>http://ausweisung.ivw-online.de/index.php?i=116</code> as start. There is a table with a long list of competitors.</p> <p>From this <code>start_url</code> you ...
python|scrapy
0
1,515
54,318,125
How to calculate shifted columns over Groups in Python Pandas
<p>I have the following pandas dataframe:</p> <pre><code> Circuit-ID DATETIME LATE? 78899 07/06/2018 15:30 1 78899 08/06/2018 17:30 0 78899 09/06/2018 20:30 1 23544 12/07/2017 23:30 1 23544 13/07/2017 19:30 0 23544 14/07/2017 20:30 1 </code></pre> <p>And I need to calculate the s...
<p>Use <code>groupby</code> and <code>shift</code>, then join it back:</p> <pre><code>df.join(df.groupby('Circuit-ID').shift().add_suffix('-1')) Circuit-ID DATETIME LATE? DATETIME-1 LATE?-1 0 78899 07/06/2018 15:30 1 NaN NaN 1 78899 08/06/2018 17:30 0 0...
python|python-3.x|pandas|pandas-groupby|shift
1
1,516
71,312,027
Python Decorator in Inheritance
<p>I have the following code:</p> <pre><code>class Foo: iterations = 3 class Bar(Foo): @test_decorator(&lt;????&gt;) def hello(self): print(&quot;Hello world!&quot;) def test_decorator(input): def my_decorator(func): def wrapper(*args, **kwargs): print(&quot;Something is ha...
<p>I found a solution to your problem. The idea is to write your own decorator.</p> <p>Since that decorator is a function wrapping your method, it has access to the class instance using the <code>*args</code> first index. From there, you can access the <code>iterations</code> variable:</p> <pre><code>def decorator(iter...
python
1
1,517
39,022,374
TensorFlow: Running the DNN Iris Example
<p>I am attempting to run the example provided on the official TensorFlow website found here: <a href="https://www.tensorflow.org/versions/r0.10/tutorials/tflearn/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.10/tutorials/tflearn/index.html</a></p> <p>For completeness, the code in question that I a...
<p>You need to change your model_dir if you update the model parameters. Likewise, deleting what was in the /tmp/iris folder had the same effect as it keeps the model state there and will try to update it when you re-fit or fail if you change the parameters.</p>
python-3.x|neural-network|tensorflow
1
1,518
47,627,934
Numpy outer addition of subarrays
<p>Is there a way, in numpy, to perform what amounts to an outer addition of subarrays?</p> <p>That is to say, I have 2 arrays of the form <code>2x2xNxM</code>, which may each be considered a stack of <code>2x2</code> matrices <code>N</code> high and <code>M</code> wide. I would like to add each of these matrices to e...
<p>Extend arrays to have more dimensions and then leverage <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>broadcasting</code></a> -</p> <pre><code>output = a1[...,None,None] + a2[...,None,None,:,:] </code></pre> <p>Sample run -</p> <pre><code>In [38]: ...
python|arrays|numpy|matrix|array-broadcasting
2
1,519
47,694,919
Printing dictionary in a While Loop
<p>I have been looking around to see if anyone has actually done it but couldn't find it so hoping I can get some help here.</p> <pre><code>newDict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30} </code></pre> <p>I created this dict and I want to use a <code>while</code> loop to out...
<p>You can make your dictionary an <code>iterator</code> calling <code>iteritems</code> (Python 2.x), or <code>iter</code> on the <code>items()</code> (Python 3.x)</p> <pre><code># Python 2.x from __future__ import print_function items = newDict.iteritems() # Python 3.x items = iter(newDict.items()) while True: ...
python|python-2.7
5
1,520
72,673,693
IndentationError: expected an indented block after 'if' statement on line 32
<p>The erro points to line 34 where finally is, but I tried to reorganize it in many different positions and it insists that the indentation is incorrect. Though as far as I learn the try, except and finally block should be aligned together. Can anyone help me figured out what the hell it wants from me??</p> <pre><code...
<p>The error is actually the lack of a statement suite on line 33, after the <code>if</code> statement on line 32. The omission is detected on line 34 because line 33 is blank and <code>finally:</code> is not the required statement or block of statements. The <code>finally:</code> itself would be fine if it also were...
python-3.x|exception|indentation
0
1,521
72,547,196
Need help installing Anaconda and Spyder
<p>so i'm having some bad issues with my conda installation. I'm running this on MacOS Monterey 12.4</p> <p>I installed the latest version &quot;Anaconda3-2022.05-MacOSX-x86_64.sh&quot; I then installed an env for spyder.</p> <pre><code>conda create -n spyder spyder </code></pre> <p>Everything seems to go ok, however e...
<p>So after research this extensively I thought I would provide the solution that ultimately worked.</p> <p>To resolve this issue you need to create an env from the conda-forge repo, in order to get the compatible versions of spyder and the spyder kernels.</p> <pre><code>conda create -n spyder-cf -c conda-forge spyder ...
python|anaconda|spyder
1
1,522
72,551,320
len function not behaving as expected
<p>I'm building a function that's applying an additional tag to an aws instance based on a dict of tags that are passed in.</p> <p>Expected behavior: When more than one <code>TEST_CUSTOMER_ID</code> is are passed in, the function should return the following dictionary of tags:</p> <pre><code>{'foo': 'bar', 'Account': '...
<p>I think you're complicating yourself a great deal here. Let's break out this function differently:</p> <pre><code>def get_acct_value(tags, customer_ids, ceid): if len(customer_ids) == 0: raise exceptions.CustomerNotFoundError(f&quot;No customer(s) found on {ceid}&quot;) tag = &quot;shared&quot; if le...
python|pytest|python-unittest
3
1,523
39,593,433
Setting of Server Side Cookie is failing - Python Tornado Framework
<p>I am trying to set server side cookies(sessions) in client side. But it is failing.</p> <p>The process is as follows:</p> <p>1) Inititate a call to an API which is residing in abc.com from blog.abc.com. </p> <p>2) The API from abc.com is going to return a response object to blog.abc.com. </p> <p>I am getting the...
<p>The cookie should still be getting set correctly on abc.com, but you can't see that cookie from javascript on blog.abc.com. This is part of the same-origin policy: you can't see cookies that are set for another domain (regardless of <code>access-control-allow-*</code>). If you need this information in the client, it...
python-2.7|session-cookies|tornado
1
1,524
16,329,505
Stepping through entities in Python 3.3 html.parser
<p>I have the following Parser:</p> <pre><code>class Parser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.tableCount = 0 def handle_starttag(self, tag, attrs): if tag == "table": for attr in attrs: if attr[0] == "class" and attr[1] == "space": ## need to ...
<pre><code>class Parser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.inTable = False def handle_starttag(self, tag, attrs): if tag == "table" and ('class','space') in attrs: self.inTable = True if self.inTable: doSomething() def h...
python|html-parsing|python-3.3
0
1,525
31,820,821
Recommended way to share pandas data frames
<p>I am working on a set of visualization tools. All the data sources have different characteristics, and the data is useful by itself, so I'm building individual front ends. Each tool stores its data in HDF5 via pandas. However, I do want the tools to cooperate, so that if they do have timeframes and data sources t...
<p>For anyone reading this in the future, I ended up going with to_msgpack; right now, you can't write a dataframe out to a file handle (see <a href="https://github.com/pydata/pandas/issues/10491" rel="nofollow">https://github.com/pydata/pandas/issues/10491</a>). There is a workaround available, but I'd prefer not to ...
python|pandas
0
1,526
31,870,047
Can I manipulate how sorted() organizes things?
<p>I'm working with a large amount of data, (a list of tuples), that I would like to organize. To be more specific:</p> <pre><code># my characters for the items in the strings are 1-9,a-e # the results of my previous program produce a list of tuples # e.g. ('string', int), where int is the count of occurrence of that ...
<p>You are sorting the individual result.</p> <p>You need to sort <em>all</em> the results.</p> <p><code>sorted</code> can take a <code>key</code> parameter. From <a href="https://docs.python.org/2/library/functions.html#sorted" rel="nofollow">the documentation</a>:</p> <blockquote> <p><code>key</code> specifies a...
python|sorting
6
1,527
38,807,203
Determine a bounding rectangle around a diagonal line
<p>A user will define a line on screen which will have, when drawn, a given thickness (<em>or width</em>).</p> <p>I now need to be able to determine the coordinates of a bounding rectangle around this. <a href="https://i.stack.imgur.com/OtuAh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OtuAh.jpg...
<pre><code>Dx= Xb - Xa Dy= Yb - Ya D= sqrt(Dx * Dx + Dy * Dy) Dx= 0.5 * W * Dx / D Dy= 0.5 * W * Dy / D </code></pre> <p>This computes <code>(Dx, Dy)</code> a vector of length <code>W/2</code> in the direction of <code>AB</code>. Then <code>(-Dy, Dx)</code> is the perpendicular vector.</p> <pre><code>Xmin = min(Xa, X...
python|java|math|geometry
7
1,528
38,846,058
How to make an array of buttons which change text upon clicking using Tkinter
<p>I'm trying to implement a simple GUI for the game of Tic Tac Toe using Tkinter. As a first step, I'm trying to make an array of buttons which change from being unlabeled to having the "X" label when clicked. I've tried the following:</p> <pre><code>import Tkinter as tk class ChangeButton: def __init__(self, m...
<p>The primary problem is that with <code>command=self.toggle_text(self.buttons[i][j]))</code>, you <em>invoke</em> the callback function and bind its <em>result</em> to <code>command. Instead, you have to bind the function itself to</code>command<code>, or a</code>lambda` that will invoke that function with the right ...
python|tkinter
2
1,529
38,674,830
Append a series of strings to a Pandas column
<p>I'm a Pandas newbie and have written some code that should append a dictionary to the last column in a row. The last column is named "Holder"</p> <p>Part of my code, which offends the pandas engine is shown below</p> <pre><code>df.loc[df[innercat] == -1, 'Holder'] += str(odata) </code></pre> <p>I get the error me...
<p>is that what you want?</p> <pre><code>In [190]: d1 = {"student name": "Peter", "data": {"notes": "Gr8 student", "Course name": "Math1"}} In [191]: d2 = {"student name": "Peter", "data": {"notes": "Foo", "Course name": "Spanish1"}} In [192]: import json In [193]: json.dumps(d1) Out[193]: '{"student name": "Peter"...
python|pandas
1
1,530
9,777,530
writing to csv, Python, different data types
<p>I'm new to Python and would like to write data of different types to the columns of a csv file.</p> <p>I have two lists and one ndarray. I would like to have these as the three columns with the first row being the variable names.</p> <p>Is there are a way to do this in one line or does one have to first convert to...
<p>You could convert it all over to a numpy array and save it with <code>savetxt</code>, but why not just do it directly? </p> <p>You can iterate through the array just like you'd iterate through a list. Just <code>zip</code> them together.</p> <pre><code>with open('output.csv', 'w') as outfile: outfile.write('C...
python|csv
4
1,531
26,026,964
is there any way to stop python to concatanate space delimited strings?
<p>Recently we found a couple of bugs in our code based because a developer forgot to add a comma in the middle of a list of strings and python just concatenated the strings. look below:</p> <p>The intended list was: ["abc", "def"]</p> <p>Developer wrote: ["abc" "def"]</p> <p>and we got: ["abcdef"]</p> <p>now I a...
<p>Yes, this is a <a href="https://docs.python.org/2/reference/lexical_analysis.html#string-literal-concatenation" rel="nofollow noreferrer">core part of python</a>:</p> <blockquote> <p>Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their...
python|string-concatenation
8
1,532
1,699,552
Python file manipulation
<p>Assume I have such folders</p> <pre><code> rootfolder | / \ \ 01 02 03 .... | 13_itemname.xml </code></pre> <p>So under my rootfolder, each directory represents a month like 01 02 03 and under these directories I have items with their create hour and item name such as 16_item1.xml, 24_item1...
<p>Here are two methods doing what you ask (if I understood it properly). One with regex, one without. You choose which one you prefer ;)</p> <p>One bit which may seem like magic is the "setdefault" line. For an explanation, see <a href="http://docs.python.org/library/stdtypes.html#dict.setdefault" rel="nofollow noref...
python|file|directory|pattern-matching
5
1,533
62,930,516
Find nearest neighbors
<p>I have a large dataframe of the form:</p> <pre><code> user_id time_interval A B C D E F G H ... Z 0 12166 2.0 3.0 1.0 1.0 1.0 3.0 1.0 1.0 1.0 ... 0.0 1 12167 0.0 0.0 1.0 0.0 0.0 1.0 0.0 ...
<p>Here's how I've done it using <code>apply</code> method. The dummy data consisting of columns A-D with an added column for neighbors:</p> <pre><code>print(df) user_id time_interval A B C D neighbors 0 12166 2 3 2 2 3 NaN 1 12167 0 1 4 3 3 NaN 2 12168 ...
python|pandas|nearest-neighbor
1
1,534
63,155,302
Create a list copy having distanced duplicate elements
<p>I have a list containing integers, I would like to create a copy of it such that duplicate elements are at least some distance apart. I am aware that it is necessary to have &quot;enough&quot; different elements and a sufficiently &quot;long&quot; starting list but I would like to create that copy or return a messag...
<p>Based on my current understanding of your problem:<br /> (Not sure how to name the operation yet;<br /> using 'takeEvery' as a placeholder.<br /> Probably there is an algorithm for that somewhere.)</p> <pre><code>def takeEvery(list, step): out = [] for pb in pbs: if pb in out: lastindex = out.index(pb)...
python|list|sorting
0
1,535
32,331,470
swig python interfacing to function using void **
<p>BACKGROUND. I have an API (third party provided) consisting of C header files and a shared library. I have managed to create a shell script for the build environment, along with a simple interface file for swig. I am trying to make this API accessible to an IPython environment such that I don't have to compile C c...
<p>I resolved my own question. The edited swig interface file, listed above in my original post, turned out to correct my issue. Turns out that somewhere along the way, I mangled the input to my function call in python and the error code returned was "undefined" from the API. </p> <p>On another note, while investig...
python|c|swig
2
1,536
32,231,676
monitoring file update using c++
<p>In c++ using windows api how do i monitor file change event</p> <p>like: "this_program.py" is updating a text file.</p> <pre><code>outfile.open("some_file_1.txt",ios::out); </code></pre> <ul> <li>then edit "some_file_1.txt", <br></li> <li>"some_file_1.txt" triggers some window event,<br></li> <li>I want to monito...
<p>There is no specific MFC option for this (as far as I know). You can use <code>FindFirstChangeNotification</code> to monitor the entire folder for changes. If change is detected then your file is possibly changed (or maybe it was another file that was changed). Read the date/time stamp on your file to see if change ...
python|c++|winapi|mfc
3
1,537
54,738,686
Calculating Manhattan distance in Python without result
<p>I have these two data frames in python and I'm trying to calculate the Manhattan distance and later on the Euclidean distance, but I'm stuck in this Manhattan distance and can't figure it out what is going wrong. <br /> Here is what I have tried so far:</p> <pre><code>ratings = pd.read_csv("toy_ratings.csv", ",") p...
<p>I think the function should give back (= return) the distance in any case: either the distance is zero as initiated, or it is is somethhing else. So the function should look like</p> <pre><code>def ManhattanDist(person1, person2): distance = 0 for rating in person1: if rating in person2: ...
python|pandas|dataframe
2
1,538
32,695,601
Flask add DB entry using a form
<p>I'm a beginner learning FLASK. I'm making an app and for it I've created a DB model User, and an HTML/ JS form that takes input. What I want is to use the form information to create a new entry in the database but I am unsure on how to do it. I tried to do this </p> <pre><code>@app.route('/add_to_db') def add_to_db...
<p>A 405 error means "method not allowed". As you are sending form data, you are using a POST request and need to allow POST requests. By default only GET requests are allowed. Change the line <code>@app.route('/add_to_db')</code> to <code>@app.route('/add_to_db', methods=['POST'])</code>.</p>
python|flask|flask-sqlalchemy
1
1,539
13,877,000
Python smtplib sometimes fails sending
<p>I wrote a simple "POP3S to Secure SMTP over TLS" MRA script in Python (see below).</p> <p>It works fine, but sometimes it returns "Connection unexpectedly closed" while trying to send via SMTP. Running the script again will deliver that message successfully.</p> <p>Please give me some suggestions why it would fail...
<p>Use Port 587 for TLS. I don't see the script use smtp_port</p> <p>Use like,</p> <pre><code>server = smtplib.SMTP( smtp_server, int(smtp_port) </code></pre> <p>For Secure SMTP (SMTP + SSL), use smtplib.SMTP_SSL</p>
python|smtp|smtplib
0
1,540
26,943,483
python list to dataframe object
<p>When I try to convert the list to pandas dataframe, I get the entire line as a single cell.</p> <pre><code>pdlist=['From: 2012-11-07 19:16:07, To: 2012-11-07 19:21:07, Downtime: 0h 05m 00s', 'From: 2012-11-13 06:16:07, To: 2012-11-13 06:21:07, Downtime: 0h 05m 00s', 'From: 201=4-10-19 18:10:57, To: 2014-10-19 18:...
<p>You need to split the items on the basis of commas . Here's a method: </p> <pre><code> pdlist2=[] for item in pdlist: pdlist2.append(item.split(',')) pd.DataFrame(pdlist2) </code></pre> <p>Using list comprehensions : </p> <pre><code>pdlist2 = [item.split(',') for item in pdlist] my_dataframe = pd.Da...
pandas
6
1,541
12,541,213
How do I fix this syntax error? I am confused
<p>Here is all my coding that I did but I keep getting this syntax error. It will be explained more at the bottom.</p> <pre><code>def main(): ActualValue() AssessedValue() printResult() def ActualValue() global actual_value actual_value = float(input("Enter actual value:\t")) def AssessedValue() ...
<p>You have the <code>\n</code> escape sequence backwards.</p> <p>Also, you need to make sure all your function definitions have a colon on the end of the line.</p> <p>Also, <code>print</code> is a function in Python 3.</p>
python|syntax-error
5
1,542
12,625,050
nginx+uwsgi+django, there seems to be some strange cache in uwsgi, help me
<p>This is uwsgi config:</p> <pre><code>[uwsgi] uid = 500 listen=200 master = true profiler = true processes = 8 logdate = true socket = 127.0.0.1:8000 module = www.wsgi pythonpath = /root/www/ pythonpath = /root/www/www pidfile = /root/www/www.pid daemonize = /root/www/www.log enable-threads = true m...
<ul> <li>uwsgi does not reload your code automatically, only development server does</li> <li>runserver is for debug purposes, uwsgi and nginx for production</li> <li>in production you can restart uwsgi by <code>service uwsgi restart</code> or via init.d script</li> <li>there is even better way to reload uwsg by using ...
python|django|nginx|uwsgi
5
1,543
12,167,261
Moving a Python environment over to a new OS install
<p>I have reinstalled my operating system (moved from windows XP to Windows 7). I have reinstalled Python 2.7.</p> <p>But i had a lot of packages installed in my old environment. (Django, sciPy, jinja2, matplotlib, numpy, networkx, to name just a view)</p> <p>I still have my old Python installation lying around on a ...
<p>That's the point where you must be able to layout your project, thus having special tools for that.</p> <p>Normally, Python packages do not do such wierd things as dealing with registry (unless they are packaged via MSI installer). The problems may start with packages that contain C extensions, so moving to another...
python|windows|copy|installation
2
1,544
41,924,740
Access the first column in each row in a list Python
<p>I have the following code in which the comments explain the output and desired output. I don't seem to be able to access (or understand the logic) behind how to access different fields in the list. </p> <pre><code>def viewrecs(username): username = (username + ".txt") with open(username,"r") as f: fRe...
<p>Because your file is not a valid CSV file. It looks more like a series of JSON objects. Each line in your file is enclosed in double quotes. So CSV reader treats it as a single column. That's why what you get in row[0]</p> <p>This is caused by the way you are writing your file. The line below tells CSV writer t...
python|field
1
1,545
47,142,567
Create and call Variables In a for loop
<p>i am trying to make it so that a user inputs a number, and that number of buttons are created Using TKinter, I have tried doing it by using the following, Where the Buttons are successfully created, however i am struggling with calling them in order to place them / display them on the grid (Added randint to simulat...
<p>You should never create dynamic variable names like you are attempting to do. It adds a lot of complexity, reduces clarity, and provides no real benefit.</p> <p>Instead, use a dictionary or list to keep track of the buttons. In your case, however, since you're never using the buttons anywhere but in the loop you ca...
python|loops|variables|tkinter
0
1,546
70,835,337
python calculate slope raster from DEM
<p>I need the slope for 4 points in austria. I have the coordinates and the DEM (from opendata Austria). I found this tutorial (<a href="https://www.earthdatascience.org/tutorials/get-slope-aspect-from-digital-elevation-model/" rel="nofollow noreferrer">https://www.earthdatascience.org/tutorials/get-slope-aspect-from-d...
<p>I managed to calculate the slope! The problem was the DEM. It had strange dimensions, with another, more precise DEM from open data it worked fine : )</p>
python|gis
0
1,547
70,894,258
Asyncify string joining in Python
<p>I have the following code snippet which I want to transform into asynchronous code (<code>data</code> tends to be a large Iterable):</p> <pre class="lang-py prettyprint-override"><code>transformed_data = (do_some_transformation(d) for d in data) stacked_jsons = &quot;\n\n&quot;.join(json.dumps(t, separators=(&quot;,...
<p>The point of <code>str.join</code> is to transform an entire list <em>at once</em>.<sup>1</sup> If items arrive incrementally, it can be advantageous to accumulate them one by one.</p> <pre class="lang-py prettyprint-override"><code>async def join(by: str, _items: 'AsyncIterable[str]') -&gt; str: &quot;&quot;&qu...
python|async-await|python-asyncio
2
1,548
33,903,202
No handlers could be found for logger "elasticsearch.trace"
<p>Updated: Turns out, this is not a function of cron. I get the same behavior when running the script from the command line, if it in fact has a record to process and communicates with ElasticSearch.</p> <hr> <p>I have a cron job that runs a python script which uses <code>pyelasticsearch</code> to index some docume...
<p>I solved this by explicitly configuring a handler for the <code>elasticsearch.trace</code> logger, as I saw in <a href="https://github.com/elastic/elasticsearch-py/blob/da1a8b92c9827e0edd0cea5a67f07ada8e9237a0/example/load.py#L169" rel="noreferrer">examples</a> from the pyelasticsearch repo.</p> <p>After importing ...
python|django|pyelasticsearch
9
1,549
46,720,838
python __init__ vs class attributes
<p>I am very new to programming. I just started for couple weeks. I spent hours reading about class but I am still confused. I have a specific question.</p> <p>I am confused on when to use class attributes, and when to use initializer (<code>__init__</code>).</p> <p>I understand that when using <code>__init__</code>,...
<p>You got everything right - except that class attributes also function like static variables in python.</p> <p>Note however that everything in the class scope is run <strong>immediately</strong> upon parsing by the python interpreter.</p> <pre><code># file1.py def foo(): print("hello world") class Person: ...
python|class
7
1,550
46,947,842
Building a mutlivariate, multi-task LSTM with Keras
<p><strong>Preamble</strong></p> <p>I am currently working on a Machine Learning problem where we are tasked with using past data on product sales in order to predict sales volumes going forward (so that shops can better plan their stocks). We essentially have time series data, where for each and every product we know...
<p>So:</p> <blockquote> <p>Firstly, how would I slice up my data for the batches? Since I have three full years, does it make sense to simply push through three batches, each time of size one year? Or does it make more sense to make smaller batches (say 30 days) and also to using sliding windows? I.e. instea...
tensorflow|machine-learning|neural-network|keras|lstm
19
1,551
38,035,317
Comparing same index in 2 lists
<p>I don't have a code for this because I have no idea how to do it, and couldn't find much help on Google.</p> <p>Is there a way to find if the same indexes on 2 lists are the same?</p> <p>For example:</p> <pre><code>x_list = [1, 2, 3, 4, 5] y_list = [1, 2, A, B, 5] </code></pre> <p>I want to know whether the firs...
<p><a href="https://docs.python.org/2/library/functions.html#zip" rel="noreferrer"><code>zip</code></a> the lists and return the test (which returns a boolean as outcome):</p> <pre><code>[i == j for i, j in zip(x_list, y_list)] </code></pre> <p>You could use <code>any</code> to quickly check for the existence of a <c...
python|python-2.7
14
1,552
27,830,650
PyOpenCL | Fail to launch a Kernel
<p>When I'm using PyOpenCL to run the kernel "SIMPLE_JOIN" it fails.</p> <p><strong>HEADER OF THE KERNEL IN .CL FILE</strong></p> <pre><code>void SIMPLE_JOIN(__global const int* a, int a_col, __global const int* a_valuesPic, __global const int* b, int b_col, __global const int* b_valuesPic, ...
<p>The first argument to your kernel invocation should be the command queue, not the context:</p> <p><code>program.SIMPLE_JOIN(</code><strong><code>queue</code></strong><code>, (a_col, b_col), None, \...</code></p>
python|opencl|gpu|gpgpu|pyopencl
0
1,553
27,623,358
local postgresql setup problems occurring when running python file
<pre><code>Traceback (most recent call last): File "app.py", line 14, in &lt;module&gt; app.config.from_object(os.environ['APP_SETTINGS']) File "/Users/nihit/Desktop/flask-intro/venv/lib/python2.7/UserDict.py", line 23, in __getitem__ raise KeyError(key) KeyError: 'APP_SETTINGS' </code></pre> <p>I get this errors when...
<p>You are missing the <code>APP_SETTINGS</code> environment variable. Define that and you'll be good to go.</p> <pre><code>export APP_SETTINGS=config.DevelopmentConfig </code></pre> <p>I'm not sure where this is first discussed in the tutorial, but you can see it about 4 minutes into the video you linked to when the...
python|postgresql|flask
0
1,554
27,575,547
re.sub on a match.group
<pre><code>for element in f: galcode_scan = re.search(ur'blah\.blah\.blah\(\'\w{5,10}', element) </code></pre> <p>If I try to perform re.sub and remove the blahs with something else and keep the last bit, the \w{5,10} becomes literal. How do I retain the characters that are taken up by that chunk of the regular exp...
<p>You can use positive lookahead (<code>(?=...)</code>) to not to match when replacing but matching as a whole pattern:</p> <pre><code>re.sub(&quot;blah\.blah\.blah\(\'(?=\w{5,10})&quot;, &quot;&quot;, &quot;blah.blah.blah('qwertyu&quot;) </code></pre> <blockquote> <p>'qwertyu'</p> </blockquote> <p>If you want to repl...
python|regex
1
1,555
43,346,300
Convert numpy.nd array to json
<p>I've a data frame genre_rail in which one column contains <code>numpy.ndarray</code>. The dataframe looks like as given below<a href="https://i.stack.imgur.com/m79ff.png" rel="noreferrer"><img src="https://i.stack.imgur.com/m79ff.png" alt="datframe"></a> </p> <p>The array in it looks like this : </p> <pre><code>...
<p>How about you convert the array to json using the <code>.tolist</code> method. Then you can write it to json like :</p> <pre><code>np_array_to_list = np_array.tolist() json_file = "file.json" json.dump(b, codecs.open(json_file, 'w', encoding='utf-8'), sort_keys=True, indent=4) </code></pre>
python|arrays|json|numpy
21
1,556
36,910,353
aggregate by group and subgroup
<p>I have a dataframe that looks like this:</p> <pre><code>Id Country amount 1 AT 10 2 BE 20 3 DE 30 1 AT 10 1 BE 20 3 DK 30 </code></pre> <p>What I want to do is aggregate amount by ID, country, So my df should lo...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.add_suffix.html" rel="nofollow"><code>add_suffix</code></a> and last <a href="http:/...
python|pandas
1
1,557
37,057,707
count occurences of number entered by the user
<p>I need to count the occurrence of the min number from input that has been entered by the user. this is what i have so far, it is displaying the max and min numbers but i don't know how to count the occurrences using ELIF e.g the smallest number occurs 'x' times' only a beginner at Python, please help </p> <pre><co...
<p>Well, you change the smallest number dynamically. This means that the count should be reset every time you change the number. The same goes for the maximum number.</p> <p>Example</p> <pre><code>max = float("-inf") min = float("inf") count_l = 0 count_s = 0 def safecast(cast_type, value, default=None): try: ...
python|input|count
1
1,558
48,441,562
Charge Account Validation Python project
<p>Design a program that asks the user to enter a charge account number. The program should determine whether the number is valid by comparing it to the following list of valid charge account numbers:</p> <pre><code>5658845 4520125 7895122 8777541 8451277 1302850 8080152 4562555 5552012 5050552 7825877 1250255 1005231...
<p>Your code is a bit off from the homework assignment, I suggest that you use search engines to research code sniplets on how to complete the tasks of the assignment:</p> <p>Step 1 -- this is a manual process, no code required</p> <p>Step 2 -- this is a manual process, no code required</p> <p>Step 3 -- you need to ...
python-3.x|validation
0
1,559
20,224,121
Problems with writing and reading files in python
<p>i need to write and read multi variables in one text file</p> <pre><code>myfile = open ("bob.txt","w") myfile.write(user1strength) myfile.write("\n") myfile.write(user1skill) myfile.write("\n") myfile.write(user2strength) myfile.write("\n") myfile.write(user2skill) myfile.close() </code></pre> <p>at the moment it ...
<p>If you are using python3 use the print function instead.</p> <pre><code>with open("bob.txt", "w") as myfile: print(user1strength, file=myfile) print(user1skill, file=myfile) print(user2strength, file=myfile) print(user2skill, file=myfile) </code></pre> <p>The print function takes care of converting...
python|file|text
2
1,560
69,497,856
Azure Python SDK retrieve Key Vault secret for storage account
<p>I have the following code for a key vault to retrieve the secret and be able to use them in a storage account backup. The following code for the key vault is the following</p> <pre class="lang-py prettyprint-override"><code>keyvault_name = f'keyvault-link' KeyVaultName = &quot;name&quot; credential = DefaultAzureCre...
<p>Thank you <a href="https://stackoverflow.com/users/188096/gaurav-mantri">Gaurav Mantri</a>. Posting your suggestion as an answer to help other community members.</p> <p>You can add value <code>client.get_secret(“your-key”).value</code></p>
azure|azure-python-sdk
1
1,561
69,330,273
Axios blocked by CORS but HTMLParser isn't? (Web Browser Scraper)
<p>I have a Python web scraper using the HTMLParser module. The website it scraps is <a href="http://consulta.siiau.udg.mx/wco/sspseca.consulta_oferta?ciclop=202120&amp;cup=D&amp;mostrarp=100000&amp;ordenp=2" rel="nofollow noreferrer">http://consulta.siiau.udg.mx/wco/sspseca.consulta_oferta?ciclop=202120&amp;cup=D&amp;...
<p>In short, you can't use the fetch API or XMLHTTPRequest to access resources that aren't allowed by the browser's cross-origin policy.</p> <p>For security reasons, browsers restrict HTTP requests initiated from scripts. A web application can only request resources from the same origin the application was loaded from ...
javascript|python|web-scraping
0
1,562
48,256,798
Image pre-processing parameters for tensorflow models
<p>I have a basic question about how to determine the image pre-processing parameters like - "IMAGE_MEAN", "IMAGE_STD" for various tensorflow pre-trained models. The Android sample applications for TensorFlow provides these parameters for a certain inception_v3 model in the ClassifierActivity.java (<a href="https://git...
<p>Unfortunately, the preprocessing requirements of various ImageNet models are still under documented. ResNet and VGG models both use the same preprocessing parameters. You can find biases for each of the color channels here:</p> <p><a href="https://github.com/fchollet/deep-learning-models/blob/master/imagenet_utils....
android|ios|tensorflow
1
1,563
48,241,666
Understanding the shape of tensorflow placeholders
<p>I am reading <a href="https://github.com/openai/pixel-cnn/blob/master/train.py" rel="nofollow noreferrer">this code</a> and I would like to understand about its implementation.</p> <hr> <p>One of the first things that I would like to know, is that what is the shape of some tensor objects (placeholders) such as <co...
<p>The shape is assembled from different command line parameters:</p> <ul> <li><code>obs_shape</code> is the shape of the input images, e.g., <code>(32, 32, 3)</code></li> <li><code>args.init_batch_size</code> and <code>args.batch_size</code> are the values from command line. It could be for example <code>30</code> an...
python|python-3.x|numpy|tensorflow
1
1,564
69,705,778
how to capture effective date in which a value change in dataframe
<p>I start with a file in which I have daily data from a group of people, and I would like to captures when one value of one column change if it did change</p> <p>The dataframe's structure looks like the one below:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>name</th> <th>st...
<p>Comapre for not equal values per groups by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.shift.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.shift</code></a>, filter by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boo...
python|pandas
1
1,565
50,113,323
Sqlite database backup and restore in flask sqlalchemy
<p>I am using flask sqlalchemy to create db which in turns create a app.db files to store tables and data. Now for the backup it should be simple to just take a copy of app.db somewhere in the server. But suppose while the app is writing data to app.db and we make a copy at that time then we might have inconsistent app...
<p>SQLite has the <a href="http://www.sqlite.org/backup.html" rel="nofollow noreferrer">backup API</a> for this, but it is not available in the built-in Python driver.</p> <p>You could</p> <ul> <li>use the <a href="https://rogerbinns.github.io/apsw/" rel="nofollow noreferrer">APSW library</a> for the backup; or</li> ...
python|sqlite|flask|flask-sqlalchemy
2
1,566
50,070,336
Django Static files URL,ROOT,DIR confusion
<p>I am using Django v1.11.In the setting file I have set like this</p> <pre><code>STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "e","static","static_root") STATICFILES_DIRS = [ os.path.join(BASE_DIR, "e","static","static_dir"), ] </code></pre> <p>Firstly I copied all my css,js,img file in static_d...
<p>The whole explanation can be found <a href="https://docs.djangoproject.com/en/2.0/howto/static-files/" rel="nofollow noreferrer">there</a></p> <p><code>STATIC_ROOT</code> provides a convenience management command for gathering static files in a single directory so you can serve them easily. When <code>DEBUG</code> ...
python|django|static
1
1,567
66,463,955
Deeplab test with a local image file
<p>I am trying to run deeplab on my local computer. I installed deeplab on my computer and defined paths. Deeplab is running successfully on my local computer. This is the last block of deeplab_demo.ipynb</p> <pre><code>SAMPLE_IMAGE = 'image1' # @param ['image1', 'image2', 'image3'] IMAGE_URL = '' #@param {type:&quot...
<p>change the local path</p> <p>_SAMPLE_URL = ('https://github.com/tensorflow/models/blob/master/research/' 'deeplab/g3doc/img/%s.jpg?raw=true')</p> <p>---&gt;</p> <p>_SAMPLE_URL = ('file:///path to/tensorflow/models/blob/master/research/' 'deeplab/g3doc/img/%s.jpg')</p>
python|tensorflow|deeplab
1
1,568
65,046,484
How to define my own continuous wavelet by using Python?
<p>As the title shows, I want to define my own continuous wavelet by Python. However, I don't know how to achieve this exactly.</p> <p>The formula of my wavelet mother function is below</p> <p><a href="https://i.stack.imgur.com/BMTsx.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BMTsx.gif" alt="ent...
<p>Per <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.cwt.html" rel="nofollow noreferrer">this</a> you need a function that takes a number of points and a scale to provide as a <code>wavelet</code> argument</p> <p>So we define it as such:</p> <pre><code>import math import numpy as np from sc...
python|scipy|wavelet|wavelet-transform|pywavelets
1
1,569
53,022,752
Dimension Problem in Keras Multilabel Classification with Word Embeddings
<p>I am currently solving an exercise which involves reading in TED talks, labelling them according to the topics they are about, and training a Feed Forward NN in Keras that can label new talks accordingly, using pre-trained word embeddings.</p> <p>Depending on what the talk is about (technology, education or design ...
<p>I found the issue:</p> <p>The last Dense layer should have 8 units, as I have 8 labels.</p>
python|tensorflow|keras|nlp
0
1,570
53,098,433
How can I run Bokeh(version 0.13) server as backgroud service in linux?
<p>Currently I am running bokeh server using this command in linux <code>bokeh serve DashboardDCD/ --port 5007 --allow-websocket-origin=52.171.38.120:5007</code> In this case i have to keep the terminal open. I want to run it in background as daemon. How can we do that? Are there any workarounds?</p>
<p>To keep Linux Process running after exiting terminal, must we use disown command, it is used after the a process has been launched and put in the background, it’s work is to remove a shell job from the shell’s active list jobs.</p> <p>In your case:</p> <pre><code>$ sudo bokeh serve DashboardDCD/ --port 5007 --allo...
python|linux|bokeh|daemon
1
1,571
65,066,310
Tensorflow Lite on MLKit giving this error: : #vk Got 1 class(es) for output index 0, expected 2 according to the label map
<p>After adding metadata to my tflite file to use it in ML Kit, I get the error <code>Calculator::Open() for node &quot;ClassifierClientCalculator&quot; failed: #vk Got 1 class(es) for output index 0, expected 2 according to the label map. </code> I have edited the number of classes in the metadata as well as the numb...
<p>Based on <a href="https://developers.google.com/ml-kit/custom-models#model-compatibility" rel="nofollow noreferrer">https://developers.google.com/ml-kit/custom-models#model-compatibility</a>, the output should be (1 * 2) or (1 * 1 * 1 * 2) if the output contains two classes. Could you double check for your output la...
java|android-studio|tensorflow|tensorflow-lite|google-mlkit
1
1,572
62,582,644
Seaborn regplot fit line does not match calculated fit from stats.linregress or stats model
<p>I am trying to fit a xlog-linear regression. I used Seaborn regplot to plot the fit, which looks like a good fit (green line). Then, because regplot does not provide the coefficients. I used stats.linregress to find the coefficients. However, that plotted line (purple) does not match the fit from Seaborn regplot. ...
<p>There are two issues with your attempt to recreate what seaborn is doing:</p> <ul> <li>you have the arguments to <code>stats.linregress</code> backwards</li> <li>that's not how yhat is computed</li> </ul> <p>Here's how you could recreate the seaborn logx regression line:</p> <pre><code>diamonds = sns.load_dataset(&q...
python|regression|seaborn|statsmodels
2
1,573
61,937,938
ModuleNotFoundError: No module named 'flask' in VS code
<p>When I run it in VS Code, it works with no errors</p> <pre class="lang-py prettyprint-override"><code>from werkzeug.wrappers import Request, Response from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == '__main__': from werkzeug.serving import ...
<p>If you're using Visual Studio too, maybe VSCode is not using the correct python interpreter. You can try choosing conda interpreter at the bottom left of the screen in VSCode.</p>
python|flask|visual-studio-code|anaconda
3
1,574
70,122,499
Python - Create plot with percentage of occurence
<p>I have a dataframe which contains orders. Each product has a color. I want to create a (line) plot of monthly data and show the occurrence of colors throughout the month.</p> <p>A snippet of the current dataframe:</p> <pre><code> Color 2021-08-25 17:43:30 Blue 2021-08-25 17:26:34 B...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Grouper.html" rel="nofollow noreferrer"><code>Grouper</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.SeriesGroupBy.value_counts.html" rel="nofollow noreferrer"><code>SeriesGroupBy.val...
python|pandas|pandas-groupby
2
1,575
66,096,330
How to extract table value from using BeautifulSoup
<p>I am trying to extract the Solar Longitude value from <a href="https://viewer.mars.asu.edu/viewer/themis#P=V77388006&amp;T=2" rel="nofollow noreferrer">this table</a></p> <p>I am using this code to look at the structure of the table:</p> <pre><code>import requests from bs4 import BeautifulSoup URL = 'https://viewer....
<p>You may get not all content back with requests, cause it is served dynamically by the website, but you can use selenium to fix that.</p> <p><strong>Example</strong></p> <pre><code>from selenium import webdriver from bs4 import BeautifulSoup driver = webdriver.Chrome(executable_path=r'C:\Program Files\ChromeDriver\...
python-3.x|web-scraping|beautifulsoup
1
1,576
59,800,286
Why does installing xlwings over the terminal produce an error?
<p>I am relatively new to Python and I am just doing a private project right now. For that I want to install xlwing to be able to run a python code from Excel. However it seems I can not install it. I try to install via:</p> <pre><code>C:\Users\Rafi&gt;python -m pip install --user xlwings </code></pre> <p>as I instal...
<p>This error comes from installing a dependency of xlwings: comtypes.</p> <p>A quick google search revealed that your issue could be caused by an old version of wheels. Upgrade wheels like this and try again:</p> <pre><code>pip install --upgrade wheel </code></pre>
python|python-3.x|pip|xlwings
0
1,577
67,781,976
Python scrapy with authentication or cookies
<p>I have the following web crawler script which is work correctly, What I need is a way to integrate authentication or sending cookies in each requests</p> <pre><code>import scrapy from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor class TheFriendlyNeighbourhoodSpider(CrawlSpi...
<pre><code>request_with_cookies = Request(url=&quot;http://www.example.com&quot;, cookies=[{'name': 'currency', 'value': 'USD', 'domain': 'example.com', 'path': '/currency'}]) </code></...
python|scrapy
0
1,578
50,568,508
How to replace values of an array with another array using numpy in Python
<p>I want to place the array B (without loops) on the array A with starting index A[0,0] </p> <pre><code>A=np.empty((3,3)) A[:] = np.nan B=np.ones((2,2)) </code></pre> <p>The result should be:</p> <pre><code>array([[ 1., 1., nan], [ 1., 1., nan], [ nan, nan, nan]]) </code></pre> <p>I tried ...
<p>Assign it where you want using indexing</p> <pre><code>import numpy as np A = np.empty((3,3)) a[:] = np.nan B = np.ones((2,2)) A[:B.shape[0], :B.shape[1]] = B array([[1.00000000e+000, 1.00000000e+000, nan], [1.00000000e+000, 1.00000000e+000, nan], [nan, nan, nan]]) </code></pre>
python|arrays|numpy
4
1,579
45,229,745
Debugging Django in VSCode fails on imp.py
<p>I am unable to debug my Django app. I am using virtualenv and have configured my VSCode workspace to point to the absolute path within my virtual environment for python.</p> <pre><code>"python.pythonPath": "/Users/Me/PyProjs/proj_env/bin/python" </code></pre> <p>When trying to debug, however, the editor jumps to t...
<p>You probably have stopOnEntry set to true in your launch.json. Try setting it to false:</p> <pre><code>{ "name": "Python: Django", "type": "python", "request": "launch", "stopOnEntry": false, "pythonPath": "${config:python.pythonPath}", "program": "${workspaceFolder}...
django|python-3.x|debugging|visual-studio-code
2
1,580
25,742,091
How to determine which instance of an object I'm dealing with?
<p>I'm making a text based dungeon crawler type game. In this game I have an enemy class and a player class. If I instantiate several enemies and place them in a grid structure along with my player, how can I detect which instance of the enemy class the player has encountered so that I can pass the instance to various ...
<p>well I did some messing around outside of my project on the online python tutor, I found that if i iterated over my list 'enemies' I could check their coordinates against the player's and and if they matched I could pass them on as a variable in this case 'currentEnemy' and it seems to work. Here's the code:</p> <p...
class|python-3.x|instance
1
1,581
24,030,352
Return an element in Pandas DataFrame with original data type
<p>I have a DataFrame with one column as <code>int</code> and one column as <code>float</code>:</p> <pre><code>In [79]: data = pd.DataFrame(dict(a = np.arange(100), b = np.arange(100.1,200.0))) In [80]: data.head() Out[80]: a b 0 0 100.1 1 1 101.1 2 2 102.1 3 3 103.1 4 4 104.1 </code></pre> <p>I w...
<p>I think if you index the column first then the row you'll get what you want.</p> <pre><code>In [6]: data.iloc[3]['a'] Out[6]: 3.0 In [7]: data['a'].iloc[3] Out[7]: 3 </code></pre>
python|pandas
2
1,582
24,147,353
Flask-SQLAlchemy many-to-many ordered relationship in hybrid_property
<p>I am trying to get the first object out of an ordered many-to-many relationship using Flask-SQLAlchemy.</p> <p>I would like to accomplish this using hybrid properties, so I can reuse my code in a clean way.</p> <p>Here is the code, with some comment:</p> <pre><code>class PrimaryModel2Comparator(Comparator): def...
<p>Perhaps looking at a working many-to-many example might help. Flask-Security is a great one.</p> <p><a href="https://pythonhosted.org/Flask-Security/quickstart.html#sqlalchemy-application" rel="nofollow">https://pythonhosted.org/Flask-Security/quickstart.html#sqlalchemy-application</a></p>
python|flask|sqlalchemy|relationship|flask-sqlalchemy
1
1,583
36,189,449
Extracting data from two dataframes to create a third
<p>I am using Python Pandas for the following. I have three dataframes, <code>df1</code>, <code>df2</code> and <code>df3</code>. Each has the same dimensions, index and column labels. I would like to create a fourth dataframe that takes elements from <code>df1</code> or <code>df2</code> depending on the values in <code...
<p><code>df4 = df1.where(df3.astype(bool), df2)</code> should do it.</p> <pre><code>import pandas as pd import numpy as np df1 = pd.DataFrame(np.random.randint(10, size = (4,2))) df2 = pd.DataFrame(np.random.randint(10, size = (4,2))) df3 = pd.DataFrame(np.random.randint(2, size = (4,2))) df4 = df1.where(df3.astype(...
python|dataframe
1
1,584
53,421,941
Flask setting cookies
<p>I try to set cookies in Flask, but I don't get what I want to. Instead of getting username I get an respone attached to my URL. My <strong>routes.py</strong></p> <pre><code>@app.route('/login', methods=['GET', 'POST']) def login(): if current_user.is_authenticated: return redirect(url_for('index')) ...
<p>Cookies are set in one request and can be used in another request. </p> <p>To overcome this, use <code>redirect</code> in <code>make_response</code>. </p> <p>I have attached an example of login/logout functionalities using cookies:</p> <p><code>app.py</code>:</p> <pre><code>from flask import Flask, render_templa...
python|cookies|flask
2
1,585
53,417,477
convert multiple dictionaries to single dictionary in python
<p>I have multiple dictionaries with its keys and values and I want to assign(transfer- all of them to a new-empty- dictionary with keeping all keys and values. note: other question that i checked have dictionaries with same size</p> <pre><code>n = {} x = {'six':6,'thirteen':13,'fifty five':55} y = {'two': 2, 'four': ...
<h3><a href="https://docs.python.org/3/library/collections.html#collections.ChainMap" rel="nofollow noreferrer"><code>ChainMap</code></a></h3> <p>For many use cases, <code>collections.ChainMap</code> suffices and is efficient (assumes Python 3.x):</p> <pre><code>from collections import ChainMap n = ChainMap(x, y, z)...
python|python-3.x|dictionary
2
1,586
40,825,363
Python - Printing duplicates after getting previous and next element in a list
<p>Sorry for the beginner question -- In running this code, it prints the output twice rather than printing once and then continuing on to the next iteration of the loop. I'm sure this is simply a formatting error, but I can't seem to spot it... Thanks!</p> <pre><code>myList = [1, 1, 1, 0.5, 1, 1, 2, 1, 0.5, 1, 3] fo...
<p><a href="https://docs.python.org/3.5/library/stdtypes.html#common-sequence-operations" rel="nofollow noreferrer"><code>index</code></a> returns the index of first occurrence of the given item, in this case <code>3</code>. You could fix the code by changing it to iterate index instead:</p> <pre><code>myList = [1, 1,...
python
1
1,587
52,300,466
Trying to select element inside webelement, but i get object is not callable error
<p>I have been trying to select element inside of web element, and i get: "TypeError: 'WebElement' object is not callable"</p> <pre><code>def get_engagmet(driver, time, a): engagment = {} body_element = driver.find_elements_by_xpath("//div[@class='_5pcr userContentWrapper']") link = body_element[a].find_el...
<p>Replace</p> <pre><code>print(link("href")) </code></pre> <p>with</p> <pre><code>print(link.get_attribute("href")) </code></pre> <p>P.S. Also you might share the URL you are trying to scrape to check if your XPath matches correctly.</p>
python|function|selenium-webdriver
1
1,588
43,718,245
How to print dictionary key and values using for loop in python
<pre><code>#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} for items in dict: print items print value </code></pre>
<p>To iterate over both the key and the value of a dictionary, you can use the <code>items()</code> method, or for Python 2.x <code>iteritems()</code></p> <p>So the code you are looking for will be as followed:</p> <pre><code>d = {'Name' : 'Zara', 'Age' : '7', 'Class' : 'First'} #dict is a key word, so you shouldn't ...
python-3.x|for-loop|iteration
1
1,589
43,820,256
Accounting for 'i' and 'j' dots in OCR python
<p>I am trying to create an OCR system in python - the first part involves extracting all characters from an image. This works fine and all characters are separated into their own bounding boxes. </p> <p>Code attached below:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib.patches a...
<p>Yes, you generally want to normalize the content of your bounding boxes to fit your character classifier's input dimensions (assuming you are working on character classifiers with explicit segmentation and not with sequence classifiers segmenting implicitly).</p> <p>For merging vertically isolated CCs of the same l...
python|artificial-intelligence|ocr|scikit-image
1
1,590
39,811,840
How can jupyter access a new tensorflow module installed in the right path?
<p>Where should I stick the model folder? I'm confused because python imports modules from somewhere in anaconda (e.g. import numpy), but I can also import data (e.g. file.csv) from the folder in which my jupyter notebook is saved in.</p> <p>The TF-Slim image models library is not part of the core TF library. So I che...
<p>From the error "ImportError: No module named datasets" <br> It seems that no package named datasets is present. You need to install datasets package and then run your script. <br> Once you install it, then you can find the package present in location <br>"/Users/me/anaconda/lib/python2.7/site-packages/" or at the <...
python|terminal|tensorflow|jupyter|jupyter-notebook
3
1,591
73,000,494
Adding a Root Node to Json output
<p>I am trying to add a top-level element to a JSON output that I get from an API.</p> <p>The following example shows the JSON output that I get from the API:</p> <pre><code>[{ &quot;Id&quot;: 1, &quot;FirstName&quot;: &quot;Ken&quot;, &quot;LastName&quot;: &quot;Sánchez&quot;, &quot;Info&quot;: { ...
<p>Is confusing why you use <code>data</code> as the name of the file, and the data itself.</p> <p>Asuming data is already a dictionary returned by the api, you can do:</p> <pre><code> with open(file_name, 'w') as f: json.dump({'info': data}, f) </code></pre>
python|json|parsing
0
1,592
73,085,437
How can i automatically fill fields for new users that register django?
<p>i have got a problem with automatically filling fields for new users that register in django. I don't know how can i get some informations.</p> <p>so this is my Profile Model</p> <pre><code>class Profile(models.Model): user = models.ForeignKey(MyUser, null=True, on_delete=models.CASCADE) name = models.CharFi...
<p>You can send <code>first_name</code> and <code>last_name</code> to Profile via your signal like this:</p> <pre><code>@receiver(post_save, sender=MyUser) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance, name=instance.first_name, last_name=instance....
python|django
1
1,593
72,852,858
I am unable to label the data points on the graph using matplotlib
<p>This is the code that I have been writing, but unable to add labels to the data points. Have tried multiple ways but getting error one after the other!! The data set in 9th line: 'country' is to be used as labelling. I want to label the 1st and last data point. Please Help!</p> <pre><code>```python import pandas as ...
<p>You can add these two additional lines after plotting the scatter plots. They will add the text to the first and last entries. You can do additional things like background box, etc. if required. You can check matplotlib documentation and examples <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.a...
python|matplotlib|data-science
0
1,594
66,631,680
why my zip returned item can't be applied set twice in Python?
<p>To illustrate my question, here is a minimal code.</p> <pre><code>x = [1,2,3] y = ['a','b','c'] m = zip(x,y) print(set(m)) print(set(m)) </code></pre> <p>I expect the second <code>print(set(m))</code> will generate the same result as the first <code>print(set(m))</code>, but here is what we got...</p> <pre><code>{(1...
<p>Since Python 3, zip now returns a iterator, not a list.</p> <p>Your first set call 'unwinds' the iterator referenced by m (consumes it).</p> <p>It is empty for the next call.</p> <p>To solve this, use</p> <pre><code>m=list(zip(x,y)). </code></pre>
python|python-3.x
5
1,595
66,522,522
Python error: "TypeError: Object of type 'NoneType' has no len()"
<p>How can I fix this error? I am attempting to eliminate the number of names the user chooses.</p> <pre><code>names = [] def eliminate(): votes = int(input(&quot;How many people would you like voted off? &quot;)) popped = random.shuffle(names) for i in range(votes): names.pop(len(popped)) print(&quot;The r...
<p><a href="https://docs.python.org/3/library/random.html#random.shuffle" rel="nofollow noreferrer"><code>random.shuffle()</code></a> returns <code>None</code>, not the shuffled list which is actually shuffled in place. Since you want to pop the last item in the list you do not need to provide an index to <code>pop()</...
python|random
2
1,596
64,824,848
Barrier in Multiprocessing Python
<p>I am working on multiprocessing in Python and I am stuck at this point.I want to put the a barrier so that all previous activities are performed first. This pseudocode will be better for understanding</p> <pre><code>def func1: #does something and returns something def func2: #does something and returns so...
<p>What you're looking for is <a href="https://docs.python.org/3.4/library/multiprocessing.html?highlight=process#multiprocessing.Process.join" rel="nofollow noreferrer"><code>Process.join()</code></a></p> <p>You would use it like this:</p> <pre class="lang-py prettyprint-override"><code>def func1: #does something...
python|multiprocessing
2
1,597
64,708,946
Pivoting a repeating Time Series Data
<p><a href="https://i.stack.imgur.com/ygdhh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ygdhh.png" alt="enter image description here" /></a>I am trying to pivot this data in such a way that I get columns like eg: AK_positive AK_probableCases, AK_negative, AL_positive.. and so on.</p> <p>You can g...
<p>Just flatten the original MultiIndex column into tuples using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.to_flat_index.html" rel="nofollow noreferrer">.to_flat_index()</a>, and rearrange tuple elements into a new column name.</p> <pre><code>df_pivoted.columns = [f&quot;{i[1...
python-3.x|pandas|pivot|pandas-groupby|data-manipulation
0
1,598
64,672,141
Python pygame sprites collision detection. How to define which sprite withing group collided and effect it's attributes by reducing a point
<p>What am trying to do is to create an <a href="https://en.wikipedia.org/wiki/Arkanoid" rel="nofollow noreferrer">Arkanoid</a> game, where the bricks have 3 points of strength each and then they die. The issue is that instead of just the particular brick that gets hit, to lose the points, the whole brick_sprite group ...
<p>I think the issue is in the <code>update()</code> of your <code>Brick</code> class calling the collision.</p> <p>The sprite update function is typically used for changing the position or look of your sprite, and is called <em>every frame</em>. So it's not a good place to check for collisions.</p> <p>A <code>Brick</...
python|pygame|sprite
1
1,599
53,011,988
Failed pycurl install on macos using pip
<p>I hope someone can help. I am currently building my python environment on my 2015 MacBook Pro which is running on Sierra 10.12.6. I have stumbled accrossed many issues downloading modules in order to run my scripts needed to automate tasks for my job (such as automated emails etc) but I have managed to overcome such...
<p>It seems that <a href="https://lists.apple.com/archives/macnetworkprog/2015/Jun/msg00025.html" rel="nofollow noreferrer">Apple stopped including OpenSSL headers</a> since OS X 10.11 El Capitan.</p> <p>To fix this, lets install OpenSSL via Homebrew:<br> If <code>openssl</code> is not installed install as below. Els...
python|macos|pip|pycurl
2