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
4,900
67,315,695
Add transparent padding to image
<p>How can I add transparent padding to all images in a specific directory?</p> <p>So for example I have images with a resolution of 100x100px and want to add: 20px top, 10px right, 40px bottom, 20px left.</p>
<p>This code works for me:</p> <pre><code>for imagePath in os.listdir(inPath): # imagePath contains name of the image inputPath = os.path.join(inPath, imagePath) # inputPath contains the full directory name img = Image.open(inputPath) # fullOutPath contains the path of the output fullOutPath ...
python|python-imaging-library
2
4,901
63,370,691
Write a program to identify whether a given line is/have a comment or not
<p>I wanna write a python program to identify if the lines are commented or not eg.</p> <ol> <li>//hello</li> <li>hi</li> <li>//hey</li> </ol> <p>Excepted output hello is a comment hi is a string hey is a comment</p>
<p>It's easy in python. Search for '//' in a string, if it is there then it's a comment.</p> <p><a href="https://i.stack.imgur.com/vMFSR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vMFSR.png" alt="enter image description here" /></a></p>
python-3.x
0
4,902
13,343,953
Python dict: How to map keys to values, where key is a range?
<p>I have a list of values:</p> <p>[0,1.51, 2.01, 2.51, 3.01,5.01, 6.01,7.01, 8.01,9.01, 10.01]</p> <p>And a second list of values:</p> <p>[.15, .22, .3, .37, .4, .5, .6, .7, .8, .9, 1]</p> <p>The rough logic of my programme is that if the value of some variable falls between two values in the first list, then set ...
<p>Have a look at the bisect module - <a href="http://docs.python.org/2/library/bisect.html">http://docs.python.org/2/library/bisect.html</a></p> <p>And the example there for percentage->grades:</p> <pre><code>&gt;&gt;&gt; def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'): i = bisect(breakpoints,...
python|list|dictionary|map|range
7
4,903
13,336,724
NameError: global name 'codepoint2name' is not defined
<p>I am using Python 2.7.3 on Windows XP I am using Pyscripter 2.5.3.0</p> <p>I am trying to get beautiful soup running and using the following test code</p> <pre><code>import urllib2 from bs4 import BeautifulSoup page = urllib2.urlopen("http://www.google.com") soup = BeautifulSoup(page) print soup.prettify() </code...
<p>This is a bug in BeautifulSoup. Clearly the author missed to import the symbol from the 'htmlentitydefs' module. So you can either fix this yourself by adding the import to the BeautifulSoup code. In addition: contact the BeautifulSoup author or file a bug report.</p>
python|python-2.7|beautifulsoup
1
4,904
13,244,378
Python HTML code syntax error
<p>I am getting the following syntax error when trying to add a hyperlink,I looked at the HTML code for href,HTML code seems right but python is throwing a syntax error..can anyone help?</p> <p>Python code</p> <pre><code> msg_body=("&lt;HTML&gt;&lt;head&gt;&lt;/head&gt;" "&lt;body&gt;Test" "&lt...
<pre><code>msg_body="""&lt;HTML&gt;&lt;head&gt;&lt;/head&gt; &lt;body&gt;Test &lt;br&gt;Hi All, &lt;br&gt; &lt;b&gt;Wiki @&lt;a href="%s"&gt;%s&lt;/a&gt; (listed @ go\link) &lt;br&gt;&lt;br&gt; &lt;b&gt;Release notes:&lt;/b&gt; %s &lt;br&gt;&lt;br&gt; &lt;b&gt;Host/Riv...
python|html
4
4,905
43,653,067
Python, removing specific long lines of text in file
<p>I've only programmed in Python for the past 8 months, so please excuse my probably noob approach to python.</p> <p>My problem is the following, which i hope someone could help me solve.</p> <p>I have lots of data in a file, for instance something like this (just a snip):</p> <pre><code>SWITCH MGMT IP;SWITCH HOSTN...
<p>You're making it way more complicated than it has to be, and not memory-friendly (you dont have to load the whole file in memory to filter duplicates).</p> <p>The simple way is to read your file line by line, and for each line check if the serial number has already been seen. If yes, skip the line, else store the s...
python|list|file|save|append
1
4,906
39,270,265
MySQLdb cursor.execute formatter
<p>I'm working with Python and MySQLdb library. This is part of a code which has been working for a lot of time.</p> <p>I was testing if the code executes correctly in other Ubuntu versions since we are planning a SO upgrade.</p> <p>The following code works fine in Ubuntu 12.04 (our baseline system now with Python 2....
<p>The parameters passed need to be iterables i.e. list or tuple. So it should be <code>(path,)</code> and not <code>(path)</code></p> <pre><code>cursor.execute('UPDATE configuration SET value=%s WHERE ' + 'property=\'OUTPUT_PATH\'', (path,)) &gt;&gt;&gt; path = 'hello' &gt;&gt;&gt; a = (path) &gt...
python|mysql|ubuntu
0
4,907
39,194,898
Queue size appears to be the ENV size in SimPy
<p>I am just starting to work on an event simulation, and I am having some issues with monitoring the queue.</p> <p>It appears that everytime I check the queue, it is actually showing the Env.now. Any advice?</p> <pre><code>import simpy num_of_machines = 2 env = simpy.Environment() bcs = simpy.Resource(env, capaci...
<p>You spawn a <code>process_client()</code> every timestep, so when the first of these processes is done after 90 time steps, you already have created 90 new processes that are queueing up. So your numbers are looking quite right.</p>
python|simpy
0
4,908
39,367,036
NetworkX - path around a node
<p>I use <a href="http://networkx.readthedocs.io/en/latest/" rel="nofollow noreferrer">NetworkX</a> to create the following graph.</p> <p><a href="https://i.stack.imgur.com/C69Jr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C69Jr.png" alt="Networkx graph"></a></p> <p>The graph is created using:<...
<p>I believe that in this specific case would suffice to find which neighbours your neighbours have in common. </p> <p>the code would be : </p> <pre><code>in_loop = set() root = (1,1) for neighb in G.neighbors(root): others = [n for n in G.neighbors((1,1)) if n != neighb] for other in others: if nei...
python|networkx
1
4,909
52,802,352
Understanding Allen Downey's 'Think Python' Section 5.14 Exercise #1
<p>Link to the exercise can be accessed here - <a href="https://greenteapress.com/thinkpython2/html/thinkpython2006.html#sec68" rel="nofollow noreferrer">Section 5.14 Exercise #1</a></p> <p>Quoting the question:</p> <blockquote> <p>Exercise 1<br /> ...</p> <p>Write a script that reads the current time and converts it t...
<p>I too have been working through the book trying to learn some python coding and today I encountered this question. And here is my attempt,</p> <pre><code>total_secs = time.time() seconds = total_secs % 60 minutes = (total_secs // 60) % 60 hours = (total_secs // 3600) % 24 days = total_secs // (3600 * 24) </code></...
python
2
4,910
52,719,743
How can I find newly installed python module in VS code?
<p>I just installed the new python3 module using terminal of Visual Studio Code on ubuntu. </p> <p>When I import it, this error occurred. </p> <p><em>[Python (analysis)] Unable to resolve 'new module'. IntelliSense may be missing for this module.</em> </p> <p>But the new module surely installed successfully. (I can ...
<p>You should look up the <a href="https://code.visualstudio.com/docs/python/environments" rel="nofollow noreferrer">official docs</a> on it. They have a neat <a href="https://code.visualstudio.com/docs/python/python-tutorial" rel="nofollow noreferrer">tutorial</a> to get you started.</p> <p>Here are a few excerpts th...
python
3
4,911
52,746,029
Are there a way with XPath in lxml for getting TEXT in chain of unknown tags <tag1>...<tagn>TEXT</tagn>...</tag1>
<p>I have a set of Elements (from lxml) with a linear html-chain of unknown tags like this:</p> <pre><code>&lt;tag1&gt;...&lt;tagn&gt;TEXT&lt;/tagn&gt;...&lt;/tag1&gt; </code></pre> <p>How could I use xpath to get the TEXT?</p> <p>I mean, if my element is elem, I could use: elem.xpath('XPATH')</p> <p>What will be X...
<p>From the position, skip everything until you found text:</p> <pre><code>elem.xpath('.//text()') </code></pre>
python|xpath|lxml
-1
4,912
37,355,274
lexicographical order in reverse order
<p>I need to make a code that sorts a list of words and puts them in lexicographical order from reverse. For example, given the list <code>["harry", "harra", harrb"]</code> I need a way to reverse each word so the list becomes <code>["yrrah", "arrah","brrah"]</code>. Then I need to sort it by lexicographical order and ...
<p>Considering the given example</p> <pre><code>list1=["harry", "harra", "harrb"] </code></pre> <p>Using list comprehension get the reverse order of the <code>list1</code> which would look like this</p> <pre><code>list1=[x[::-1] for x in list1] </code></pre> <p>Now</p> <pre><code>list1=['yrrah','arrah','brrah'] </...
python
-1
4,913
34,018,683
Creating a dictionary from txt file Python
<p>I'm trying to take a text file with a list in it take the input values and order them in an appropriate output format however I'm having difficulty trying to create a loop and create this dictionary. </p> <p>I have created a blank dictionary however I'm not sure I'm supposed to create a dictionary like in order to ...
<p>Hopefully the following will help. You need to start with an empty dictionary. For each line of your input your are correctly splitting out the two parts of your input. You can then use these to create dictionary entries. Each entry in the dictionary will be a list. <code>setdefault</code> is used to allow you to cr...
python|list|loops|dictionary|text-files
1
4,914
34,311,695
Split DF string column and add it as new column
<p>I want to take a DF column and build new column based on str splitting.<br> Column values looks like that: <em>abcd &lt;> 1234</em></p> <p>In order to split i'm using the following: </p> <pre><code>df['user_id'] = df['Customer User Id'].str.split('&lt;&gt;').str.get(1) </code></pre> <p>This action works but i'm...
<p>I am using this kind of data:</p> <pre><code>key1 key2 22 abcd &lt;&gt; 1234 34 abcd &lt;&gt; 1234 12 abcd &lt;&gt; 1234 55 abcd &lt;&gt; 1234 </code></pre> <p>And the code is:</p> <pre><code>my_df["key3"] = my_df['key2'].str.split('&lt;&gt;').str.get(1) </code></pre> <p>Output is :</p> <pr...
python|pandas
0
4,915
65,955,214
python encoding and decoding
<p>I have found a text from a book that says the following:</p> <blockquote> <p>In Python 3.X, the normal <code>str</code> string handles Unicode text (including ASCII, which is just a simple kind of Unicode); a distinct <code>bytes</code> string type represents raw byte values (including media and encoded text); and ...
<p>It's saying that in Python 2, strings are not Unicode by default, they are simple old-fashioned 8-bit characters ASCII/ANSI. So if you want to put a constant string in quotes in your source code (which is what literal means) and have it Python 2 interpret it as a Unicode string, not ASCII, then you have to put a &qu...
python|unicode
0
4,916
52,192,877
Why does inspect return different line for class inheriting from superclass?
<p>While trying to figure out if <a href="https://stackoverflow.com/a/52192154/5079316">a function is called with the <code>@decorator</code> syntax</a>, we realized that <code>inspect</code> has a different behaviour when looking at a decorated class that inherits from a superclass.</p> <p>The following behaviour was...
<p>Further experiment shows that this is a quirk of Python's line number assignment. Particularly, if we use <code>dis</code> to see the disassembly of <a href="https://ideone.com/bmt4hz" rel="noreferrer">code with and without a base class</a>:</p> <pre><code>import dis import sys dis.dis(sys._getframe().f_code) def...
python|python-3.6|decorator|python-decorators|inspect
6
4,917
39,815,695
How else part work in continue statement?
<p>I'm not sure how the <code>continue</code> statement is interpreted when it is inside a <code>for</code> loop with an <code>else</code> clause.</p> <p>If the condition is true, the <code>break</code> will exit from a <code>for</code> loop and <code>else</code> part will not be executed. And if the condition is Fals...
<p>With a <code>for</code> loop in Python, the <code>else</code> block is executed when the loop finishes normally, i.e. there is no <code>break</code> statement. A <code>continue</code> does not affect it either way.</p> <p>If the for loop ends because of a <code>break</code> statement, then <code>else</code> block w...
python|for-loop|for-else
5
4,918
40,704,821
Remove consecutive duplicate characters from a string in python
<p>Hey I was trying to write a program which will remove the consecutive duplicate characters from a string.</p> <p>for example:<br> string->aabbccde<br> first iteration: bbccde<br> second iteration: ccde<br> third Iteration: de </p> <p>and de is the answer.</p> <p>following is the program I wrote.</p> <pre><code>...
<p>python have some easier way to do this, one of them:</p> <pre><code>&gt;&gt;&gt; dup_string = 'aabcbccde' &gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; ''.join([x for x,y in groupby(dup_string) if sum(1 for i in y)&lt;2]) 'bcbde' &gt;&gt;&gt; dup_string = 'aabbccde' &gt;&gt;&gt; ''.join([x for x,y in grou...
python|string|duplicates
3
4,919
40,632,442
regex re.compile, can't get it work
<p>I tried the following:</p> <pre><code>title = 'Die.Simpsons.S02.German' season = re.compile('.*S\d|\Sd{2}|eason\d|eason\d{2}.*') test = season.match(title) print test </code></pre> <p>but I always received 'none'</p>
<p>Basing on your variable name I assume you are interested in the season number, not in the whole title. If I'm right it should look like this:</p> <pre><code>title = 'Die.Simpsons.S02.German' # This will match Die.Simpsons.S1, Die.Simpsons.S01, Die.Simpsons.Season1 etc ... reg = re.compile('.*(S|Season|eason)(\d+)'...
python|regex
3
4,920
9,913,067
The Alphabet and Recursion
<p>I'm almost done with my program, but I've made a subtle mistake. My program is supposed to take a word, and by changing one letter at a time, is eventually supposed to reach a target word, in the specified number of steps. I had been trying at first to look for similarities, for example: if the word was find, and th...
<p>I might be slightly confused about what you need, but by borrowing from <a href="http://norvig.com/spell-correct.html" rel="noreferrer">this post</a> I belive I have some code that should be helpful.</p> <pre><code>&gt;&gt;&gt; alphabet = 'abcdefghijklmnopqrstuvwxyz' &gt;&gt;&gt; word = 'java' &gt;&gt;&gt; splits =...
python|list|recursion|append|alphabet
6
4,921
68,148,307
Jupyter Notebook Kernal Error win32api not found
<p>I installed Jupyter notebook from my terminal by typing in cmd: jupyter notebook it opened Jupyter notebook in the browser. I opened a new python3 notebook <a href="https://i.stack.imgur.com/rm8VN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rm8VN.png" alt="enter image description here" /></a><...
<p>its because you have open jupyter notebook on vscode . the kernal dir has been changed from anaconda jupyter notebook to vscode jupyter notebook</p> <p>you have to change the directory vscode to anaconda</p>
python|jupyter-notebook|jupyter
2
4,922
25,982,586
Approximate Minimal Set Cover Python
<p>I have a list of lists each list contains the edge lengths of a polygon. For example:</p> <pre><code>[[0, 1, 2], [0, 1.1, 2], [0, 1.2, 2], [0, 1.3, 2], [4.5, 1.1], [4.4, 1.1], [5, 1, 2], [5, 1.1, 2], [5, 1.2, 2] [6, 1, 7, 4], [6, 1.1, 7, 4.1]] </code></pre> <p>I would like to be able to find a approx min...
<p>To find an optimal solution here will be computationally quite difficult -- you seem to be asking for something, but it doesn't have to be perfect.</p> <p>For the rest of this, I'm going to discuss a proposed algorithm for the 1D case, on the grounds that it's simpler to describe, but you can extend the algorithm t...
python|set|cover
0
4,923
1,504,378
Fitting a bimodal distribution to a set of values
<p>Given a 1D array of values, what is the simplest way to figure out what the best fit bimodal distribution to it is, where each 'mode' is a normal distribution? Or in other words, how can you find the combination of two normal distributions that bests reproduces the 1D array of values?</p> <p>Specifically, I'm inter...
<p>What you are trying to do is called a Gaussian Mixture model. The standard approach to solving this is using Expectation Maximization, scipy svn includes a section on machine learning and em called <a href="http://scipy.org/scikits.html" rel="nofollow noreferrer">scikits</a>. I use it a a fair bit.</p>
python|algorithm
4
4,924
63,087,420
Pivot pandas dataframe to long format with multiple layers
<pre><code>| | Var1 Var2 |------------|------|------|-----|------|------|-----| | | SPY | AAPL | MSFT| SPY | AAPL | MSFT | Date | | | | | | | | 2011-01-03 | 30 | 30 | 30 | 30 | 30 | 30 | | 2011-01-04...
<p>let's reproduce the dataframe 1st.</p> <p><strong>A:</strong></p> <pre><code> SPL AAPL MSFT 2011-01-03 30 30 30 2011-01-04 30 30 30 2011-01-05 30 30 30 </code></pre> <hr /> <p><strong>B:</strong></p> <pre><code> SPL AAPL MSFT 2011-01-03 30 30 30 2011-01-04 21 30 30 2011-01-05 30...
python|python-3.x|pandas|dataframe|pivot-table
2
4,925
28,179,883
Python kill scripts
<p>I need to kill all python scripts except one. Unfortunattely, all scripts have similar name "pythonw.exe". Difference in PID only.</p> <p>First time, i don't need to leave one script alive, thats why i just kill all python scripts in system by <code>taskkill /F /T /IM "python*"</code> command.</p> <p>But now, i ha...
<p>My solution is place testing code in exe file. Now i can kill all python scripts, as previously. Maybe someone will offer another solution?</p>
python|windows|multithreading
0
4,926
44,285,869
How to convert Pandas dataframe to np.array while preserving the index?
<p>For example, I have a small set of data (from movielens)</p> <p>check.csv</p> <pre><code>userId,movieId,rating,timestamp 1,31,2.5,1260759144 1,1029,3.0,1260759179 1,1061,3.0,1260759182 2,17,5.0,835355681 3,267,3.0,1298861761 3,296,4.5,1298862418 3,318,5.0,1298862121 </code></pre> <p>If I do </p> <pre><code>ratin...
<pre><code>df = pd.read_csv('check.csv') Y = pd.pivot_table(df, values=['rating'], index=['movieId'], columns=['userId']) rating userId 1 2 3 movieId 31 2.5 0 0 1029 3.0 0 0 1061 3.0 0 0 17 0 5.0 0 296 0 0 ...
python|pandas
0
4,927
32,718,770
Python PIL save Image in directory no override if the name is same
<p>I am trying to make a backup copy of an image, because it will be resized often. I am asking for the path where the image is (Tkinter), then I am adding to the path and the image an "-original" and save it in the same directory where I got it from.</p> <p>The problem is everytime I use this function it overrides th...
<p>Consider using <code>os.path.splitxext</code> instead of slicing and indexing. You can also use <code>os.path.isfile</code> instead of <code>listdir</code>.</p> <pre><code>import os pfad = askopenfilename() name, ext = os.path.splitext(pfad) backup_name = name + "-original" + ext if not os.path.isfile(backup_name):...
python|image|save|python-imaging-library
4
4,928
27,165,407
KeyError: 'id' when trying to index documents to Solr using sunburnt
<p>I am trying to index a few text files to Solr using sunburnt. Below is my code</p> <pre><code>solr_url = "http://localhost:8983/solr" h = httplib2.Http(cache="/var/tmp/solr_cache") solr_instance = sunburnt.SolrInterface(url=solr_url, http_connection=h) for url,title, webpage in webpages: html_id = hashl...
<p>If you're using Solr 4.8 or greater this is a <a href="https://github.com/tow/sunburnt/issues/90" rel="nofollow">bug against sunburnt 0.6</a>.</p> <p><a href="https://github.com/arafalov/sunburnt" rel="nofollow">The fork of sunburnt</a> by arafalov has a patch that fixed it for me.</p> <p>Try:</p> <pre><code>git ...
python|solr|sunburnt
3
4,929
12,615,290
django/python variables inside strings?
<p>I'm new to python and would like some assistance.</p> <p>I have a variable</p> <pre><code>q = request.GET['q'] </code></pre> <p>How do I insert the variable <code>q</code> inside this:</p> <pre><code>url = "http://search.com/search?term="+q+"&amp;location=sf" </code></pre> <p>Now I'm not sure what the conventio...
<p>Use the format method of String:</p> <pre><code>url = "http://search.com/search?term={0}&amp;location=sf".format(q) </code></pre> <p>But of course you should URL-encode the q:</p> <pre><code>import urllib ... qencoded = urllib.quote_plus(q) url = "http://search.com/search?term={0}&amp;location=sf".format(qenco...
python|django|variables|dynamic
5
4,930
7,810,064
query cloudant with python
<p>There may be an obvious answer to this, but I can't seem to find it anywhere: what's the best way to query couchdb databases stored on cloudant servers? I try using temporary views, a la the couchdb.py instructions:</p> <pre><code>&gt;&gt;&gt; db['johndoe'] = dict(type='Person', name='John Doe') &gt;&gt;&gt; db['...
<p>This is how I am adding a record with python.</p> <pre><code>import requests import json doc = { 'username':'kerrie', 'high_score':550, 'level':3 } auth = ('username', 'password') headers = {'Content-type': 'application/json'} post_url = "https://account.cloudant.com/database/kerrie".format(auth[0]) r = r...
python|couchdb|cloudant
3
4,931
7,699,704
Pygame Segmentation error when using the SimpleCV library findBlob function
<p>I have been using SimpleCV for find blobs to be used with a self-driving robot. The problem is when I call the findBlobs command in SimpleCV. When I completely block the lens of the Kinect Camera, PyGame crashes giving me this error:</p> <p>Fatal Python error: (pygame parachute) Segmentation Fault</p> <p>Sometime...
<p>Kat here, I wrote the SimpleCV blob library. </p> <p>There were a couple issues with the blob library that we found after we shipped the 1.1 release. The two big ones were that the blob library would hit the python max recursion depth and bail out. The second one stems from the actual underlying OpenCV wrapper and ...
python|segmentation-fault|pygame|kinect|simplecv
5
4,932
804,336
Best way to convert a Unicode URL to ASCII (UTF-8 percent-escaped) in Python?
<p>I'm wondering what's the best way -- or if there's a simple way with the standard library -- to convert a URL with Unicode chars in the domain name and path to the equivalent ASCII URL, encoded with domain as IDNA and the path %-encoded, as per RFC 3986.</p> <p>I get from the user a URL in UTF-8. So if they've type...
<h2>Code:</h2> <pre><code>import urlparse, urllib def fixurl(url): # turn string into unicode if not isinstance(url,unicode): url = url.decode('utf8') # parse it parsed = urlparse.urlsplit(url) # divide the netloc further userpass,at,hostport = parsed.netloc.rpartition('@') user,...
python|url|unicode|utf-8
46
4,933
42,025,544
How to print name of each file , and content in directory?
<p>I have many text files in a directory and I want to print each file name and its content. The problem is the content is duplicated from the previous file to the next file. Here is my code:</p> <pre><code>import os directory = os.listdir('/Users/user/My Documents/test/') os.chdir('/Users/user/My Documents/test/') fo...
<p>You don't close the files, and you should be using a <code>with</code> (which closes the file after you exit), something like this</p> <pre><code>import os directory = os.listdir('/Users/user/My Documents/test/') os.chdir('/Users/user/My Documents/test/') for file in directory: print(file) print("********...
python|file|python-3.x
0
4,934
42,071,074
Multidimensional lstm tensorflow
<p>Can someone suggest an improvement on my implementation of multi-dimensional lstm?</p> <p>It is very slow and uses a lot of memory.</p> <pre><code>class MultiDimentionalLSTMCell(tf.nn.rnn_cell.RNNCell): """ Adapted from TF's BasicLSTMCell to use Layer Normalization. Note that state_is_tuple is always True. """ de...
<pre><code>def ln(tensor, scope = None, epsilon = 1e-5): """ Layer normalizes a 2D tensor along its second axis """ assert(len(tensor.get_shape()) == 2) m, v = tf.nn.moments(tensor, [1], keep_dims=True) if not isinstance(scope, str): scope = '' with tf.variable_scope(scope + 'layer_norm'): ...
tensorflow|lstm
2
4,935
42,062,022
How to manipulate expressions in matrices using sympy?
<p>I'm writing a library, and I can construct expressions using objects from my library. For example, <code>x</code> and <code>y</code> are instances from my library, and I can construct expressions like:</p> <pre><code># below is a simplified version of my class class MySymbol(object): import random _random...
<p>You need to subclass from a SymPy class to use it within SymPy. Depending on what your class is doing will tell you what class to subclass, but the most typical superclass is <code>Expr</code>. See my answer to a very similar question <a href="https://stackoverflow.com/a/42119908/161801">here</a>.</p>
python|python-2.7|oop|matrix|sympy
2
4,936
41,840,344
Have an error " error: command 'cl.exe' failed: No such file or directory"
<p>try install mysql-python</p> <pre><code>C:\Users\Одиночка&gt;pip install mysql-python Collecting mysql-python Using cached MySQL-python-1.2.5.zip Installing collected packages: mysql-python Running setup.py install for mysql-python ... error Complete output from command c:\python27\python.exe -u -c "import ...
<p>I've met this problem too. And I tried the methods listed in Internet and not work. Either install Microsoft Visual Studio with cl.exe in computer or add C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin" to PATH. Just didn't work for me. Then as there's error shows in the middle of the error mesg:</p> <bl...
python|mysql|pip|installation|cl.exe
1
4,937
47,157,230
python transfer args from __new__ to __init__
<p>i am trying to change the args before i run the init but it doesn't change and stays as the first args that given in the main, how do i change the args from the <strong>new</strong>? </p> <pre><code>class A(object): def __init__(self,ip,st): print 'A arrived to init '+st ...
<p>It's the metaclass's <code>__call__()</code> method that both calls <code>YourClass.__new__()</code> and <code>YourClass.__init__()</code>, each time passing the arguments it received. So if you want to change the arguments before they reach <code>YourClass.__init__()</code> you have two solutions: decorating <code>...
python|class
2
4,938
70,744,695
How to use zfill to make length equivalent to 2 digit length of n
<p>I have asked a previously one question where I was impressed with unpacking approach shared by one person I am bit playing with bit to print patterns</p> <p>I want to pad the single digit with zero to make it equivalent to 2 digit number length</p> <p>I tried zfill but not throwing me error : <code>AttributeError: '...
<p>You can use <a href="https://docs.python.org/3/library/string.html#format-string-syntax" rel="nofollow noreferrer">format string syntax</a> <code>02</code>.</p> <p>change the line : <code>print(*range(1,n+1))</code> to <code>print(*(f&quot;{i:02}&quot; for i in range(1, n + 1)))</code></p> <p>Full code:</p> <pre cla...
python
1
4,939
70,876,862
Python changes are not reflected in a running app
<p>I've decided to make a simple Telegram Bot in order to learn a bit of Python. I have a main.py that imports and executes another file</p> <pre><code>#!/usr/bin/env python import butlerr if __name__ == '__main__': butlerr.main() </code></pre> <p>I run that file</p> <pre><code>&gt; python src/main.py </code></pre...
<p>What you are looking for is called hot-reloading. every famous python framework has the hot-reloading option ( so you can turn it on and off )</p> <p>first check if your package has this feature or not.</p> <p>Then if it did not have hot-reloading option, you can run your python app using <a href="https://github.com...
python
1
4,940
58,305,626
How to solve unexpected token { syntax error in JSON in javascript
<pre><code>"{ \"nodes\": { \"name\": \"Enron Announcements\", \"counts\": { \"name\": \"Enron Announcements\", \"role\": \"employee\", \"team_name\": \"Ufone\", \"oversees\": \"\", \"reports_to\": \"Zimin Lu,Lorna Brennan\", \"unique_threads\": \"366\" },...
<p>You're encoding JSON twice. In your code, remove everything after the <code># return G</code> line and replace it with:</p> <pre><code>graph_json = {'nodes': nodes, 'links': links} with open('temp.json','w') as fp: json.dump(graph_json , fp, indent=2) </code></pre> <p>If you need to remove <code>nan</code>...
javascript|python|json
1
4,941
33,958,133
Calculating Catalan Numbers
<p>I am trying to use this code to calculate the Catalan Number in Python, but it just does not work. How can I fix it?</p> <p>Here is the code I have:</p> <pre><code>def catalan_rec(n): if n == 0: return 1 else: b = 0 for i in range (n): b += sum((catalan_rec(i))*(catalan_...
<p>The problem is that you are summing, you should actually multiply. From <a href="https://en.wikipedia.org/wiki/Catalan_number" rel="nofollow noreferrer">Wikipedia</a> the definition is:</p> <p><a href="https://i.stack.imgur.com/tEjeU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tEjeU.png" alt=...
python|catalan
5
4,942
47,005,119
Accessing img from Flask
<p>I am developing an app that needs to generate a static image from Google Maps, process it and then reupload it.</p> <p>I save it to a variable:</p> <pre><code>var img = document.createElement('div'); document.body.appendChild(img) img.innerHTML = "&lt;img src='https://maps.googleapis.com/maps/api/staticmap...
<p>I am showing a way to add alternative text for your image using AJAX.</p> <p><code>application.py</code></p> <pre><code>from flask import Flask, render_template, request, url_for, redirect app = Flask(__name__) @app.route('/show_map_result', methods=['GET','POST']) def show_map_result(): if request.method == &q...
python|html|flask
0
4,943
61,608,010
Pytorch C++ (libtorch) outputs different results if I change shape
<p>So I'm learning Neural networks right now and I noticed something really really strange in my network. I have an input layer created like this</p> <pre><code>convN1 = register_module("convN1", torch::nn::Conv2d(torch::nn::Conv2dOptions(4, 256, 3).padding(1))); </code></pre> <p>and an output layer that is a tanh fu...
<p>THANK YOU @MichaelJungo turns out you were right in that one of my BatchNorm2d wasn't being set to eval mode. I was unclear how registering modules worked in the beginning (still am to an extent) so I overloaded the ::train() function to manually set all my modules to the necessary mode.</p> <p>In it I forgot to se...
c++|neural-network|pytorch|reshape|libtorch
0
4,944
27,814,743
How to read CSV file with of data frame with row names in Pandas
<p>I have a CSV file (<code>tmp.csv</code>) that looks like this:</p> <pre><code> x y z bar 0.55 0.55 0.0 foo 0.3 0.4 0.1 qux 0.0 0.3 5.55 </code></pre> <p>It was created with Pandas this way:</p> <pre><code> In [103]: df_dummy Out[103]: x ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_table.html"><code>index_col</code></a> parameter:</p> <pre><code>&gt;&gt;&gt; pd.io.parsers.read_csv("tmp.csv",sep="\t",index_col=0) x y z bar 0.55 0.55 0.00 foo 0.30 0.40 0.10 qux 0.00 0.30 5....
python|pandas
21
4,945
27,771,007
How to refresh if statement in Python Service
<p>Ok, so I made a python service that gets the current time and checks that against all the files in the directory. If a file in that directory has the same time as the current time, it should read that file and follow the command inside. For example: If the current time is 7:30, then if it finds a file in the 'Time' ...
<ol> <li>First of all, add </li> </ol> <blockquote> <p>sleep(5)</p> </blockquote> <p>command at the end of the loop (just before the continue statement) so that the service won't eat up your CPU in a restless loop :)</p> <ol start="2"> <li>You load the list of the protocol files just upon the service startup. are ...
python|windows|service
1
4,946
65,763,849
Unable To Format String - Python
<p>I'm unable to format this string, why is this?</p> <pre><code>def poem_description(publishing_date, author, title, original_work): poem_desc = &quot;The poem {title} by {author} was originally published in {original_work} in {publishing_date}.&quot;.format(publishing_date, author, title, original_work) return po...
<p>The curly brackets should be empty <code>{}</code>. You have typed variables in-between the curly brackets. Just remove them and you are good to go.</p> <pre><code>def poem_description(publishing_date, author, title, original_work): poem_desc = &quot;The poem {} by {} was originally published in {} in {}.&quot;.fo...
python|format
0
4,947
43,310,740
how to set up an Inherited MethodView in Flask to do CRUD operations on sqlalchemy models
<p>In order to avoid writing api methodviews for my models. i wish to create a more elegant inherited way of doing this. </p> <pre><code>class ModelCrudAPI(MethodView): def __init__(self, model): self.model = model def get(self): store_id = request.args.get("store_id", None, int) waiter...
<p><a href="http://flask.pocoo.org/docs/0.12/api/#flask.views.View.as_view" rel="nofollow noreferrer"><code>as_view</code></a> is a <em><code>classmethod</code></em>, and it forwards arguments provided to it to the class' constructor. So all you have to do is pass your model as the <em>second</em> argument to <code>as...
python|inheritance|flask|sqlalchemy|crud
3
4,948
43,451,948
Python mysql update with no subquery results in subquery error
<p>I have the following code</p> <pre><code>conn = MySQLdb.connect(server, user, password, database, autocommit=True, charset='utf8') for e in list_to_updpate: nid = e[0] vid = e[1] text = e[2] delta = e[3] deleted = e[4] langcode = e[5] to_update = e[6] ...
<p>Found the answer:</p> <p>It turns out that in order to match the LONGTEXT of the mysql db one should use io.String() object to pass the text. Otherwise it does not behave as expected. Mostly you can expect that a simple string would be mapped to varchar which should be at a max length. Be careful, since a varchar c...
python|mysql|string|subquery|longtext
1
4,949
43,387,133
How to display concatenated string on same
<p>Using following code I want to take two strings, concat them and display them on same line using <code>sys.stdin.readline()</code> for input and <code>sys.stdout.write()</code> for output. </p> <pre><code>import sys str1 = sys.stdin.readline() str2 = sys.stdin.readline() str3 = str1 + str2 sys.stdout.write(str...
<p>The <code>readline</code> method returns a string <em>that includes the line terminator</em>. One easy way to get rid of that would be to use the retruned string minus its last character:</p> <pre><code>str1 = sys.stdin.readline()[:-1] </code></pre> <p>Another would be to use the string's <code>rstrip</code> metho...
python|sys
2
4,950
37,042,748
How to create a Rotation Matrix in Tensorflow
<p>I want to create a rotation matrix in tensorflow where all parts of it are tensors.</p> <p>What I have:</p> <pre><code>def rotate(tf, points, theta): rotation_matrix = [[tf.cos(theta), -tf.sin(theta)], [tf.sin(theta), tf.cos(theta)]] return tf.matmul(points, rotation_matrix) </code><...
<p>with two operations:</p> <pre><code>def rotate(tf, points, theta): rotation_matrix = tf.pack([tf.cos(theta), -tf.sin(theta), tf.sin(theta), tf.cos(theta)]) rotation_matrix = tf.reshape(rotation_matrix, (2,2)) r...
python|tensorflow
10
4,951
48,651,699
How to sum panda column by unique index, but then reset the sum?
<p>New to Python. I have a pandas DataFrame as follows:</p> <pre><code>User_ID Clicks 23 2 19 3 19 5 22 1 98 8 19 1 19 3 </code></pre> <p>I want to sum the clicks for each User_ID but I want the sum to reset when the User_ID shows up again with a new row, lik...
<p>By using <code>diff</code> and <code>cumsum</code> create the group key , then we using <code>agg</code></p> <pre><code>df.groupby(df['User_ID'].diff().ne(0).cumsum()).agg({'User_ID':'first','Clicks':'sum'}) Out[1176]: User_ID Clicks User_ID 1 23 2 2 19 ...
python|python-3.x|pandas|sum|pandas-groupby
2
4,952
48,483,505
can't install numpy package in pycharm with latest pycharm and python 2.7
<p>I installed Python 2.7, Pycharm 2017.3 and in pycharm in </p> <pre><code>settings &gt; project interpreter &gt; add package </code></pre> <p>I searched for numpy and installed the package but I get this error:</p> <p><img src="https://i.stack.imgur.com/ToCLt.png" alt="error"></p> <pre><code>Error occured: _c...
<p>I suppose that you are trying to install numpy on windows. <br> On windows, install this package could be quite complicated, so my suggestion is to use an unofficial installer for Numpy.</p> <p><a href="https://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow noreferrer">Here</a> you can find the link with all un...
python|python-2.7|numpy|installation|pycharm
0
4,953
19,910,280
Stuck in an Exception loop
<p>I am parsing through the HTML returned from a list of links. When I reach a certain point in each HTML document I raise an Exception.</p> <pre><code>import urllib2, time, from HTMLParser import HTMLParser class MyHTMLParser2(HTMLParser): def handle_starttag(self, tag, attrs): if somethings: ...
<p>No, your diagnosis is not correct, there is not infinite exception loop here. Each URL is an entirely separate exception.</p> <p>The <code>cntr</code> variable won't update whenever you have an exception, perhaps that is giving you the <em>impression</em> that you end up in a exception loop. Either move the <code>c...
python|html|parsing
2
4,954
20,220,698
How to vectorize multiple levels of recursion?
<p>I am a noobie to python and numpy (and programming in general). I am trying to speed up my code as much as possible. The math involves several summations over multiple axes of a few arrays. I've attained one level of vectorization, but I can't seem to get any deeper than that and have to resort to for loops (I belie...
<p>You can use <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><em>broadcasting</em></a> to make 2d arrays from your 1d index vectors. I haven't tested these yet, but they should work:</p> <p>If you reshape the <code>N</code> to be a column vector, then <code>B1</code> will retu...
python|recursion|numpy|vectorization
2
4,955
67,054,727
Python List Comprehenion Get JSON Values
<p>I have a JSON like:</p> <pre class="lang-py prettyprint-override"><code>data = [ {&quot;word&quot;: &quot;Hi&quot;, &quot;lang&quot;: &quot;en&quot;}, {&quot;word&quot;: &quot;Bonjour&quot;, &quot;lang&quot;: &quot;fr&quot;}, ... ] </code></pre> <p>I want to execute a function (named <code>db.insertIntoS...
<p>You can use the built-in <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow noreferrer">zip</a> function. For example:</p> <pre><code>&gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; b = ['a', 'b', 'c'] &gt;&gt;&gt; c = [(i, j) for i, j in zip(a, b)] &gt;&gt;&gt; c [(1, 'a'), (2, 'b'), (3, 'c')] </c...
python|json|list-comprehension
1
4,956
4,278,444
Exposing a file-like object from Cython
<p>I need to expose a file-like object from a C library that i'm wrapping with a Cython module. I want to reuse python's generic io code for stuff like buffering, readline(), etc.</p> <p>The new IO module seems to be just what i need, but actually using it from Cython seems to be non-trivial, I've tried several aproac...
<p>Would it be too inefficient to call <code>os.fdopen()</code> on the file descriptor number returned by the underlying library, and then to dispatch normal Python method calls to the resulting file object in order to do your input and output? With most I/O, I would be surprised if you could see a difference with whet...
python|file-io|cython
1
4,957
69,475,873
why Django filter giving me this error 'QuerySet' object has no attribute 'user_id'?
<p>When I am using this queryset I am not getting any error and it's returning the user id</p> <pre><code>UserProfile.objects.get(forget_password_token=forget_password_token) print(user.user_id) &gt;&gt;&gt;19 </code></pre> <p>But when I am using this queryset <code>UserProfile.objects.filter(forget_password_token=fo...
<p>With .get() the return the instance of the object found so you can check directly user_id. With .filter() the rturn is a query set object contain all instances of ogject found (you can compare it to a list of results with some différences as it's an object type Queryset) So if you Want to check user_id, you have fir...
python|python-3.x|django
3
4,958
69,852,530
Adding a calculated metric in multiindex pandas dataframe
<p>I have a <code>df</code>:</p> <pre><code>date category subcategory order_id product_id 2021-05-04 A aa 10 5 2021-06-04 A dd 10 2 2021-05-06 B aa ...
<p>Remove list after <code>groupby</code>, then add new column with division by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><code>DataFrame.assign</code></a> and last reshape with <code>unstack</code> - if necessary sorting pre datetimes:</p...
python|pandas|group-by
1
4,959
73,090,518
Django querysets using __lte
<p>Can I do something like this in django/python without hardcoding it?</p> <pre><code>def get_rating_average(self, type): return list(super().aggregate(Avg(type)).values())[0] def filter_rating_average_under(self, type): return super().filter(type__lte=self.get_rating_average(type=type))...
<p>Yes, you can use:</p> <pre><code>from django.db.models import Q def get_rating_average(self, type): return super().aggregate(result=Avg(type))['result'] def filter_rating_average_under(self, type): return super().filter( Q((<strong>f'{type}__lte'</strong>, self.get_rating_average(type=type))) )...
python|django|postgresql|django-models
1
4,960
56,008,477
django retrieve csrf token
<p>In my web application I need to retrieve csrf token for sending some data through xmlhttprequest but I'm getting an error at the server as " <strong>django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'str' object has no attribute 'get'...
<p>You need to return an <code>HttpResponse</code>. Try something like this:</p> <pre><code>def interfacePageSubmit(request): # . . . csrf1 = str(csrf(request)['csrf_token']) json_data = json.dumps(csrf1) return HttpResponse(json_data, content_type='json') </code></pre>
python|django
1
4,961
66,452,490
How to simplify this acronym generator?
<p>I wrote code for an acronym generator. I can only get it to work for up to ten words.</p> <p>I feel the code is unnecessarily repetitive. Is there a simpler way to do this? Can it work for a larger sets of words?</p> <p>I just started coding and I have no prior knowledge of programming so I might need detailed expla...
<p>Use a loop, a <a href="https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions" rel="nofollow noreferrer">generator expression</a> or a <a href="https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions" rel="nofollow noreferrer">comprehension...
python
-1
4,962
68,780,385
Resolve Unconverted Data Remains: Error without replace other file contents
<p>I am currently writing a script which sorts dates. I have a input file which is called <code>sample.txt</code> and an output file called <code>sample2.txt</code>. At the end the contents of the input file should be sorted and written to the output file. But when running my script I am running into the following erro...
<p>If your input file is always going to be formatted the way you showed it, that is in 2 columns, the easiest way to avoid the error would be to use <code>.strptime</code> to only convert the date column. In other words, split the line into the date text and rest:</p> <pre class="lang-py prettyprint-override"><code> w...
python|python-3.x|sorting|datetime|strptime
1
4,963
67,529,037
Have a print method in a print statement in python
<p>I have the following piece of code in Python which tries to put a function that prints something in a print statement.</p> <pre><code>def my_print(num: int) -&gt; None: for i in range(num): print(i, end=' ') if __name__ == '__main__': print('When num is 5 :', my_print(5)) </code></pre> <p>I expect t...
<p>Try this:</p> <pre><code>def my_print(num: int) -&gt; None: for i in range(num): print(i, end=' ') if __name__ == '__main__': print('When num is 5 :', end=&quot; &quot;) my_print(5) </code></pre> <p>The <code>None</code> was printing because your <code>my_print()</code> function would return a N...
python|printing
1
4,964
67,497,271
Creating new dataframe column using string filter of other column
<p>Below is the dataframe with column name 'Address'. I want to create a separate column 'City' with specific string using filter from Address column.</p> <pre><code>df1 Serial_No Address 1 India Gate Delhi 2 Delhi Redcross Hospital 3 Tolleyganj Bus Stand Kolkata 4 Kolkata Howrah 5...
<p>Let us try <code>str.extract</code></p> <pre><code>df['new'] = df.Address.str.extract(('(Delhi|Kolkata)'))[0] </code></pre>
python|pandas|dataframe|if-statement|append
2
4,965
71,171,734
Keep getting Type_Error in Python when trying to solve with formula containing >
<p>I need to print all the values from XML data that are more than the average. I figured out how to solve for the average but I'm having trouble printing all the values that are more than the average. This is the code, the formula is in the more_than_average function</p> <pre><code>import xml.etree.cElementTree as ET ...
<p>average is a <a href="https://docs.python.org/3/library/stdtypes.html#set" rel="nofollow noreferrer">set()</a></p> <p>By surrounding your value with brackets, you are creating a set containing one value. Python cannot compare float and set, that's why it throws an error.</p> <pre><code>average = round(value / len(pr...
python|xml|database|function|import
1
4,966
66,048,650
Selenium selecting from mutilple dropdown with same class - problem python
<p>I'm having 3 drop downs on same div and i want to select the first parameter of each class. It's look like this: <a href="https://i.stack.imgur.com/vBkwt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vBkwt.png" alt="enter image description here" /></a></p> <p>I Wrote this code:</p> <pre><code>fi...
<p><code>driver.find_element_by_class_name(&quot;list&quot;)</code> will always select the first list of drop-down options</p> <p>You need to use <code>test</code> as context node:</p> <pre><code>fields= driver.find_elements_by_class_name(&quot;masked-select-inner&quot;) for test in fields: test.click() test.fi...
python|selenium|selenium-webdriver
0
4,967
69,171,881
QtableView sortingEnabled and column selection
<p>I use a QtableView in PySide 6, populated by QSortFilterProxyModel, and setSortingEnabled is true, so I can sort by column. But by doing this, I'm no more able to select the column by clicking the header.</p> <p>The idea is to be able to sort the column by clicking on the arrow icon and to select the column by clic...
<p>When the sortingEnabled property is enabled, the sectionPressed signal of the selectColumn slot is disconnected, so a possible solution is to reconnect it:</p> <pre class="lang-py prettyprint-override"><code>from PySide6.QtCore import QSortFilterProxyModel from PySide6.QtGui import QStandardItem, QStandardItemModel ...
python|select|qtableview|qsortfilterproxymodel|pyside6
1
4,968
58,752,540
How to access the contents of an excel file stored in my model - django
<p>I am developing an app in Django. I have a file model (let's say <code>my_file_model</code>) like this:</p> <pre><code>class my_file_model(models.Model): file = models.FileField(upload_to='myDirectory/', blank=False, null=False) </code></pre> <p>in which are stored excel sheets like this:</p> <p><a href="http...
<p>SOLVED:</p> <pre><code>def pour_entire__my_file_model(): import pandas as pd from .models import my_file_model, output_model all_files = my_file_model.objects.all() for file_element in all_files: excel_sheet = pd.read_excel(file_element.My_file_model) var_col_A = excel_sheet.Colu...
python|django|excel|pandas|file
0
4,969
59,487,175
Can't install mist or pycrypto on python 3.6
<p>Whenever I try to run <strong>pip install mist</strong>, it shows me this error.</p> <blockquote> <p>ERROR: Failed building wheel for pycrypto<br> Running setup.py clean for pycrypto Failed to build pycrypto Installing collected packages: pycrypto, ansible, mist Running setup.py install for pycrypto ....
<h2>TL;DR</h2> <p>Possible duplication of <a href="https://stackoverflow.com/questions/27630793/error-installing-pycrypto-on-mac-10-9-5">this</a> and <a href="https://stackoverflow.com/questions/8102292/problems-installing-pycrypto-on-osx/10686297">this</a>.</p> <h2>Full Read</h2> <p>I know this is probably solved by <...
python|python-3.x|pycrypto
0
4,970
58,459,217
Merge and Print Distinct Dictionaries
<p>I'm new to Python and I'm learning about dictionaries and I'd like to clarify something.</p> <p>Let's say I have two dicts: <code>d1 = {'id1' : '1', 'id2' : '2', 'id3' : '3', 'id4' : '4'}</code> and <code>d2 = {'fruit1': 'Apple', 'fruit2': 'Banana', 'fruit3': 'Strawberry', 'fruit4': 'Kiwi'}</code>. I'd like to crea...
<h2>Use <code>dict</code> and <code>zip</code>:</h2> <ul> <li>This will work as long as both <code>dicts</code> are aligned <ul> <li>Modern python <code>dict</code> order is <strong>guaranteed</strong> to be insertion order as of v3.7, but should also be the case for v3.6.</li> </ul></li> <li>The <code>values</code> ...
python|dictionary
1
4,971
57,033,104
Return all instances of a class that meet a criterion
<p>I'm completely new to Python so I may not be asking this in the right way and I have tried to find an answer (unsuccessfully, obviously).</p> <p>I am trying to set up a class and then to find all instances of the class that meet a certain criterion. I don't know if a class is the right way to go about this so open ...
<p>You would typically have your instances in some sort of collection like a list rather than individual variables. You could then filter your list or use a list comprehension to get the elements in the list you want. Here's an example with a list comprehension:</p> <pre><code>class Employee: def __init__(self, na...
python
4
4,972
54,344,882
combine asyncio and tornado
<p>Given that in version 5 of Tornado <code>tornado.ioloop.IOLoop.current()</code> is asyncio event loop when available - how does one go about ensuring that an aiohttp web-scraping script called from a handler uses the same event loop?</p> <p>Are there any examples around of such a setup?</p> <p>Thanks</p>
<p>It should just work by default. Here's a simple example:</p> <pre><code>from tornado.ioloop import IOLoop from tornado.web import RequestHandler, Application import aiohttp class MyHandler(RequestHandler): async def get(self): async with aiohttp.ClientSession() as session: async with sessio...
tornado|python-asyncio|aiohttp
2
4,973
54,507,426
How to loop over multiple groups while holding one value constant per group?
<p>I am trying to automate a <code>for loop</code> calculation within 34 different groups. I have a dataset which contains X and Y points for 400 districts located in 34 provinces. For each province, I want to calculate the distance from that province's district capital to each of the province's districts.</p> <p>Then,...
<p>Without seeing the structure of your data frame, it is a bit tough to give detail. But, what you have described is a nested loop operation. in pseudo-code you:</p> <pre><code>Loop over all of the provinces: identify the capital somehow Loop over all of the districts: calculate the distance (capital, distr...
python|for-loop
1
4,974
51,246,591
Using local variables in one function in a main function
<p>I'm completely new to programming and python as a whole but I have recently joined a class. Currently I am trying to make a program which prompts the user for an input of the coordinates of the center of an object on the screen.</p> <p>The program will then take the X and Y coordinates of the item and randomize the...
<p>Welcome to SO (and to programming)!</p> <p>You are almost there with this, the thing you are missing is saving the return values of the <code>randomizex(), randomizey(), randomizedelay()</code> functions to variables, so they can be used within main. Even though you name the variables within their respective functi...
python-3.x
1
4,975
73,134,729
Using Python, how to extract text and images from PDF + color strings and numbers from the output txt file
<p>Using Python, I would like to</p> <ol> <li>extract text from a PDF into a txt file (done)</li> <li>color all numbers and specific strings of the txt file like this example (<a href="https://tex.stackexchange.com/questions/521383/how-to-highlight-numbers-only-outside-a-string-in-lstlisting">https://tex.stackexchange....
<p>You can do:</p> <pre class="lang-py prettyprint-override"><code>import fitz doc = fitz.open(&quot;AR_Finland_2021.pdf&quot;) for page in doc: for img_tuple in page.get_images(): img_dict = doc.extract_image(img_tuple[0]) img_bytes = img_dict['image'] # Do whatever you want with it </cod...
python|image|pdf|extract|txt
0
4,976
56,000,098
About locally weighted linear regression problem
<p>One problem with linear regression is that it tends to underfit the data and one way to solve this problem is a technique known as locally weighted linear regression. I have read about this technique in <a href="http://cs229.stanford.edu/notes/cs229-notes1.pdf" rel="nofollow noreferrer">CS229 Lecture notes by Andrew...
<p>In the loop, <code>i</code> is a list, e.g. <code>[1.0, 1.0]</code>. You need to decide what value to take from the list to multiply <code>slope*i</code>. For instance:</p> <pre><code>best_fit = [] for i in xArr: best_fit.append(slope*i[0]+y_intercept) </code></pre> <p>The first element in the list seems to al...
python|tensorflow|machine-learning
0
4,977
55,773,339
how to add multiple pdfs to be converted into excel?
<p>I have program which converts pdf to excel, Now i want add multiple inputs i.e. multiple pdfs to be converted one by one. </p> <p>my code is below:</p> <pre><code>from PIL import Image import io import pytesseract from wand.image import Image as wi import os import cv2 import pandas as pd import re import numpy as...
<p>Try the code below. This will loop through every PDF file in the folder directory you define. Be sure to update your file_path to be where your PDFs are saved, making sure you use double backslashs in place of single backslashes.</p> <pre><code>from PIL import Image import io import pytesseract from wand.image impo...
python|python-3.x|pdf
0
4,978
73,298,810
Group by the column in df python
<p>I have a simple df. It has two columns. I want to groupby the values based on column a. Here is a simple example: Any input would be greatly appreciated!</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame() df['a'] = [1, 2, 3, 4, 1, 2] df['b'] = [10, 20, 30,40, 50,60] </code></pre> <p>Desired ou...
<p>Here's a way to do what you want. First you want to group by column 'a'. Normally <code>groupby</code> is used to calculate group aggregation functions:</p> <pre><code>df.groupby('a')['b'].mean() </code></pre> <p>but in this case we want to keep the values of b associated with each a. You can use</p> <pre><code>[(a,...
python|dataframe
1
4,979
66,377,357
Python 3.8.2 / 2.7.9 cannot output UTF-8?
<p>I have a weird issue, I attempted all the suggested answers of this field but I'm probably missing something that should be very easy. I have the following code:</p> <pre><code>def parseinvalid(): newfile = open('outputBlueTooth.txt', 'r') print('Parsing Invalid') for line in newfile: splitted = line.split(&quo...
<p><code># -*- coding: UTF-8 -*-</code> only affects string literals in the code. It has nothing to do with any other strings in the code, namely strings read from files.</p> <p>The most likely issue here is that you don't provide <code>encoding</code> to <code>open</code>, which does a very bad job at choosing a defau...
python|python-3.x|python-2.7
0
4,980
66,693,540
Can't convert 'generator' object to str implicitly
<pre><code>for i in range(len(parsed_data)): c = [('.'.join(re.findall(&quot;\d+&quot;,str(parsed_data[i][j].split()[:5]))) for j in range(len(parsed_data[i])))] df_list.append(c) index.append(dates[k] + c[0]) </code></pre> <p>error:</p> <pre><code>TypeError Traceback (most recent call l...
<p>You have an extra pair of parentheses around your list comprehension which makes it a one element list containing a generator instead of a list with the actual data.</p> <p>replace:</p> <pre><code>[( '.'join... )] </code></pre> <p>with:</p> <pre><code>[ '.'join... ] # i.e. without the extra parentheses </code></pre>
python|iterator
0
4,981
64,070,488
Serialize Dictionary Object Where Keys Are Different
<p>I have a dictionary object which has the days of the week as keys. Please can someone advise if there is a way to serialize this object using a Django Serializer.</p> <p>The example dictionary output looks like this:</p> <pre><code>[{'mon': {'AM': False, 'PM': False}}, {'tue': {'AM': True, 'PM': False}}, {'wed': {'A...
<p>I'm doing it this way:</p> <p>First I create classes to hold instance of week with the days.</p> <pre><code>class Week(object): def __init__(self): self.mon = None self.tue = None self.wed = None self.thu = None self.fri = None self.sat = None self.sun = No...
python|django|django-rest-framework|django-serializer
0
4,982
10,805,356
Change color weight of raw image file
<p>I am working on a telescope project and we are testing the CCD. Whenever we take pictures things are slightly pink-tinted and we need true color to correctly image galactic objects. I am planning on writing a small program in python or java to change the color weights but how can I access the weight of the color i...
<p>Typical white-balance issues are caused by differing proportions of red, green, and blue in the makeup of the light illuminating a scene, or differences in the sensitivities of the sensors to those colors. These errors are generally linear, so you correct for them by multiplying by the inverse of the error.</p> <p>...
java|python|image-processing|rgb
3
4,983
10,750,001
for loop performance in huge list or dictionary
<p>I am making a research project on search engines, and i am having problems with a performance of the for loop. I have the following problem:</p> <pre><code>for value in hash_array.keys(): cell= db_conn.use_client().hql_query(db_conn.use_namespace(),'SELECT doc_text FROM SE_doc_text WHERE ROW=\"'+ ...
<p>I've never used Hypertable but simply reading the <a href="http://hypertable.com/documentation/reference_manual/thrift_api/" rel="nofollow">documentation</a> suggest the <code>SCAN_AND_FILTER_ROWS</code> clause may be a problem:</p> <blockquote> <p>This is an explicit optimization for the case where you're queryi...
python|performance|hypertable
2
4,984
5,410,470
How to read complete IP frames from TCP socket in Python?
<p>I need to read a complete (raw) IP frame from a TCP stream socket using Python. Essentially I want an unmodified frame just as if it came off the physical line, including all the header information.</p> <p>I have been looking into raw sockets in Python but I have ran into some issues. I don't need to form my own pa...
<p>If you don't mind using <a href="http://www.secdev.org/projects/scapy/" rel="nofollow">Scapy</a>, which is not part of the standard library, and super speed isn't a requirement, you can use its <code>sniff</code> function. It takes a callback. Something like:</p> <pre><code>pkts_rxd = [] def process_and_send(pkt): ...
python|linux|sockets|raw-sockets
3
4,985
61,715,924
Pass multiple parameters in Django
<pre><code>class Article(models.Model): Title = models.CharField(max_length = 255) writing = models.TextField() category = models.CharField(max_length = 225) published = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug =...
<p>You can a <a href="https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField" rel="nofollow noreferrer"><strong><code>ManyToManyField</code></strong></a> to link your post to multiple categories, for example:</p> <pre><code>class Category(models.Model): name = models.CharField(ma...
python|django|django-models|django-views|web-site-project
0
4,986
71,163,461
Saving optuna study.pkl in Google Colab
<p>I'm tuning my ML model on Google Colab but I don't know how to save that model to pkl.</p> <pre><code>import time import optuna study_name = &quot;/gdrive/MyDrive/Colab Notebooks/test/params_{}&quot;.format(time.strftime(&quot;%Y%m%d-%H%M%S&quot;)) study=optuna.create_study(study_name, direction='maximize') </code>...
<p>You mean save the study ?</p> <p><a href="https://optuna.readthedocs.io/en/stable/faq.html#how-can-i-save-and-resume-studies" rel="nofollow noreferrer">https://optuna.readthedocs.io/en/stable/faq.html#how-can-i-save-and-resume-studies</a></p> <p>I use this :</p> <pre><code>install joblib import joblib # Let's say I...
python-3.x|google-colaboratory|optuna
0
4,987
71,162,820
Trouble checking if the value in a list is already been changed from the original and shouldn't be changed again
<p>I am making a game where it generates an item and randomly places it in the displayed list. When I run the code, it occasionally places the random item over a cell that already had one random item placed in that cell. How can I fix my code so that it does not allow a cell to be modified if it already had been? I am ...
<p>How many items do you want to place? You could construct an iterable of all possible positions in the grid and then find n different, but random positions using</p> <pre class="lang-py prettyprint-override"><code>import itertools import random row = 10 col = 10 N = 5 positions = sorted(itertools.product(range(row), ...
python
0
4,988
71,150,074
How do I remove items from a list that meet a criteria
<p>I am attempting to identify if an item is even and then removing them from any list and printing the new list</p> <pre class="lang-py prettyprint-override"><code>def remove_evens(my_list): if item in my_list 0 % 2 == 0: # how do I remove the specified items? return list </code></pre>
<pre><code>def remove_evens(my_list): for item in my_list: if item %2 == 0: my_list.remove(item) return my_list my_list = [1,2,3,4,5,6] remove_evens(my_list) print(my_list) </code></pre>
python|list
1
4,989
71,226,790
python tkinter: Calling a objects method on button click does not work
<p>here is my sample code:</p> <pre><code>from time import sleep import tkinter as tk import threading class Action: counter = 0 def do_something(self): while True: print('Looping') sleep(5) action = Action() root = tk.Tk() button = tk.Button(root, text='pressme harder', ...
<p>You shouldn't try to start a thread directly in the button command. I suggest you create another function that launches the thread.</p> <pre><code>from time import sleep import tkinter as tk import threading class Action: counter = 0 def do_something(self): while True: print('Looping') ...
python|multithreading|tkinter|python-multithreading
2
4,990
70,722,460
Python parallel processing sudden shutdown
<p>While running some parallelized code in python, my dual boot (Windows 11 / Ubuntu 20.04.3 LTS) laptop suddenly shut down on multiple occasions. Afterwards, when running in Windows, my laptop has also randomly shut down and once booting Ubuntu, the screen started glitching a lot. I've been running the code on Ubuntu....
<p>I managed to figure out what it was that caused the random shutdowns. On the Windows side of my dual-boot system, HP Sure Run was running (which, it says, is 'hardware enforced'). I think that means that when I'm running Ubuntu and doing something HP Sure Run doesn't like, it manages to interfere and shutdown the sy...
python|windows|ubuntu|parallel-processing
1
4,991
56,859,205
How to deal with TypeError: must be str, not float
<p>I am trying to run this</p> <pre><code> pa['pattern'] = pa['AccessType'] + pa.groupby(['AccessedBy'])['AccessType'].shift(1) </code></pre> <p>but it's throwing </p> <pre><code> TypeError: must be str, not float </code></pre> <p>But </p> <pre><code>AccessedBy object AccessType o...
<p>I think you're data might have changed:</p> <pre><code>df = pd.DataFrame({'Group':['X']*4+['Z']*4, 'AccessType':[*'ABCDEFGH']}) df['AccessType'] + df.groupby('Group')['AccessType'].shift(1) </code></pre> <p>Runs fine:</p> <pre><code>0 NaN 1 BA 2 CB 3 DC 4 NaN 5 FE 6 GF 7 HG Name: Ac...
python|python-3.x|pandas
1
4,992
56,583,080
how to implement Grad-CAM on your own network?
<p>I want to implement Grad-CAM on my own network, should I save my model and load it, then treat my saved model like VGG-16, then do similar operations?</p> <p>I tried to search on the internet, and I found that all methods are based on famous models, not their owns.</p> <p>So I wonder, maybe I just need to treat my...
<p>Hi i have one solution in pytorch</p> <pre><code>import torch import torch.nn as nn from torch.utils import data from torchvision import transforms from torchvision import datasets import matplotlib.pyplot as plt import numpy as np # use the ImageNet transformation transform = transforms.Compose([transforms.Resize(...
python-3.x|pytorch
0
4,993
60,835,093
Destroy function not destroying a frame efficiently after the first iteration in Tkinter Python
<p>I have built a code that saves the calculated data at every iteration in a for loop and the results are stored in 3 different csv files. These saved results are read in another python code that displays the results using GUI tkinter on a window containing three different frames. These three frames are updated every ...
<p>I found a way that solves this problem. However, a new problem arises .. </p> <p>Basically, I was defining frame1 inside the MVs function. I removed that and kept it only at the beginning. The same approach was done for frame2 and frame3. This way, when I press the close button, the respective frame is immediately ...
python|user-interface|tkinter|destroy
0
4,994
61,178,653
Visualization of missing records in DataFrame
<p>Visualization of missing records in DataFrame</p> <p>I have a lot of missing dataframe records.</p> <pre><code>df.isnull().sum() </code></pre> <p>The problem is that these deficiencies are connected and I don't know how to see them. Because I do not want to mess up so as to spoil data. What are your ways to see t...
<p>You ca use such plot of concentration</p> <pre><code>import seaborn as sns sns.heatmap(df.isnull(),yticklabels=False,cbar=False,cmap='viridis') </code></pre> <p><a href="https://i.stack.imgur.com/IqqQT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IqqQT.png" alt="enter image description here"...
pandas
1
4,995
66,257,600
How to multiply a sparse matrix by a sparse matrix element-wise in pytorch
<p>In pytorch, I can achieve two sparse matrixes multiplication by first turning them into a dense form</p> <pre><code>adjdense = torch.sparse.FloatTensor(indextmp, valuetmp, torch.Size([num_nodes,num_nodes])).to_dense() mask_dense = torch.sparse.FloatTensor(edge_index, edge_mask_list[k], torch.Size([num_nodes,num_node...
<p>Thanks for sim. I have known how to do it.</p> <p>adjsparse = torch.sparse.FloatTensor(indextmp, valuetmp, torch.Size([num_nodes,num_nodes])) masksparse = torch.sparse.FloatTensor(edge_index, edge_mask_list[k],torch.Size([num_nodes,num_nodes]))</p> <p>result = adjsparse.mul(masksparse)</p>
python|sparse-matrix|elementwise-operations
0
4,996
72,506,356
How to save dataframe value in excel/csv
<p>i am trying to save outlook email body content to dataframe then to csv/excel, we usually get prices from vendor for different indices in tabular format, i tried using Body_content = message.HTMLBody but didnt work as intented.</p> <p>Thus i am ok with using Body_content = message.Body and print (df.To_string()). No...
<p>You can export the <code>dataFrame</code> to excel</p> <p><code>df.to_excel(&quot;output.xlsx&quot;, index=False) </code></p> <p>or CSV -</p> <p><code>df.to_excel(&quot;output.csv&quot;, index=False) </code></p>
python|pandas|dataframe|outlook|win32com
2
4,997
72,722,415
Qtimer event not executing
<p>I'm trying my first play with Python timers for use with QT GUI's, but this simple example I have created is not triggering the 'update_time' event. 'start' is printed ok as expected.</p> <pre><code>from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import QTimer, QTime def change_time(): timer =...
<p>Alternatively to what @musicamante suggested you could also define the timer outside of the function so that if you ever decide to stop the timer, future calls to <code>change_time</code> can reuse the same timer and avoid creating a new one.</p> <pre><code>from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCor...
python|qt|pyqt5
1
4,998
68,323,680
Counting sequences of numbers in an array?
<p>I have the following dataframe for a year of data:</p> <pre><code> lat lon date month ssta 90th 10th threshold year dayofyear 21680 30.375 273.875 1982-01-01 1 0.995117 1.566498 -1.620501 0 1982 1 21681 30.375 273.875 1982-01-02 1 ...
<p>If I understand you correctly you're just looking for neighboring values that are more than 5 apart by value?! If so you can just shift the array by 1 and compare like so</p> <pre><code>arr[np.argwhere(np.abs(arr-np.roll(arr,-1)) &gt;= 5)] </code></pre> <p>This almost gives your desired output just as a 3,1 array. I...
python|pandas|numpy
0
4,999
68,058,021
Why this code doesn't print a circle in python using turtle library?
<p>I have recently started using the <code>turtle</code> library but I don't understand why it doesn't print circles when I execute the following code:</p> <pre class="lang-py prettyprint-override"><code>from turtle import * color('green') speed(11) for i in range(60): circle(i * 1.5) right(4) hideturtle...
<p>If we treat this as simply an indentation problem, then the following whitespace cleanup:</p> <pre><code>from turtle import * color('green') speed('fastest') for i in range(60): circle(i * 1.5) right(4) hideturtle() done() </code></pre> <p>runs fine and prints circles:</p> <p><a href="https://i.stack.imgu...
python|turtle-graphics|python-turtle
0