Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
9,600
64,047,807
H2OFrame column to array: quickest way?
<p>Suppose I have an H2OFrame called <code>df</code>. What is the quickest way to get the values of column <code>x</code> from said frame as a <code>numpy</code> array?</p> <p>One could do</p> <p><code>x_array = df['x'].as_data_frame()['x'].values</code></p> <p>But that seems unnecessarily verbose. Especially passing v...
<p>here is another way. However, I'm not sure it's faster. I'm using the h2o.as_list() function to convert a column to a list and then I use the np.array() function to convert the list to an array.</p> <pre><code>import h2o import numpy as np h2o.init() # Using sample dataset from H2O train = h2o.import_file(&quot;ht...
python|h2o
2
9,601
53,272,184
"TypeError: 'int' object is not iterable" When making a small words list
<p>I need to make a function using iteration to make a list of all words that are shorter than 3 letters. I keep getting some int error.</p> <pre><code>def shortWords(aList): total = 0 aList = 0 for index in aList: index = str(index) if len(aList([index])) &lt;= 3: total = aList....
<p>You got <code>TypeError: 'int' object is not iterable</code> because you have declared <code>aList = 0</code> in your function, which overwrites the parameter that is passed into it.</p> <p>It seems there is some confusion on how python loops work. When iterating through a list, it will return the value and not the...
python
1
9,602
71,877,881
Reorder level in a multiindex from a pandas pivot_table?
<p>This question was hard to word, sorry for the bad title. I have a multiindex dataframe created from a pivot_table that I have transposed, the indexes are now the columns. I already know how to reorder the outer index by just doing:</p> <pre><code>df[['Sunday', 'Monday', 'Tuesday', ...]] </code></pre> <p>As you can ...
<p>You can use <code>CategoricalDtype</code>. And it's best if you change the column type before the pivot:</p> <pre class="lang-py prettyprint-override"><code># Some sample data import string error = list(string.ascii_uppercase[:10]) weekday = [&quot;Sunday&quot;, &quot;Monday&quot;, &quot;Tuesday&quot;, &quot;Wednesd...
python|pandas|pivot-table|multi-index
2
9,603
71,926,260
Creating grouped heatmaps with fixed cell width in plotly
<p>I would like to plot several heatmaps on one plotly figure, where the columns of all heatmaps should have the same width (within and across heatmaps). My first idea was to use <code>make_subplots</code> together with <code>go.Heatmap</code> but with this approach the width of each cell changes accordingly to how man...
<p>After much trial and error on my part, I think it would be easiest to add a title to the second example with the annotation feature.</p> <pre><code>import plotly.express as px z = df.pivot(columns=['source','variable'], index='variate', values='value') source_labels,variable_labels = z.columns.get_level_values(0), ...
python|plotly|heatmap
1
9,604
71,623,029
Can we write a loop or algorithm for compare elements of a list which includes tuples?
<pre><code>list2 = [(2, 4), (2, 6), (2, 8), (2, 12), (3, 6), (3, 12), (4, 8), (4, 12), (6, 12)] </code></pre> <p>Well. I have a list like this. And I need to make a new list that includes the second value of tuples which is the first value of it same, for every different first value of tuples. To make it clear, I give ...
<p>The <code>dict.setdefault</code> to group by the second values, by first, will solve that easily</p> <pre><code>list2 = [(2, 4), (2, 6), (2, 8), (2, 12), (3, 6), (3, 12), (4, 8), (4, 12), (6, 12)] result = {} for first, second in list2: result.setdefault(first, []).append(second) print(result) # {2: ...
python
6
9,605
5,533,048
Why isn't my pathtracing code working?
<p>I've been hacking together a pathtracer in pure Python, just for fun, and since my previous shading-thing wasn't too pretty (<a href="http://en.wikipedia.org/wiki/Lambert%27s_cosine_law" rel="nofollow noreferrer">Lambert's cosine law</a>), I'm trying to implement recursive pathtracing.</p> <p>My engine gives an abo...
<p>My first question is should <code>if test &gt; result:</code> be <code>if test &lt; result:</code>? You're looking for the closest hit, not the furthest.</p> <p>Second, why do you add <code>direction*0.00001</code> to the hit point here <code>n = Ray(ray.position(result) + direction * 0.00001, direction)</code>? Th...
python|raytracing
4
9,606
62,713,355
Find corresponding rows with frequent itemsets
<p>My dataset is an adjacency matrix comparable with customer buying information. An example toy dataset:</p> <pre><code>p = {'A': [0,1,0,1], 'B': [1,1,1,1], 'C': [0,0,1,1], 'D': [1,1,1,0]} df = pd.DataFrame(data=p) df </code></pre> <p>Now I am interested in the frequent itemset so I used an apriori fim:</p> <pre><code...
<p>It doesn't appear that there's a direct way to do this via <code>apriori</code>. However, one way would be as follows:</p> <pre><code>from mlxtend.frequent_patterns import apriori frequent_itemsets = apriori(df, min_support=0.1, use_colnames=True) # lists of columns where value is 1 per row cols = df.dot(df.columns...
python|apriori|mlxtend
1
9,607
67,339,360
Iam trying to install cocoapi but iam getting this error
<p>WARNING: Ignoring invalid distribution -ip (c:\users\sangay sherpa\appdata\local\programs\python\python37\lib\site-packages) WARNING: Error parsing requirements for tensorflow-gpu: [Errno 2] No such file or directory: 'c:\users\sangay sherpa\appdata\local\programs\python\python37\lib\site-packages\tensorflow_gpu-2...
<p>You can find some problems in your folder[c:\users\sangay sherpa\appdata\local\programs\python\python37\lib\site-packages],There have some error packet such as the [ip],this packet maybe become ~ip. like this packet_img <a href="https://i.stack.imgur.com/UQOZc.png" rel="nofollow noreferrer">enter image description h...
python-3.x|object|detection
0
9,608
67,542,578
Bytes encoding in cryptography module giving error
<p>I am using the <code>cryptography</code> module's <code>Fernet</code> for encoding.<br /> The Fernet technique converts the data to bytes using a key, and then we can convert the bytes back to a string using that same key.<br /> I want to convert the encoded bytes to a string and store that string. (It is important ...
<p>You should use <code>print()</code> to see what you have in variables after using <code>bytes</code> and `str()</p> <p>When you use</p> <pre><code> bytes('abc', 'utf-8') </code></pre> <p>then you get</p> <pre><code> b'abc' </code></pre> <p>and when you use</p> <pre><code> str(b'abc') </code></pre> <p>then you get</p...
python|string|cryptography|byte|python-cryptography
2
9,609
10,902,294
Image Not Uploading From Form
<p>I want to save and filter user’s objects in my django app. After inputting the below codes, the imagefield is not uploading any image to my database and it’s not returning any image in my template. </p> <p>Models</p> <pre><code>class Fin(models.Model): user=models.ForeignKey(User) title=models.CharField(ma...
<p>You're missing a number of things on the template and view layer. </p> <p>Read this: <a href="https://docs.djangoproject.com/en/1.3/topics/http/file-uploads/#basic-file-uploads" rel="nofollow">https://docs.djangoproject.com/en/1.3/topics/http/file-uploads/#basic-file-uploads</a></p>
python|django
2
9,610
56,785,243
How to send BluetoothRFCommSocket with Scapy?
<p>I set up a BluetoothRFCommSocket with this code:</p> <pre><code> from scapy.layers.bluetooth import * from scapy.all import * bt = BluetoothRFCommSocket('68:A0:3E:CC:24:06',2) </code></pre> <p>And the error is:</p> <pre><code> Traceback (most recent call last): File "test.py", line 3, in &lt;m...
<p>I also get this error.</p> <p>From scapy source code:</p> <pre><code>class BluetoothRFCommSocket(BluetoothL2CAPSocket): """read/write packets on a connected RFCOMM socket""" def __init__(self, bt_address, port=0): s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_RFC...
python|bluetooth|scapy|rfcomm
0
9,611
69,801,734
Ascii strings in Python
<p>I'm currently working on setting up a CTF-competition for my University. Where one of our challenges will utilize a Caesar Cipher to solve one of the basic flags. While creating the code that'll create our ciphered text I noticed that a quite common way of creating a Caesar cipher program is to utilize the string li...
<p>I think a lot of people just do it that way, because thats how you would do it in other programming languages.</p> <p>In python you can utilize a lot of build in functions. A clean solution (in my opinion) is doing it this way</p> <pre><code>def shift_cipher(text: str, shift: int) -&gt; str: &quot;&quot;&quot; ...
python|python-3.x|string
0
9,612
17,972,893
Django Nonrel Groups Issue
<p>Django Nonrel Groups Issue</p> <p>Django Nonrel branch version 1.4 of Django is being used. Groups from: <a href="https://github.com/django-nonrel/django-permission-backend-nonrel" rel="nofollow">https://github.com/django-nonrel/django-permission-backend-nonrel</a> </p> <p>The admin section works fine. I am able ...
<p>I believe user.groups is a List of keys to groups. I don't think that djangotoolbox or djangoappengine currently will generate a query for a list of keys. You can try updating djangotoolbox to handle this case, or more easily, you can issue a query outside the template for <code>Group.objects.filter(id__in=user.gr...
python|django|django-nonrel
0
9,613
17,838,168
Can I build an automatic class-factory that works on import?
<p>I have a class-factory F that generates classes. It takes no arguments other than a name. I'd like to be able to wrap this method and use it like this:</p> <pre><code>from myproject.myfactory.virtualmodule import Foo </code></pre> <p>"myfactory" is a real module in the project, but I want virtualmodule to be somet...
<p>You can stuff an arbitrary object into the <code>sys.modules</code> structure:</p> <pre><code>import sys class VirtualModule(object): def __init__(self, name): self.__name__ = name.rsplit('.', 1)[-1] self.__package__ = name self.__loader__ = None def __getattr__(self, name): ...
python
3
9,614
60,769,808
Pandas - Applying filter in groupby
<p>I am trying to perform a group by function in a Dataframe. I need two aggregations done, to find total count and find the count based on filtering of one column</p> <pre><code>product, count, type prod_a,100,1 prod_b,200,2 prod_c,23,3 prod_d,23,1 </code></pre> <p>I am trying to create a pivot of columns, <code>col...
<p>If need count by only one condition like <code>type==1</code> then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer"><code>GroupBy.agg</code></a> with <a href="https://pandas.pydata.org/docs/user_guide/groupby.html#named-aggregation...
python|pandas|pandas-groupby
3
9,615
61,125,218
Python - Calling a module function which uses globals() but it only pulls globals() from the module not the current python instance
<p>python version: 3.8.1</p> <p>platform = Windows 10 pro</p> <p>dev environment : visual studio code, jupyter notebook, command line</p> <p>I have function that I import from a personal module to find all the current Pandas - DataFrames in memory or the globals(). However I only get the globals() from the module. (...
<p>Sorry, it seems I did not your question carefully enough.</p> <p>For your problem I found a hint at the <a href="https://stackoverflow.com/a/1095621/5646962">this</a> question.</p> <p>It seems that the <code>inspect</code> module can do what you want:</p> <pre><code># my_module.py # import pandas as pd import in...
python|python-3.x|pandas|dataframe|global
0
9,616
69,217,678
Organizing JSON files while appending through Python (discord.py) input
<p>I'm currently making a bot on Discord.py right now, and one of the commands takes input that would be stored into a JSON file. One of the keys is a sort of ID associated for each object, and its format is basically a sort of alphanumeric code. A sample version of the JSON looks like this:</p> <pre><code>{ &quot;da...
<p>You can try sorting the list every time you append a new element i.e:</p> <pre class="lang-py prettyprint-override"><code>data.append(newelement) data.sort(key=lambda x: x['id']) </code></pre> <p>Which will sort the list 'data' <strong>inplace</strong></p>
python|json|discord.py|append
0
9,617
59,306,538
JavaScript MD5 differs from Python/Bash md5sum
<p>I have the following snippet</p> <pre><code> function runUpload( file ) { key_name = file.name if( file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/gif' || file.type === 'i...
<p>The only explanation is that encoding is different. Figure out encoding in JS (ISO-8859-1) to that in python (UTF-8). </p>
javascript|python|md5|md5sum
0
9,618
59,467,291
How to specify a specific github repo version in requirements.txt?
<p>I want to be able to install a specific version of a github repo. I followed the instructions given <a href="https://stackoverflow.com/questions/16584552/how-to-state-in-requirements-txt-a-direct-github-source">here</a> and my file <code>requirements.txt</code> looks as follows:</p> <pre><code>git://github.com/twoo...
<p>I solved the problem by adding the following argument to the <code>setup</code> method in `setup.py':</p> <pre><code>install_requires=['NBT@git+git://github.com/twoolie/NBT@f9e892'], </code></pre> <p>and using an empty <code>requirements.txt</code> file. With these setting the install of the specific version of th...
python|setup.py|requirements.txt
1
9,619
62,112,066
python: can't open file 'main.py': [Errno 2] No such file or directory - docker
<p>I'm seeing the above error when I try to run my docker image. Below are the screenshots of my docker file and the directory structure.</p> <p><a href="https://i.stack.imgur.com/7HWsb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7HWsb.png" alt="Dockerfile"></a></p> <p><a href="https://i.stack....
<p>As you have already specified the <code>WORKDIR</code> in the <code>Dockerfile</code>. Dont' copy your files to <code>/</code>. </p> <p>Change your command to </p> <pre><code>COPY . . # If you want to copy whole folder into container </code></pre> <p>and as well <code>CMD</code> command to </p> <pre><code>CMD ...
python|docker
2
9,620
58,998,827
Gradient computations in Tensorflow 2.0
<p>Here is my example from Tensorflow 2.0:</p> <pre><code>import tensorflow as tf w = tf.Variable([[1.0]]) with tf.GradientTape() as tape_1: loss_1 = w * w with tf.GradientTape() as tape_2: loss_2 = w * w * w grad_1 = tape_1.gradient(loss_1, w) grad_2 = tape_2.gradient(loss_2, w) print(grad_1) print(grad_2...
<p>The gradient results do not mean that. If you take your functions, f(w) = w<sup>2</sup> and g(w) = w<sup>3</sup>, their respective derivative functions with respect to w would be f'(w) = 2w and g'(w) = 3w<sup>2</sup>. What the gradient function gives you is the value of these functions for the current value of w. So...
tensorflow|derivative|gradienttape
1
9,621
58,714,805
Decoding text file using lists in Python
<p>I encoded this sentence:</p> <p>This is an amazing "abstract" AND this: is the end of this amazing abstract.</p> <p>to this:</p> <p>1 2 3 4 "5" 6 7: 2 8 9 10 7 4 5.</p> <p>The corresponding index table (as text file) is:</p> <pre><code>word,index This,1 is,2 an,3 amazing,4 abstract,5 AND,6 this,7 the,8 end,9 of...
<p>First of all, it's better to use dict and replace your code:</p> <pre><code>for line in content_index: fields = line.split(",") </code></pre> <p>to:</p> <pre><code>fields = {} for line in content_index: word, number = line.split(',') fields[number] = word </code></pre> <p>Then you can use regular exp...
python|list|encoding|decoding
1
9,622
31,498,784
Performance difference between filling existing numpy array and creating a new one
<p>In iterative algorithms, it is common to use large numpy arrays many times. Frequently the arrays need to be manually "reset" on each iteration. Is there a performance difference between filling an existing array (with nans or 0s) and creating a new array? If so, why?</p>
<p>The answer depends on the size of your arrays. While allocating a new memory region takes nearly a fixed amount of time, the time to fill this memory region grows linear with size. But, filling a new allocated memory with <code>numpy.zeros</code> is nearly twice as fast, as filling an existing array with <code>numpy...
python|numpy
6
9,623
59,622,843
File Upload S3 and heroku python
<p>I am trying to write a file to S3 using the s3.Object() method by creating a file in /tmp/ directory. I deployed it on heroku and its throwing an application error saying Worker timed out.</p> <p>Below is my source code: </p> <pre><code>def writeAckFile(dt,num1,num2): dt = dt.split('/') dt = dt[2] + dt[0]...
<p>Can you confirm if that ack.txt is been created or not. </p> <p>If its created you can use client instead of resource.</p> <p><code> client_s3 = boto3.client('s3') client_s3.upload_file('/tmp/Ack.txt', bucket_name, 'Ack1.txt') </code></p>
python|heroku|amazon-s3
0
9,624
49,204,378
Python/BeautifulSoup: Scrape Select Class
<p>I am trying to scrape the option values with the following HTML;</p> <pre><code>&lt;select class="PI__select PI__input js-select js-select-SIZE js-select-SIZE-static"&gt;&lt;option value=""&gt;SIZE&lt;/option&gt;&lt;option value="43714927955"&gt;XS&lt;/option&gt;&lt;option value="43714928019"&gt;S&lt;/option&gt;&lt...
<p>Instead of <code>&lt;select&gt;</code>, target <code>&lt;option&gt;</code> itself:</p> <pre><code>from bs4 import BeautifulSoup as soup s = soup('&lt;select class="PI__select PI__input js-select js-select-SIZE js-select-SIZE-static"&gt;&lt;option value=""&gt;SIZE&lt;/option&gt;&lt;option value="43714927955"&gt;XS&l...
python|beautifulsoup
0
9,625
60,233,322
How to hit URL with parameters within an API
<p>How to pass parameters to an url for get request in python?</p> <p>Suppose this is my url:</p> <pre><code>url = "http://105.119.2.20/data/personal/get/Id/&lt;Id&gt;/empId/&lt;empId&gt;/org_id/&lt;orgId&gt;" </code></pre> <p>I have to pass three parameters to this url:</p> <ol> <li>Id</li> <li>empId</li> <li>orgI...
<p>Just pass it as a <code>dict</code> to <code>params</code> arg</p> <pre><code>import requests response = requests.get("http://example.com/some/api/blah", params={"id": 1, "empId": 2, "orgId": 3}) </code></pre>
python-3.x|python-2.7|api|flask|flask-sqlalchemy
1
9,626
60,138,692
sqlalchemy psycopg2.errors.InsufficientPrivilege: permission denied for relation <<table>>
<p>I've read over 20 different questions with the same problem - and the suggested answers didn't solve my problem. I'm still getting <code>sqlalchemy psycopg2.errors.InsufficientPrivilege: permission denied for relation &lt;&lt;table&gt;&gt;</code></p> <p>Environment: EC2, debian 8, postgresql, flask, sqlalchemy my t...
<p>Not sure if you're manually testing with <code>psql</code> or <code>pgAdmin</code>, but ensure you're testing with the same account used in your code.</p> <p>Even if the user has access to a table/relation in the schema, they also need access to the schema itself: <code>grant usage on schema public to &lt;myuser&gt...
python|postgresql|sqlalchemy|permissions
7
9,627
60,256,628
Finding the max of numbers in multiple DataFrames Python
<p>I have 1000+ .txt files with stock dates and prices that I've cast to a dictionary (with filename(stock ticker) as the key, and the data for each file as a data frame). I calculated the moving average with .rolling, then found the percent difference between the moving average and the price. So, the percent differenc...
<p>Is this what you mean?</p> <pre><code>list_result = [] for key,value in dic1.items(): value.rename(columns={value.columns[0]:'Dates',value.columns[1]:'Prices'},inplace=True) value['ma'] = value['Prices'].rolling(window=50).mean() value['diff'] = value['Prices'] - value['ma'] value['pctdiff']= value[...
python|python-3.x|pandas|numpy|finance
2
9,628
5,861,997
Why is this python code taking so long?
<p>Alright, I have this python code that compares merge sort and selection sort, but it is taking forever. When done from n = 0 to 90,000 (the size of the list), it only takes about 3 seconds to sort the list. By this logic, it would take about 10 * 3 * 9 seconds (number of run throughs * duration * incremented run t...
<p>Because you are using O(n^2) sorting algorithms. This means that if you double n, the algorithm takes 4 times longer to run. Note that you are starting at 100,000 not 10,000</p>
python|sorting
4
9,629
6,051,051
getting odd error when calling python script within another python script
<p>I am getting an IOError when calling a python script(script2) within another python script(script1).</p> <p>Script 2 runs fine if called stand alone, however, if I call it from within script one, i get the following error.</p> <pre><code>C:\&gt;C:\Python32\python.exe R:\Scripts\BatchAging.py Traceback (most recent...
<p>Cleaner is to import the script and run its main method:</p> <pre><code>import DeleteAgingFiles DeleteAgingFiles.main() </code></pre> <p>Adding a main method to your script:</p> <pre><code>def main(): # the main code goes here if __name__ == "__main__": main() </code></pre>
python|logging|ioerror|invalid-argument
1
9,630
6,274,760
In Python, how do you conserve grouping when you sort by one value and then another?
<p>Data looks like this:</p> <p><strong>Idx &nbsp;&nbsp;&nbsp;&nbsp;score &nbsp;&nbsp;&nbsp;&nbsp;group</strong><br/> 5 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0.85 &nbsp;&nbsp;&nbsp;&nbsp;Europe<br/> 8 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0.77 &nbsp;&nbsp;&nbsp;&nbsp;Australia<br/> 12 &nbsp;&nbsp;&nbsp;&nbsp;&...
<p>I would just populate a dictionary with the maximum per group, and then sort on group maximum followed by individual score. Like this:</p> <pre><code>data = [ (5 , 0.85, "Europe"), (8 , 0.77, "Australia"), (12, 0.70, "S.America"), (13, 0.71, "Australia"), (42, 0.82, "Europe"), (45, 0.90, "Asia"), (65,...
python|sorting|sortedlist|sorteddictionary
2
9,631
67,762,870
I can't see the problem with numpy array (image-processing)
<p>I try to manually adjust the contrast of the image. The 2nd code works fine with me but it uses loop -&gt; it's slow so I change to 1st code but get a different output.</p> <p>I don't know what gone wrong because I assumed that these 2 are alike. Can somebody tell me what did I miss? Thanks a lot.</p> <p><strong>Cod...
<p>The problem is that <code>img</code> is an unsigned integer <code>uint8</code>, so when you subtract 128, it would get clipped at 0 instead of going negative.</p> <p>If you convert the image to <code>int</code>, it would work as expected:</p> <pre><code>a = PIL.Image.open('test.jpeg') b = np.asarray(a).astype(int) I...
python|numpy|image-processing|python-imaging-library
1
9,632
66,821,102
Appending sample number to X-Labels in altair
<p>I would like to automatically append the sample # (in parentheses) corresponding to the x-labels of an altair figure. I am open to doing this outside of altair, but I thought there may be a way to do it at the figure level using altair/vega-lite. I am pasting the code using an example from the altair/vega website (p...
<p>You could use pandas to generate the replacement dictionary and assign it to a new dataframe column:</p> <pre><code>import altair as alt from vega_datasets import data df = data.cars() group_sizes = df.groupby('Origin').size() replace_dict = group_sizes.index + ' (n=' + group_sizes.astype(str) + ')' df['Origin_with...
python|altair|vega-lite
1
9,633
67,009,827
Selenium webdriver : find element question
<p>I am trying to use python Selenium for the first time.<br /> This would be a simple question for some of you but I am a bit disappointed here..</p> <p>I would click on a link text which will open another webpage (WebDriver IE)</p> <p>When I inspect the link I have this:</p> <pre><code>&lt;li class=&quot;limarginSP&...
<p>Try to use one of the following locators:</p> <pre><code>driver.find_element_by_css_selector(&quot;limarginSP&gt;.spLink.ng-binding&quot;) </code></pre> <p>Or</p> <pre><code>driver.find_element_by_css_selector(&quot;.limarginSP&quot;) </code></pre> <p><code>find_element_by_link_text</code> is not always a good idea ...
python|selenium|internet-explorer|css-selectors|web-inspector
1
9,634
64,146,479
Include only .gz extension files from S3 bucket
<p>I want to process/download .gz files from S3 bucket. There are more than 10,000 files on S3 so I am using</p> <pre><code>import boto3 s3 = boto3.resource('s3') bucket = s3.Bucket('my-bucket') objects = bucket.objects.all() for object in objects: print(object.key) </code></pre> <p>This lists .txt files which ...
<p>The easiest way to filter objects by name or suffix is to do it within Python, such as using <code>.endswith()</code> to include/exclude objects.</p> <p>You can <code>Filter</code> by Prefix, but not by suffix.</p>
python|amazon-web-services|amazon-s3|boto3
0
9,635
72,265,507
FileNotFoundError in module easyocr when running exe file
<p>I am trying to run exe file and scan picture with easyocr, but here's occurs the error. Could someone help me, please?</p> <pre><code>Traceback (most recent call last): File &quot;threading.py&quot;, line 954, in _bootstrap_inner File &quot;threading.py&quot;, line 892, in run File &quot;ZhongDon.py&quot;, lin...
<p>This has solved my problem</p> <pre><code>pyinstaller -F ZhongDon.py --collect-all easyocr </code></pre> <p>Found the solution <a href="https://github.com/JaidedAI/EasyOCR/issues/473" rel="nofollow noreferrer">here</a></p>
python|pytorch|easyocr
0
9,636
72,437,914
how to get the answer of a question from a string or paragraph or article in python
<p>i got some data fetched out from an URL and i removed out the tags so the web page text remains so how to extract out the answer of the question i asked for</p> <p>for ex:</p> <p>input &gt; how to make money?</p> <p>get the article that tells me how to do so (id did that)</p> <p>algorithm to get the answer of that q...
<p>This is Natural language processing, which is much more advanced for me to do it justice in a single stackoverflow response. Theres a reason Google's search engine is so popular, and that's because stuff like this is a daunting task.</p> <p>Assuming you want to write an algo, I'd probably search the text for keyword...
python|nlp
0
9,637
65,765,588
How to divide a pandas pivot table by a dataframe with a difference shape?
<p><strong>Objective:</strong> I have a pivot table, where I would like to divide each cell by a value from my dataframe, if there is a match. <br> <a href="https://i.stack.imgur.com/daJbh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/daJbh.png" alt="enter image description here" /></a> <br><br> <a...
<p>Here's a solution with a <strong>for</strong> loop:</p> <pre><code>for store in df_div.index: divider = df_div.loc[store,][0] df.loc[:,(slice(None),store)] = df.loc[:,(slice(None),store)]/divider </code></pre> <p>Output of <em>df</em>:</p> <pre><code> Distance Start Store1 Store2 ...
pandas|pivot-table
1
9,638
50,947,759
Removing case-sensitive stopwords
<p>I am preprocessing a text and want to remove common stopwords in german. This works almost fine with the following code [final_wordlist as example data]:</p> <pre><code>from nltk.corpus import stopwords final_wordlist =['Status', 'laufende', 'Projekte', 'bei', 'Stand', 'Ende', 'diese', 'Bei'] stopwords_ger = stopw...
<p>Try this : <code>filtered_words = [w for w in final_wordlist if w.lower() not in stopwords_ger]</code></p>
python|nltk|case-insensitive|stop-words
5
9,639
51,063,420
Python, how to get the params of an xsl stylesheet?
<p>I want to get the params of an <code>xsl</code> file which is used to transform an <code>xml</code> file to a <code>csv</code> file. I especially want to get this line:</p> <pre><code>&lt;xsl:param name="sep" select="','"/&gt; </code></pre> <p>What I've tried:</p> <pre><code> with open(file, "r") as file: con...
<p>You can do it using <code>xml</code> parser. Like this:</p> <p>Suppose your file is <code>test.xsl</code>. Then you could do:</p> <pre><code>import xml.etree.ElementTree as ET tree = ET.parse('test.xsl') root = tree.getroot() match = [c.attrib for c in root if 'param' in c.tag] </code></pre> <p>Then <code>match</...
python|regex|xslt
1
9,640
3,463,496
Converting to Twisted Asynchronous Design
<p>Ok I have had a problem expressing my problems with the code I am working on without dumping a ton of code; so here is what it would be synchronously (instead of asking it from the view of it being async). </p> <p>Also for classes when should a variable be accessed through a method argument and when should it be ac...
<p>Given the circumstances, this just a skeleton of a solution which much implied. It seems to go against instinct to provide a solution with code where much is implied and untested...</p> <p>However, if I was coding what I think you're trying to achieve, I might go about it something like this:</p> <pre><code>from t...
python|asynchronous|twisted
5
9,641
3,790,563
How can I package a scrapy project using cxfreeze?
<p>I have a scrapy project that I would like to package all together for a customer using windows without having to manually install dependencies for them. I came across cxfreeze, but I'm not quite sure how it would work with a scrapy project.</p> <p>I'm thinking I would make some sort of interface and run the scrapy ...
<p>Try out py2exe. It works well, you can bundle all the code in one exe.</p> <p>I suggest you to exclude unused packages to reduce exe size (see py2exe examples on its site)</p> <p><strong>UDATE</strong> As suggested try also</p> <blockquote> <p><a href="http://code.google.com/p/gui2exe/" rel="nofollow">GUI2Exe<...
python|screen-scraping|py2exe|scrapy
1
9,642
3,795,914
Is there a way to use IronPython objects and functions (compiled into an assembly) from C# code?
<p>IronPython.net documentation says the MSIL in the assembly isn't CLS-compliant, but is there a workaround?</p>
<p>This was partly a motivation for adding the <code>dynamic</code> type to C# 4.0. The biggest problem is that IronPython declarations doesn't include type information, which makes it difficult to use it from C#. The <code>dynamic</code> keyword adds support for such dynamically typed objects to C# 4.0. See for exampl...
c#|ironpython|.net-assembly|cil|cls-compliant
1
9,643
35,210,619
Could not get visible text when using BeautifulSoup get_text or findAll(text=True)
<p>I am trying to extract visible text from a webpage using bs4 and python 3.4.1. For this I'm extracting all script and style elements from my soup and then proceed to getting the text from the remaining html.</p> <p>For testing purposes I used x,y,z to watch my soup modifications</p> <pre><code>html = urllib.reques...
<p>Removing all <code>script</code> and <code>style</code> elements and then getting the text of the <code>soup</code> worked for me:</p> <pre><code>import urllib.request from bs4 import BeautifulSoup html = urllib.request.urlopen('http://www.skilledup.com/articles/reasons-to-learn-python').read() soup = BeautifulSo...
python|html|beautifulsoup
2
9,644
35,232,308
django-markupfield returns string
<p>I'm trying to set up a Django app that has a <a href="https://github.com/jamesturk/django-markupfield" rel="nofollow noreferrer">MarkupField</a> in it's model, like this:</p> <pre><code>from django.db import models from markupfield.fields import MarkupField class Recipe(models.Model): instructions = MarkupFiel...
<p>Thanks to @doru's advices I stumbled across the Jinja2 documentation and found the autoescaping statement:</p> <pre><code>{% autoescape off %}{{ recipe.instructions }}{% endautoescape %} </code></pre> <p>This one worked for me.</p> <p>It's even possible to make it work globally by setting the <code>autoescape</co...
python|django|jinja2
0
9,645
44,986,818
How to catch the stack status in Openstack
<p>I have following conditions 1. stackCreate 2. stackUpdate 3. stackCreate</p> <p>What I am trying to do is, while the stackCreate/Update/Delete is triggered, I need to check on the progress. How can I do that? I know of 2 wayts 1. openstack stack event list . 2. I have below python code. </p> <pre><code> stack_...
<p>I worked it with below for now. It's not the best I think but satisfies what I need to do. </p> <pre><code>def stackStatus(status): evntsdata = hc.events.list(stack_name)[0].to_dict() event_handle = evntsdata['resource_status'].split("_") event_handle = '_'.join(event_handle[1:]) if event_handle == ...
python-2.7|automation|openstack
0
9,646
44,891,998
How to get boolean values from lambda in python?
<p>I am trying to feed values into lambda and if values exceed a certain limit consecutively 5 times I want to return 1 from the function, I am using filter but each time the <code>if</code> statement executes. How should I implement it using lambda? Please any other suggestion.</p> <pre><code>rpm = [45,20,30,50,52,35...
<p>If you're dead set on using a lambda expression, I think <code>reduce</code> is better suited to your purposes.</p> <pre><code>def check(): max_consec = reduce(lambda acc, r: acc + 1 if r &gt; rpm_limit else 0, rpm, 0) return 1 if max_consec &gt;= 5 else 0 </code></pre> <p>Here's what's going on: <code>acc...
python|lambda
1
9,647
64,821,596
ModuleNotFoundError for module 'linearmodels'
<p>I want to perform an OLS Panel Regression</p> <pre><code>import pandas as pd import numpy as np import statsmodels.api as sm from linearmodels.datasets import wage_panel from linearmodels.panel import PanelOLS data = wage_panel.load() </code></pre> <p>But I get this error:</p> <pre><code>ModuleNotFoundError ...
<p>&quot;linearmodels&quot; is a separate package, see <a href="https://github.com/bashtage/linearmodels" rel="nofollow noreferrer">https://github.com/bashtage/linearmodels</a>. Therefore, it must be installed separately:</p> <p><code>pip install linearmodels</code> works for me.</p>
python|jupyter-notebook|regression|linearmodels
2
9,648
64,812,449
How to make a function that receives an integer and returns only its odd digits?
<pre><code>def odd_numbers(x): res = 0 dig = 0 while x &gt; 0: dig = x % 10 if dig % 2 != 0: ___________________ x = x // 10 return(res) </code></pre> <p>Example:</p> <p>Input: <code>345321</code></p> <p>Output: <code>3531</code></p> <p>I was doing something like this...
<p>You can do the same in the other direction</p> <pre><code>def even_numbers(x): res = 0 fac = 1 while x &gt; 0: dig = x % 10 if dig % 2 != 0: res += dig * fac fac *= 10 x //= 10 return res </code></pre>
python
0
9,649
61,575,275
Event Source doesn't represent an information at each client/session
<p>I have a python server-side which sends a request using SSE.</p> <p>Here the example of python code. It sends an 'action-status' and data which JS has to handle (to do):</p> <pre class="lang-py prettyprint-override"><code>async def sse_updates(request): loop = request.app.loop async with sse_response(reque...
<p>I think your problem is synchronizing the data (<code>app["sse_requests"]</code>).<br> Depending on how you modify the data and who needs to be notified you might need to keep a list of clients (sessions). </p> <p>For example if all clients need to be notified of all events then keep a <code>list</code> (or even b...
javascript|python|server-sent-events|aiohttp
1
9,650
57,735,296
How to show total attempts at the end?
<p>I can't seem to be able to get the correct total number of attempts to be displayed.</p> <pre><code>def checkAge(): Age=int(input("EnterAge:")) attempts=0 if Age&gt;=100: attempts=attempts+1; return checkAge() elif Age&lt;=1: attempts=attempts+1; return checkAge() ...
<p><code>attempts</code> is being reset to 0 on each function call. You should create a parameter that you pass to <code>checkAge</code> and remove the variable instantiation <code>attempts=0</code>.</p> <p>An updated function might look like</p> <pre><code>def checkAge(attempts): Age=int(input("EnterAge:")) ...
python
2
9,651
56,226,284
Why do I get AttributeError: module 'tensorflow' has no attribute 'placeholder'?
<p>I was able to run my python program three weeks ago but now every time I try to run it, I get the following error:</p> <pre><code>AttributeError: module 'tensorflow' has no attribute 'placeholder' </code></pre> <p>I have tensorflow installed (version '2.0.0-alpha0'). I have read a couple of posts related to this i...
<p>In Tensorflow 2.0, there is no placeholder. You need to update your TF1.x code to TF2.0 code and then run it on your cluster. Please take a look at the <a href="https://www.tensorflow.org/alpha/guide/upgrade" rel="noreferrer">official doc</a> on converting your TF1.x code to TF2.0.</p> <p>In TF1.x codes, you build ...
tensorflow
10
9,652
56,331,005
How to save any file with PyQt5?
<p>In PyQt5, let's say I have a path to a given file or folder, would it be possible to save it in a location inputted by the user? I suppose it could also be a copy paste operation, where it copies the file or folder from one directory and pastes it to another.</p> <p>I currently have the current:</p> <pre><code>def...
<p>Saving a file in Python is completely independent from PyQt. You could save a file with contents in <code>contents</code> at location <code>path</code> using this code:</p> <pre><code>with open(path, "w") as f: # use "wb" if writing binary data f.write(contents) </code></pre>
python|pyqt|pyqt5
0
9,653
18,495,291
Takes an "eternity" to run my Python script
<p>I have a Python script which loads binary data from any targeted file and stores in inside itself, in a list. The problem is that the bigger the stored file is, the longer it takes to open it the next time. Let's say that I want to load a 700 MB movie and store it in my script file. Then imagine that I open it next ...
<p>Python compiler works in a way that makes what you are looking to do very very hard to say the least.</p> <p>First, every-time you change the script (by adding the file for example), it will trigger a new cycle of compilation before the execution (turning a .py file in a .pyc one). </p> <p>Second, every time you i...
python
1
9,654
18,601,282
Adding the result of an array in a csv file
<p>I tried to make this algorithm: random draw between 0 and 1(tir).si tir '&lt;'pred then Xestime2= 1 else Xestime2=0. I wish apply this algorithm in df ['X3'] but I had 0 in all the values ​​of X3 columns. Which explains thats i have an error in my code. My coding:</p> <pre><code>df = pd.read_csv(FNAME3, header=Non...
<p>First, don't use <code>genfromtxt</code> if you're using <code>pandas</code>. <code>read_csv</code> is much more flexible.</p> <pre><code>from cStringIO import StringIO from pandas import read_csv sio = StringIO('''0.000000000000000000e+00,4.871303471776848859e-01 0.000000000000000000e+00,2.489319061991416837e-01 ...
python|csv|numpy|pandas
1
9,655
18,431,313
How can static method access class variable in Python?
<p>This is what my code looks like</p> <pre><code>class InviteManager(): ALREADY_INVITED_MESSAGE = "You are already on our invite list" INVITE_MESSAGE = "Thank you! we will be in touch soon" @staticmethod @missing_input_not_allowed def invite(email): try: db.session.add(Invite(...
<p>You can access it as <code>InviteManager.INVITE_MESSAGE</code>, but a cleaner solution is to change the static method to a class method:</p> <pre><code>@classmethod @missing_input_not_allowed def invite(cls, email): return cls.INVITE_MESSAGE </code></pre> <p>(Or, if your code is really as simple as it looks, y...
python
67
9,656
71,715,580
How to extract a series of data based on specific keys that multiple dicts in a list (PYTHON)
<p>Requirements are:</p> <ol> <li>For each record of the file, there should be six main matrices: date, url, title, lang, jsonld, metatags. In the metatags, you can find keys and values. <strong>Please extract the data that contains any of the keys in the key_list.</strong></li> </ol> <p><strong>matrix = ['date', 'url'...
<p>In order to solve this, try to understand the data structure you are working with.</p> <p>In your attempts, it seems you are struggling with obtaining the <code>record</code> dictionaries, so try to get to those first (currently, 90% of your question focusses on obtaining data from metatags of specific records, filt...
python|json|python-3.x|list|dictionary
0
9,657
71,625,500
Removing all occurrences of any characters in the word 'dust' in the string
<p>Example:</p> <pre><code>Input: Output: dustbin bin </code></pre> <pre><code>if 'dust' in string: new = string.split('dust') listToStr = ''.join(map(str, new)) print(listToStr) </code></pre> <p>The above code works fine.</p> <p>But if the input changes like this.</p> <pre><code>Input: ...
<p>Use a regular expression.</p> <pre><code>import re result = re.sub(r'[dust]', '', string) </code></pre> <p>The regexp <code>[dust]</code> matches any of those characters, and all the matches are replaced with an empty string.</p> <p>If you want to remove only the whole word <code>dust</code>, with possible repetiti...
python|string|split
1
9,658
71,527,595
Efficiently count all the combinations of numbers having a sum close to 0
<p>I have following pandas dataframe df</p> <pre><code>column1 column2 list_numbers sublist_column x y [10,-6,1,-4] a b [1,3,7,-2] p q [6,2,-3,-3.2] </code></pre> <p>the sublist_column will contain the numbers from the column &quot;li...
<h2>Step 1: using Numba</h2> <p>Based on the comments, it appear that <code>memo_func</code> is the main bottleneck. You can use Numba to speed up its execution. Numba compile the Python code to a native one thanks to a just-in-time (JIT) compiler. The JIT is able to perform tail-call optimizations and native function ...
python|pandas|numpy|performance
17
9,659
69,606,823
How to get all files from a Bucket - IBM Cloud Object Storage?
<p>I want to get all files that are in my bucket with python. I trying this way:</p> <pre><code>import ibm_boto3 from ibm_botocore.client import Config, ClientError files = cos.Object(my_bucket_name).objects.all() # error here </code></pre> <p>But it shows this error:</p> <pre><code>ValueError (note: full except...
<p>Sorry, I was doing it wrong, the correct way is like this:</p> <pre><code>files = cos.Bucket(bucket_name).objects.all() </code></pre> <p>Problem solved!</p>
python|ibm-cloud
0
9,660
57,607,648
Getting empty list while using xpath with html.fromstring
<p>I am trying to extract text from a webpage using below code. It is working fine for other websites but here i am getting empty list</p> <pre><code>import requests from lxml import html siteurl = 'https://clinicaltrials.gov/ct2/show/NCT03752268?cond=cancer&amp;draw=2&amp;rank=1' rq = requests.get(siteurl) get_soup ...
<p>Consider also using css attribute = value selector. This is both shorter so less fragile, quicker as stops at the first match, and by adding/removing the <code>i</code> you can make case insensitive/sensitive</p> <pre><code>import requests from bs4 import BeautifulSoup as bs r = requests.get('https://clinicaltrial...
python|web-scraping|python-requests|lxml.html
0
9,661
54,209,202
pyparsing: nested expression with simple arithmetics
<p>I am using pyparsing to parse a nested expression which is formed by delimited lists but which includes some basic arithmetic (just multiplication, for instance). A sample expression could look like this:</p> <pre><code>(A, B, 2 * C, 3 * ( D, E, 2 * F, 3 *(G, H)), I ) </code></pre> <p>The output should unfold the ...
<p>If you want to use Forward() to roll our own recursive grammar, it is best to start with writing a BNF for your grammar. This will help you think straight about the problem space first, and then worry about the coding later.</p> <p>Here is a rough BNF for what you've posted:</p> <pre><code>list_expr ::= '(' list_...
python-3.x|math|pyparsing
1
9,662
53,842,863
flask/jinja sending an array to javascript
<p>I have the following code in </p> <blockquote> <p>main.py:</p> </blockquote> <pre><code>@app.route("/admin") def admin_panel(): resources = [{'id': '302', 'title': 'Participant 302'}] events = [] return render_template("admin.html", admin_resources=resources, admin_events=events) </code></pre> <p>In...
<p>There were 2 changes that needed to be made:</p> <ol> <li>today's date in the calendar cannot be "12-18-18". Needed to put into correct format: '2018-12-18'</li> <li>Need to put the variable accesses using safe. {{admin_resources | safe}}</li> </ol>
javascript|python|flask|fullcalendar|jinja2
1
9,663
58,274,966
Why is Python Skipping Over Tkinter Code?
<p>I'm in Python 3.x using Tkinter to make a button that changes a boolean variable's value from true to false then a if statement to check if that value is false. Here is my code for that:</p> <pre><code>import tkinter import time x = True top = tkinter.Tk() def helloCallBack(): x = False print (x) B = tkin...
<p>The reason you see that the code does <code>sleep()</code> and then prints <code>True</code> before the tkinter windows opens is due to how the <code>mainloop()</code> works in tkinter.</p> <p><code>sleep()</code> is useful in python however due to tkinter's single threaded nature all <code>sleep()</code> can due i...
python-3.x|tkinter
1
9,664
58,582,205
How to create a function in Python to determine if list is sorted or not?
<p>I'm asked to check to see if a list is sorted using a function, but I'm having trouble defining the parameter (lst) within my function without using the input function. It says lst is undefined but I'm not sure how to change that without using the input function</p> <pre><code>def is_sorted(lst): lst = [] ...
<p>At the point that you've called <code>lst</code> the first time (in the line <code>print (is_sorted(lst))</code> ) you haven't actually given <code>lst</code> a value. Before the print() you need a <code>lst = [1,2,3]</code> (or something).</p> <p>However, you may have overthought this function. I've added a simpli...
python|python-3.x|function|sorting
1
9,665
22,610,616
When I try to run 'cfx run' or 'cfx test' using the Mozilla Add-On SDK, my application binaries are not found
<p>I installed the the latest Add-On SDK by Mozilla (version 1.15). Installation was successful and when I execute <code>cfx</code> I get a list of all possible commands. I made a new separate empty folder, cd'd into it and ran <code>cfx init</code>. This was also successful and all necessary folders and files got crea...
<p>It's looking for the Firefox binary file, not your application's binaries. You have to install Firefox because <code>cfx run</code> will open a browser with your add-on installed so you can use it and test it live. </p> <p>If firefox is already installed, then it is in a non-standar path, so you must tell cfx comma...
python|macos|firefox|firefox-addon|firefox-addon-sdk
3
9,666
22,765,334
Running a command in python script and storing the result in a csv file or as tuple
<p>I'm trying to run OpenStack APIs from a python script. I used subprocess module to do that.</p> <pre><code>output = subprocess.check_output('nova-manage vm list',shell=True,) print output </code></pre> <p>"nova-manage vm list" gives a table that has columns as "instance, node, type, state, launched, image, kernel,...
<p>The first option is to use OpenStack API Python bindings directly as <a href="https://stackoverflow.com/questions/22765334/running-a-command-in-python-script-and-storing-the-result-in-a-csv-file-or-as-tu#comment34706355_22765334">@dorvak suggested in the comment</a>.</p> <p>If you want to use a subprocess then you ...
python|csv|subprocess
0
9,667
45,410,434
Pytest - python testing with asyncio
<p>Is it possible to return execution to <code>event loop</code> from a function. And as soon <code>Task</code> will be completed return to the function and continue execution?</p> <p>Im trying to use <code>pytest-asyncio</code> plugin</p> <p>Example:</p> <pre><code>@pytest.mark.asyncio async def test_async1(event_l...
<p>When your tests are marked with <code>pytest.mark.asyncio</code>, they become coroutines so you can use the <code>await</code> syntax:</p> <pre><code>@pytest.mark.asyncio async def test_sleep(event_loop): result = await asyncio.sleep(1, result=3, loop=event_loop) assert result == 3 </code></pre> <hr> <p>E...
python|python-3.x|pytest|python-asyncio
7
9,668
28,706,567
is it proper to use float64 data type with scikit-learn ML algorithms?
<p>I am trying to execute Decision Tree and SVM for a dataset given <a href="https://archive.ics.uci.edu/ml/machine-learning-databases/spambase/spambase.data" rel="nofollow">here</a> using scikit-learn. My purpose is to compare these two algorithms so that I am using KFold cross-validation method for both algorithms an...
<p>DecisionTreeClassifier and SVC internally use float32 to represent the features. They will convert any input data into this format. For machine learning tasks, that is usually more than enough precision.</p>
python|machine-learning|scikit-learn|classification|decision-tree
2
9,669
14,508,727
How to Get Value Out from the Tkinter Slider ("Scale")?
<p>So, here is the code I have, and as I run it, the value of the slider bar appears above the slider, I wonder is there a way to get that value out? Maybe let a=that value. ;)</p> <pre><code>from Tkinter import * control = Tk() control.geometry("350x200+100+50") scale = Scale(control,orient=HORIZONTAL,length=300,w...
<p>To get the value as it is modified, associate a function with the parameter <code>command</code>. This function will receive the current value, so you just work with it. Also note that in your code you have <code>cline3 = Scale(...).pack()</code>. <code>cline3</code> is always None in this case, since that is what <...
python|python-2.7|tkinter
16
9,670
6,477,578
PyGtk: change image after window's main() method?
<p>I'm using a gtk.Image widget to display a picture in a gtk window. I can set the image to be displayed before I call window.main(), but after I've done that the image won't change any more. Basically:</p> <pre><code>import pygtk pygtk.require('2.0') import gtk (...) window= Window() window.canvas= gtk.Image() win...
<p>As Rawing hasn't yet accepted his own answer, I'll post it to get this off the top of the unanswered questions page, and to help out anyone skimming this from a search engine clickthrough by providing a comprehensive answer. (Rawing, feel free to post your answer yourself, all the same.)</p> <p>In your code, you're...
pygtk|python-2.6
1
9,671
44,447,408
how do I allow user to delete their model objects in django?
<p>Ive been struggling to come up with a solution to allow a logged in user in django to delete their own created model objects. Im testing on service objects (a service order they create with a ServiceForm(ModelForm). I have django-safedelete in use to preserve the deleted objects in django admin, but disappear for ...
<p>After much struggle, abandoned writing a custom view that does not work, for the Generic DeleteView. best answer I found was here <a href="https://stackoverflow.com/questions/19382664/python-django-delete-current-object">Python Django delete current object</a></p>
django|database|forms|python-3.x
0
9,672
61,933,384
RISC-V Toolchain Makefile error problem with separators and code. How could I do it correct?
<p>Im having a problem with a Makefile Im trying to create. I just want to create one by one the .elf file then the dump and lastly the bin file and then with a python script convert it to .hex file. My goal is to actually create the .elf and .hex files with just using the make command.</p> <p>Despite that because Im ...
<p>How do you know you "used tabs on each rule"? It's not enough to press the TAB key on your keyboard: you have to be sure that your editor actually inserts a TAB character when you press the TAB key, and that when your editor writes out your file it preserves the TAB character in the written file (some editors will ...
python|c|makefile|riscv|riscv32
0
9,673
23,555,283
Why can't I scrape Amazon by BeautifulSoup?
<p>Here is my python code:</p> <pre><code>import urllib2 from bs4 import BeautifulSoup page = urllib2.urlopen(&quot;http://www.amazon.com/&quot;) soup = BeautifulSoup(page) print soup </code></pre> <p>it works for google.com and many other websites, but it doesn't work for amazon.com.</p> <p>I can open amazon.com in m...
<p>Add a header, then it will work.</p> <pre><code>from bs4 import BeautifulSoup import requests url = "http://www.amazon.com/" # add header headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36'} r = requests.get(url, headers=heade...
python|beautifulsoup|amazon
5
9,674
24,383,341
Pass list of links to Django Template
<p>I have a list of urls that I have imported in my settings.py file via:</p> <p><code>from myproject.image_folders_link import Links</code></p> <p>Now my <code>image_folders_link</code> contains the following constants:</p> <p>MY_image_doctors_link = "<a href="http://www.mywebsite.com/images/doctors" rel="nofollow"...
<p>If you want a set of constants available in all of your template, you should <a href="https://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors" rel="nofollow">write a "context processor"</a>. </p> <p>I don't really understand what variables you are trying to add, but in general y...
python|django|templates|django-templates|django-views
3
9,675
24,192,591
Control statement confusion in Python
<p>x is an array, y is a dict which is a member of the method z. What does the '\' mean? What does this code do?</p> <pre><code>for x, y in \ self.z({'yup': [10]}): for typex in x: //if statement </code></pre> <p>EDIT: Thank you for the help, I'm still unsure of what is being iterated over here, the p...
<p>The <code>\</code> is a line continuation, allowing the statement to continue to the next line without raising an indentation error. Aside from that this is just a vanilla for loop.</p>
python|for-loop|for-in-loop
3
9,676
24,112,027
What is a broken pipe error?
<p>Running code in python, I discovered a "Broken Pipe Error." Can someone please explain to me what this is <em>simply</em>?</p> <p>Thanks.</p>
<p>A pipe connects two processes. One of these processes holds the read-end of the pipe, and the other holds the write-end.</p> <p>When the pipe is written to, data is stored in a buffer waiting for the other processes to retrieve it.</p> <p>What happens if a process is writing to a pipe, but the process on the other...
python|broken-pipe
27
9,677
24,441,653
Trouble adding numbers together in python
<p>I am trying to rum a program that simulates 5 dice rolls. I know there is something simple I am missing, but I can't put a finger on it. I have tried to change the dice roll int, but it only prints the number in the output nothing is being added. What have I done??? The code is here and the output is below. Any help...
<p>every time you call <code>random.randint(MIN,MAX)</code> you get a NEW random number.</p> <p>you need to do something like this:</p> <pre><code>for count in range(ROLLS): dice = random.randint(MIN, MAX) if dice == 2: print('The total is two!') if dice == 3: .... </code></pre>
python
1
9,678
36,121,123
Python NLTK align import error
<p>I am getting a strange import error for NLTK's align module:</p> <pre><code>$ python2 --version Python 2.7.10 $ pip2 freeze | grep nltk nltk==3.2 $ python2 Python 2.7.10 (default, Oct 23 2015, 18:05:06) [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin Type "help", "copyright", "credits" or "lic...
<p>As of NLTK version 3.2, the <code>align</code> module has been <a href="https://github.com/nltk/nltk/commit/7690cbf5f4b548b51d1985c6432dade3d09bb460" rel="noreferrer">renamed to <code>translate</code></a>. Therefore use:</p> <pre><code>from nltk.translate import AlignedSent </code></pre>
python|nltk|python-import|python-module
10
9,679
29,632,515
Getting positions of your portfolio using python ibPy library
<p>I am using ibpy to get the positions of my portfolio. I understand that I can do:</p> <pre><code>from ib.opt import ibConnection tws = ibConnection( host = 'localhost',port= 7496, clientId = 123) tws.reqAccountUpdates(True,'accountnumber') </code></pre> <p>and then I am supposed to use <code>updatePortfolio()</cod...
<p><code>tws.reqAccountUpdates(True,'accountnumber')</code> Will send the string "acctnumber" when you probably meant it to be a variable. Notice the string I send is my actual (fake)account number.</p> <p>Then you need to register a callback for the messages you're interested in.</p> <pre><code>from ib.opt import ...
python|interactive-brokers|ibpy
6
9,680
46,332,673
Compare occurrences of shared items between lists
<p>Ok, for a fun project I'm working on in order to learn some python I'm hitting a wall with what should be a basic task: I need to compare lists for the times items shared among the lists occur in each list. Using <code>shared_items = set(alist).intersection(blist) gives me the items shared</code>betwen the lists...
<p>You almost had it using the set <code>intersection</code>. Since that gives you the common elements amongst both lists, all you have to do now is loop over that and count the elements. One way could be:</p> <pre><code>list1 = [0, 1, 2, 3, 1, 2, 3, 4, 3, 2] list2 = [1, 4, 3, 5, 2, 1, 0, 2, 7, 8] shared = set(list1)....
python
2
9,681
46,369,942
Syntax Error installing scikit-learn using pip from SHELL
<p>The following gives a syntax error:</p> <pre><code>python -m pip install scikit-learn </code></pre> <p>SyntaxError: invalid syntax There is a "^" under the 2nd 'p' in pip.</p> <p>I am using the <strong>SHELL</strong>. There are two programs in the Windows 10 program group: "Python 3.6 (32-bit)" and "IDLE (Python ...
<p>This problem occurs when you try to run <code>pip</code> from the Python interpreter. Instead, run from the Windows Command Prompt and you should have no issues.</p>
python|python-3.x|windows-10|python-import|python-install
0
9,682
49,355,749
How to fix TypeError: input expected at most 1 arguments but got 3
<p>The following code raises <code>TypeError: input expected at most 1 arguments but got 3</code>. I am unsure how to fix this.</p> <pre><code>def leg_count(w): x = input("How many legs does a", w, "have? ") print("A", w, "has", x, "legs") leg_count("crocodile") </code></pre>
<p>The function <code>input</code> takes a single argument. It cannot be used the same way as <code>print</code> which will take and print multiple arguments. You will need to use <code>str.format</code> to do what you want.</p> <pre><code>def leg_count(w): x = input("How many legs does a {} have? ".format(w)) ...
python|python-3.x
1
9,683
49,473,708
SVG embedded in SVG is of poor quality (python, svgwrite)
<p>I am creating an <code>svg</code> file using python and its module <code>svgwrite</code>. Alongside with circles and so on (which works fine) I need to input another <code>svg</code> file. For that I used:</p> <pre><code>dwg = svgwrite.Drawing('test.svg', size=(size_x, size_y), profile='tiny') dwg.add(dwg.image('i...
<p>Inkscape doesn't have good support for SVG images embedded in SVG images. It shows them as their raster representations, see also <a href="https://bugs.launchpad.net/inkscape/+bug/171795" rel="nofollow noreferrer">https://bugs.launchpad.net/inkscape/+bug/171795</a> .</p>
python|svg|inkscape|svgwrite
1
9,684
21,064,311
Convert tree of dictionaries to multidimensional list
<p>I have a dictionary like this (Python):</p> <pre><code>{'G': {'G': {'T': {'A': 'end'}, 'C': 'end'}, }, 'C': {'G': 'end'} } </code></pre> <p>How can I convert it to a multidimensional array like this one?:</p> <pre><code>['G', ['G', ['T', ['A'], ...
<pre><code>d = { 'G': {'G': {'T': {'A': {'$': '$'}}, 'C': {'$': '$'}} }, 'C': {'G': {'$': '$'}} } def merge(dct): return [[k] + merge(v) for k,v in dct.items() if isinstance(v, dict)] &gt;&gt;&gt; merge(d) [['C', ['G']], ['G', ['G', ['C'], ['T', ['A']]]]] </code>...
python|dictionary|multidimensional-array
2
9,685
62,507,490
HTML img src returning a 404 not found error despite everything in order v.2
<p>I can access the IMG folder from the browser, caps and everything checked. Although when I run python main.py or Heroku app shows 404. I don´t know why it keeps showing 404, I´ve tried every path possible it´s just not working. I´m using Flask <a href="https://i.stack.imgur.com/cQZ2I.png" rel="nofollow noreferrer">a...
<p>You can use url_for function. For example, for the first img, you can do the following</p> <pre><code>&lt;img src=&quot;{{ url_for('img', filename='uiyou.png') }}&quot; alt=&quot;logo&quot; class=&quot;nav-brand&quot;&gt; </code></pre>
python|flask
0
9,686
45,815,531
Tensorflow op with two inputs, return one of the two and override gradient
<p>I'm trying to implement a synthetic gradient scheme in Tensorflow.</p> <p>I need to have an op which takes two inputs and return one of them (i.e. an identity with a dummy variable). Something like <code>f(a, b): return a</code></p> <p>I need this because then I want to override the gradient with a formula which d...
<p>You can add the following code during model definition to override gradient. <code>tf.Graph</code> has <a href="https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/Graph#gradient_override_map" rel="nofollow noreferrer"><code>gradient_override_map</code></a> construct to achieve the same</p> <pre><code>g = t...
python|tensorflow|neural-network
1
9,687
45,724,230
Pyspark - create training set and testing set from dataframe
<p>I have a dataframe like the photo below. I would like to create a training and testing set out of it. The dataset is ordered by CustomerID and InvoiceNo. For each customer, I would like to take every row except the last 2 rows of that customer as training set, while the second to the last row of each customer would ...
<p>You could always add an index and filter based off of that index--not sure if there's anything more efficient than that. </p> <pre><code>from pyspark.sql.window import Window from pyspark.sql import functions as func window = Window.partitionBy(func.col("CustomerID"))\ .orderBy(func.col("InvoiceNo").desc()...
python|machine-learning|pyspark|pyspark-sql
0
9,688
24,935,064
Python: How to plot circles around given coordinates
<p>I'm currently trying to plot circles of a given radius around coordinates, in order to see if the plotted circles overlap. I currently have:</p> <pre><code>import matplotlib.pyplot as plt for i in range(len(b)): for j in range(len(d)): circle1=plt.Circle((b[i,0], b[i,1]), 0.5, color='r', fill=False) ...
<p>Your circle plotting code saves len(d) x len(b) images with the same name, and these images have more and more circles (as you are only creating a new image once, implicilty at <code>plt.gcf()</code>). If you just want to create many png images, I suggest you draw the two circles once and then every round just chang...
python|matplotlib|geometry
0
9,689
24,641,126
Python ImageMagick pip install of pymagick not working
<p>I'm looking to install image magic with pip. I was under the impression that pymagick was the way to do this.</p> <p>I would like to use it to determine color schemes of images.</p> <p>pip install ... ImageMagic,python-pythonmagick, pythonmagick all have the cannot find error. Ex:</p> <blockquote> <p>Could not ...
<p>ImageMagick isn't a Python package - you install it separately (and before installing your Python dependencies)</p> <p>See <a href="http://www.imagemagick.org/" rel="noreferrer">http://www.imagemagick.org/</a></p>
python|image|python-2.7|imagemagick|pip
8
9,690
40,972,649
save two list in one json file
<p>I'm getting data with two lists and I want to save both of them in one single json file can someone help me. I'm using selenium </p> <pre><code>def get_name(self): name = [] name = self.find_elements_by_class_name ('item-desc') price = [] price = self.find_elements_by_class_name ('it...
<p>I would create a dictionary and then JSON <code>dumps</code></p> <p>An example could be:</p> <pre><code>import json def get_name(self): names = [ name.text for name in self.find_elements_by_class_name('item-desc') ] prices = [ price.text for price in self.find_elements_by_class_name('item-goodPrice')] ...
python|json|selenium
1
9,691
38,460,944
Replace values in one column for specific instances of another column
<p>I am new to Pandas and not sure how to do the following:</p> <p>I have a dataframe (df) with several columns. One column is called </p> <pre><code>OldCat = ['a-nn', 'bb-nm', 'ab-pp', 'ba-nn', 'cc-nm', 'ca-mn'] </code></pre> <p>Now I want to create a new column that organizes/categories OldCat in a new way (NewCat...
<p>You can use the vectorised <code>str.extract</code> to return matches with <code>fillna</code> to replace <code>NaN</code> with the string <code>'nan'</code>:</p> <pre><code>In [119]: df['NewCat'] = df['OldCat'].str.extract('(^a|ba|ca)', expand=False).fillna('nan') df Out[119]: OldCat NewCat 0 a a 1 ...
python|string|pandas|str-replace
2
9,692
30,753,732
Can't call Python entry_points from command line
<p>I just installed a <a href="https://github.com/rkern/line_profiler" rel="nofollow">python tool for line profiling</a> that <a href="https://github.com/rkern/line_profiler/blob/master/setup.py#L68" rel="nofollow">should ship with itself</a> a command line entry point named kernprof</p> <pre><code>$pip install line_p...
<p>The problem is that with Macports's Python the scripts are installed in <code>/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin/</code> that is not in the <code>PATH</code>. </p> <p>The lighter solution could be to symlink the script to <code>/usr/local/bin</code></p> <pre><code>sudo ln -s /opt/local...
python|macos|macports
1
9,693
39,993,714
user.is_authenticated always returns False for inactive users on template
<p>In my template, <code>login.html</code>, I have:</p> <pre><code>{% if form.errors %} {% if user.is_authenticated %} &lt;div class="alert alert-warning"&gt;&lt;center&gt;Your account doesn't have access to this utility.&lt;/center&gt;&lt;/div&gt; {% else %} &lt;div class="alert alert-warning"&gt;&lt;...
<p>There isn't any point checking <code>{% if user.is_authenticated %}</code> in your login template. If the user is authenticated, then your <code>custom_login</code> view would have redirected them to the homepage.</p> <p>If the account is inactive, then the form will be invalid and the user will not be logged in. T...
python|django|django-templates|django-authentication
3
9,694
29,216,684
How to play a sound file in Debian Python?
<p>sorry if this is a bit noobish but it's my first post. I am trying to open a .wav file (could be any though) in Python, on Debian Linux (on my raspberry Pi) I can't find any soloution that actually works, most modules are too old and don't work. I would preferablly like it to be as simple as possible. I just want th...
<p>Pyglet should work. Something like this:</p> <pre><code> import pyglet sound = pyglet.resource.media('file.wav', streaming=False) sound.play() </code></pre> <p>I dont think it is preinstalled on the pi, but it's less than 1mb.</p>
python|linux|audio|debian
0
9,695
8,814,842
Data types in PHP SOAP
<p>I'm having problems creating proper variables according to my WebService WSDL. I have implemented this simple feature in python succesfully using suds 0.4 SOAP library.</p> <p>Python implementation (tracker is my SOAP client object that consumes wsdl):</p> <pre><code>c = self.tracker.factory.create("ns4:Text") c.t...
<p>PHP can use the WSDL file to generate an appropriate set of methods to which you can pass generic objects, arrays, or scalars as arguments. You can also specify which classes map to which methods (the <code>classmap</code> option), and which type declarations map to which serialization callback functions (the <code>...
php|python|soap
1
9,696
58,767,740
3D scatter plot of multiple files with each file having unique color
<p>I have seen <a href="https://stackoverflow.com/questions/12236566/setting-different-color-for-each-series-in-scatter-plot-on-matplotlib">this thread</a> but my data are a little different. I want to create a 3D plot of multiple files containing x,y,z coordinates and color code each <strong>file</strong> with a uniqu...
<p>I think you mistake comes from the mesh list that you are updating at every step. You plot the whole mesh list every step, such that your first file is plotted 16 times, in 16 different colors. </p> <p>The simplest code could be:</p> <pre><code>import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3...
python|matplotlib|numpy-ndarray
1
9,697
52,026,654
how is asyncio.sleep() in python implemented?
<p>I'm a newbie python3 enthusiast, who hopes to find out how asyncio.sleep() is implemented by the library. </p> <p>I'm capable of writing coroutines but I can't seem to think about how to start writing code for asynchronous sleep.</p> <p>would be great if you share the code directly or give a quick tutorial on how ...
<p>For code implemented in Python (as opposed to C extensions), if you're using <code>ipython</code>, an easy way to see the source code is to use the <code>??</code> operator. For example, on my 3.6 install:</p> <pre><code>In [1]: import asyncio In [2]: asyncio.sleep?? Signature: asyncio.sleep(delay, result=None, *,...
python|python-3.x|asynchronous|python-asyncio
11
9,698
52,342,543
Extract content of <Script> in Python with BeautifulSoup
<p>I want to extract value of window.<strong>FEED__INITIAL__STATE</strong></p> <p><a href="https://i.stack.imgur.com/p4OSZ.png" rel="nofollow noreferrer">Piece of code</a></p> <p>How can I do it?</p>
<p>Maybe you should try like this:</p> <pre><code>import requests from bs4 import BeautifulSoup def check_script_tag(url): r = requests.get(url) parsed_html = BeautifulSoup(r.content, features="html.parser") try: text = parsed_html.body.find('script').text print (text) # Here text in sc...
python|python-3.x|beautifulsoup
0
9,699
18,827,538
SignedJwtAssertionCredential refresh
<p>Each thread in my client initializes with</p> <pre><code>self.credentials = oauth2client.client.SignedJwtAssertionCredentials(...) http = httplib2.Http() http = self.credentials.authorize(http) self.http = http </code></pre> <p>This works fine initially and each client is able do appropriate work. </p> <p>As the ...
<p>Regarding threads, please read this: <a href="https://developers.google.com/api-client-library/python/guide/thread_safety" rel="nofollow">https://developers.google.com/api-client-library/python/guide/thread_safety</a></p> <p>There is no need for manual refresh since it's automagically done in the apiclient library ...
google-oauth|google-api-python-client
0