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
8,300
64,732,824
Call python script from another python script
<p>I have two scripts</p> <p><strong>script_1.py</strong></p> <pre><code>import sys import math from datetime import datetime, timedelta from calendar import isleap count = sys.argv[1] state = sys.argv[2] f = open(&quot;myfile_c_&quot;+count+&quot;.xml&quot;, 'a') f.write(&quot;&lt;state &gt;&quot;+state+&quot;state ...
<p>in top of script_2.py put the line below,else, you have another variable in your script_2.py called count so change one of them into another name to avoid bug.</p> <pre><code>from script_1 import count </code></pre>
python
0
8,301
52,963,909
Pytorch: Getting the correct dimensions for final layer
<p>Pytorch newbie here! I am trying to fine-tune a VGG16 model to predict 3 different classes. Part of my work involves converting FC layers to CONV layers. However, the values of my predictions don't fall between 0 to 2 (the 3 classes). </p> <p>Can someone point me to a good resource on how to compute the correct dim...
<p>I wrote a function that takes a Pytorch model as input and converts the classification layer to convolution layer. It works for VGG and Alexnet for now, but you can extend it for other models as well.</p> <pre><code>import torch import torch.nn as nn from torchvision.models import alexnet, vgg16 def convolutionize...
python|machine-learning|pytorch|conv-neural-network
1
8,302
65,317,288
How to sort a list by date correctly?
<p>Im trying to sort a list of data, but it seems like the sort isn't working. I first took out the date portion of the list and tried to compare it to the current date.</p> <pre><code>from datetime import datetime, date test = { '3001265': ['Samsung', 'phone', '1200', '12/1/2023', ''], '1009453': ['Lenovo', '...
<p>The reason for the error is that the sorting was done using a string instead of a time.</p> <p>Your code is too long, and it's actually very easy to do this sort.</p> <pre><code>from datetime import datetime test = { '3001265': ['Samsung', 'phone', '1200', '12/1/2023', ''], '1009453': ['Lenovo', 'tower', '5...
python|sorting|date
2
8,303
62,652,159
How to get dynamodb to only return certain columns
<p><a href="https://i.stack.imgur.com/dUy7D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dUy7D.png" alt="enter image description here" /></a></p> <p>Hello, I have a simple dynamodb table here filled with placeholder values.</p> <p>How would i go about retrieving only <code>sort_number</code>, <cod...
<p>Within the Boto3 SDK you can use:</p> <ul> <li><a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Client.get_item" rel="noreferrer">get_item</a> if you're trying to retrieve a specific value</li> <li><a href="https://boto3.amazonaws.com/v1/documentation/api/lat...
python|amazon-web-services|amazon-dynamodb|boto3
5
8,304
67,316,669
Pandas merge or join directly from read_csv
<p>I have seen many examples of how to use merge.</p> <p>Has anyone ever tried doing something like this?</p> <p>df = pd.read(“data1.csv).merge(pd.read_csv(“data2.csv, how='inner', on='a'))</p> <p>I’m going to try it but figured I’d ask here too...</p> <p>If I could this, then I wouldn’t need to read in data1 and data2...
<p>It looks like you can actually do this - I wonder if this can aid in memory management.</p> <p>See below.</p> <pre><code>data1 = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'], 'key2': ['K0', 'K1', 'K0', 'K1'], 'P': ['P0', 'P1', 'P2', 'P3'], 'Q': ['Q0', ...
python|merge|pandas
0
8,305
63,628,098
how to plot "_" objects along the X axis but varying the values ​on the Y axis ?(in python, matplotlib, pandas)
<p>I have two dataframes A and B, I want to plot dataframe B values ​​in dataframe A graph, both shared the same indices, but in point y two &quot;_&quot; objects will be placed one up two points and the other 2 points down the value they share in Y, how to do?</p> <p>look like this the image=</p> <p><a href="https://i...
<p>Not sure to fully understand your expectation, but you should be able to manage with:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt data_a={&quot;date&quot;:[&quot;2015-08-31&quot;,&quot;2015-09-01&quot;, &quot;2015-09-02&quot;,&quot;2015-09-03&quot;, &quot;2015-09-04&quot;,&quot;2015-09-08&qu...
python|pandas|matplotlib|artificial-intelligence|data-science
0
8,306
68,895,645
Decorator to check input type in a class
<p>By using decorator I can use to check variable type of function. Something like this:</p> <pre><code>def accepts(*types): def check_accepts(f): assert len(types) == f.__code__.co_argcount def new_f(*args, **kwds): for (a, t) in zip(args, types): assert isinstance(a, t)...
<p>As written, <code>print_dataframe</code> is an instance method, so you either need to take that into account:</p> <pre><code>NO_CHECK = object() def accepts(*types): def check_accepts(f): assert len(types) == f.__code__.co_argcount def new_f(*args, **kwds): for (a, t) in zip(args, ty...
python|python-decorators
1
8,307
58,727,245
Tensorflow 2 won't compile using bazel on windows 10 - package name error
<p>I am trying to compile Tensorflow 2 c++ API on windows, using this guide: <a href="https://itnext.io/how-to-use-your-c-muscle-using-tensorflow-2-0-and-xcode-without-using-bazel-builds-9dc82d5e7f80" rel="nofollow noreferrer">https://itnext.io/how-to-use-your-c-muscle-using-tensorflow-2-0-and-xcode-without-using-bazel...
<p>This is an error about the command line.</p> <p>Maybe you accidentally entered invalid characters that confused Bazel. I do that sometimes if I jump left and right with Ctrl+Left / Ctrl+Right and accidentally hit a key inbetween.</p> <p>Try typing the command again (do not copy-paste it), and running it. Also, it ...
windows|tensorflow|bazel|tensorflow2.0
0
8,308
65,497,783
Dataset organization for Convolutional Neural Network
<p>Is there anyone who can give me the right links for data organization for <strong>Convolutional Neural Network</strong>, please? I searched myself, I was looking for an article about that topic from towardsdatascience.com but did not found it. Thank you in advance!</p>
<p>I don't know if this is what you need, but are you looking for a specific structure of a CNN?</p>
python|dataset|conv-neural-network|organization
0
8,309
65,532,109
How can I organize a text in python with web scraping
<p>I'm trying to web scrape text and organize it, the text looks something like this: <a href="https://i.stack.imgur.com/bKuXl.png" rel="nofollow noreferrer">https://i.stack.imgur.com/bKuXl.png</a> It is a mess. How can I organize it to a json file or something? Also I just did a basic web scrape:</p> <pre><code>from b...
<p>Try this:</p> <pre><code>source = requests.get('https://api.hypixel.net/skyblock/bazaar') json_response = source.json() </code></pre>
python
1
8,310
50,916,210
Exporting training checkpoint to production - idiot's guide required
<p>I'm having a right 'mare.<br> I'm having real difficulties with trying to get training information to a state where I can deploy to a production server.<br> I followed <a href="https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10" rel="nofollow noreferrer">thi...
<p>I don't necessary think that a frozen graph is bad for serving, at least I don't see why it would be, but that could be just me. I'm going to try and help, but can't promise anything.</p> <p>1) A frozen graph is basically a transformed savedModel with all the weights set to constants instead of variables, and there...
tensorflow|object-detection
1
8,311
26,560,640
Cannot pickle a Naive Bayes classifier in Python?
<p>I am trying to save my trained Naive Bayes classifier in python. I've followed previous, similar questions to no avail. I'm kind of new to Python and don't really understand what is wrong, I've created and trained my classifier as per the NLTK book. How can I save this model to work on it later?</p> <p>This is the ...
<p>EDITED: I experimented a bit with this and I concluded that your code works perfectly when tried with the latest stable version of nltk on a valid dataset. So I would suggest you either update/reinstall your library or check that your dataset is a valid one. A valid dataset has to be a list of tuples <code>(features...
python|text|nltk|pickle|text-classification
0
8,312
26,438,022
Creating login for a websocket application?
<p>I've created a websocket avatar chat application where a user is given an avatar and they can move around with this avatar and send messages.</p> <p>I want to design a login which connects to my database (already has several accounts stored). When a user has logged in with the correct details, I'd like for their us...
<p>Cookie is available with websocket. Just login and store a session/cookie for the user as normal. The you will know who it is.</p> <p>Or, just send the cookie as the first message after connecting.</p>
javascript|python|websocket
0
8,313
61,277,233
How do I structure my Django view classes?
<p>I and a friend are about working on a project. I have a structure for working with my views. If I'm working with the User model, and I want to write code for CRUD operation, I write using four different classes. One for each like so:</p> <pre><code>class CreateUser(FormView): &lt;code here&gt; class ReadUser(...
<p>I think your friend's proposal goes the right way and I would go a little bit further.</p> <p>I recommend you using <a href="https://www.django-rest-framework.org/" rel="nofollow noreferrer">Django Rest Framework</a>. It already has Class-based views that can save you a lot of time of coding.</p> <p>Depending on t...
python-3.x|api|oop|django-rest-framework|django-views
1
8,314
56,377,960
Swig: syntax error when wrapping global static constants
<p>When I try to wrap the following code:</p> <pre><code>enum VehicleSide { LEFT = 0, ///&lt; left side of vehicle is always 0 RIGHT = 1 ///&lt; right side of vehicle is always 1 }; /// Class to encode the ID of a vehicle wheel. /// By convention, wheels are counted front to rear and left to right. In other...
<p>Showing your SWIG .i file would help, but the cause is likely that you've put instances of your class in the header file. I see that you don't want to edit the header, but the .h file should <code>extern</code> the class instances and the definition should be in the .cpp file; otherwise, you'll have multiple separa...
python|c++|swig
0
8,315
58,201,133
Aggregation by Foreign Key and other field in Django Admin
<p>I'm working in Django and having an issue displaying something properly in my Admin site. These are the models</p> <pre><code>class IndexSetSize(models.Model): """ A time series of sizes for each index set """ index_set = models.ForeignKey(IndexSet, on_delete=models.CASCADE) byte_size = models.BigIntege...
<p>I don't think you would be able to return the full queryset and group by <code>index_set</code> in <code>get_queryset</code> as you can't select all columns but group by an individual column in sql</p> <pre class="lang-sql prettyprint-override"><code>SELECT *, SUM(index_size) FROM indexsetsize GROUP BY index_set ...
python|django|django-admin
0
8,316
45,485,676
How can I start reading text at a specific line and stop and specific line
<p>Long time listener first time caller, I'm quite new to this so please be kind.</p> <p>I have a large text document and I would like to strip out the headers and footers. I would like to trigger the start and stop reading lines with specific strings in the text.</p> <pre><code>filename ='Bigtextdoc.txt' startlookup...
<p>For readability I'll extract the logic in a function like:</p> <pre><code>def lookup_between_tags(lines, starttag, endtag): should_yield = False for line in lines: if starttag in line: should_yield = True elif endtag in line: should_yield = False if should_yie...
python-3.x|lines
2
8,317
53,453,179
python3 request body with variable
<p>I stuck in my Python3 code when using requests to make HTTP POST requests. I need to put variable "PackageId" inside data and gets error:</p> <pre><code>{"meta":{"code":4015,"type":"Bad Request","message":"The value of `carrier_code` is invalid."},"data":[]} </code></pre> <p>My code is:</p> <pre><code>import requ...
<p>You need to convert the <code>data</code> dict to a json string when providing it to <code>post()</code>, it does not happen implicitly:</p> <p><code>request = requests.post('https://api.trackingmore.com/v2/trackings/post', headers=headers, data=json.dumps(data))</code></p>
python-3.x|http-headers|python-requests
1
8,318
53,636,004
No module named 'django.db.backends.mysql.compiler'
<p>I have this strange error since we upgrade from Django 1.11.5 to Django 2.1.3 (python 3.5.2). We use MySQL 5.7.24. The latest packages installed are:</p> <ul> <li>django-mysql==2.4.1</li> <li>mysqlclient==1.3.14</li> </ul> <p>We also use Celery:</p> <ul> <li>celery==4.2.1</li> <li>django-celery-beat==1.3.0</li> <...
<h1>Solved!</h1> <p>We finally found the problem. The solution was to recreate the virtual environment.</p>
python|mysql|django
1
8,319
53,778,052
Plot values for multiple months and years in Plotly/Dash
<p>I have a Dash dashboard and I need to plot on the x axis months from 0-12 and I need to have multiple lines on the same figure for different years that have been selected, ie 1991-2040. The plotted value is a columns say 'total' in a dataframe. The labels should be years and the total value is on the y axis. My data...
<p>It seems to me that you should have a look at <code>pd.pivot_table</code>.</p> <pre><code>%matplotlib inline import pandas as pd import numpy as np import plotly.offline as py import plotly.graph_objs as go # create a df N = 100 df = pd.DataFrame({"Date":pd.date_range(start='1991-01-01', ...
python-3.x|plotly
1
8,320
33,266,344
np.where Not Working in my Pandas
<p>I have an np.where problem using Pandas that is driving me crazy and I can't seem to solve through Google, the documentation, etc.</p> <p>I'm hoping someone has insight. I'm sure it isn't complex.</p> <p>I have a df where I'm checking the value in one column - and if that value is 'n/a' (as a string, not as in .i...
<p>You need to pass the boolean mask and the (two) values columns:</p> <pre><code>np.where(Full_Names_Test_2['MarketCap'] == 'n/a', 7) # should be np.where(Full_Names_Test_2['MarketCap'] == 'n/a', Full_Names_Test_2['MarketCap'], 7) </code></pre> <p><em>See the <a href="http://docs.scipy.org/doc/numpy/reference/genera...
python|pandas|where
19
8,321
52,861,413
Tensorflow CNN test data splitting and array sizing problems
<p>I've tried to figure things out myself and not fallback to actually creating an account here but as a self-taught beginner I've reached a wall with this code.</p> <p>I'm having two major issues besides optimizing the net architecture when everything is working:</p> <ul> <li><p>Everytime I've tried to create a new ...
<p>are you sure that this part:</p> <pre><code>_, c = sess.run([optimiser, cross_entropy], feed_dict={x_shaped: batch_x, y: batch_y}) </code></pre> <p>doesn't have to be:</p> <pre><code>_, c = sess.run([optimiser, cross_entropy], feed_dict={x: batch_x, y: batch_y}) </code></pre> <p>furthermore you've a batchsize ...
python|tensorflow|machine-learning
0
8,322
52,827,483
Tensorflow: What if my cond is not a scalar in tf.cond in while loop?
<p>in <code>tf.cond</code> of tensorflow, <code>cond</code> has to be a scalar, but in my case <code>cond</code> need to be rank 1 with shape [batch_size]. Is there any method to solve this problem? Have tensorflow provided a solution to it?</p> <pre><code>import tensorflow as tf seq_len = 10 while_length = 10 batch_s...
<p>One potential solution I realized is <code>tf.where</code>:</p> <pre><code>import tensorflow as tf seq_len = 10 batch_size = 4 output_ta = tf.TensorArray( dtype=tf.float32, size=seq_len, tensor_array_name='example_1') cond_tensor = tf.constant([3, 4, 5, 6]) t1 = tf.ones(shape=[batch_size, seq_len]) ...
python|tensorflow
1
8,323
70,488,117
Is there a way I can detect if there is any of a list inside of a string
<p>I have a variable called 'command' and I want to check whether command contains any of a certain list. For instance, if I have a list with [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;] and I want to detect if command has any of those elements in it. So if command is &quot;abc&quot; it will return true for that if st...
<pre class="lang-py prettyprint-override"><code>def command_contains_element(command, element_list): return any(c in command for c in element_list) </code></pre>
python|python-3.x
3
8,324
70,385,525
Extracting value with beautifulsoup get_text() problem
<p>I am trying to extract a single &quot;value&quot; <strong>$82.76</strong> from the code below.</p> <pre><code>&lt;div class=&quot;MuiBox-root jss40 metric price&quot;&gt; &lt;h6 class=&quot;MuiTypography-root MuiTypography-h6 MuiTypography-colorTextSecondary&quot;&gt;HEC Price&lt;/h6&gt; &lt;h5 class=&quot;M...
<p>Changing '.next_sibling' to '.find_next_sibling()' does the trick.</p> <pre><code>content = html_file.read() soup = BeautifulSoup(content, 'html.parser') tags = soup.find('h6', text='HEC Price') tag = tags.find_next_sibling().get_text() print(tag) </code></pre> <p>EDIT:</p> <p>I would not recommend using nested .n...
python|beautifulsoup
0
8,325
70,393,592
What is best way to send images to Rest API?
<p>I am trying to build a React app which sends an image to an Rest API and returns a processed image. What is the best way to send images through Rest API ? My current assumption is using &quot;base64&quot; encoding to send images as strings,but the size of my images will be around 5-10MB and I dont think base64 will ...
<p>You shouldn't be sending the images this way at all. The rough approach might be to upload images to some storage (S3 or whatever), then use API just to communicate the reference to that image (id, URI). Basically, you just need to send the info about who uploaded the image (user id) and where it is stored (filesyst...
javascript|python|reactjs
3
8,326
70,426,337
Sphinx documentation showing double-colon in fields
<p>I am developing documentation for a package and when I build the sphinx docs I'm getting double colons</p> <p><img src="https://i.stack.imgur.com/8EmeK.png" alt="double colons" /></p> <p>for all of the fields for every function definition.</p> <p>I am using the numpydoc style for my docstrings and there are no colon...
<p>Seems like to be a bug of some versions. I moved from Sphinx <code>3.5.2</code> to <code>4.4.0</code> and the double colons are gone.</p>
python|python-sphinx|docstring|numpydoc
0
8,327
66,739,244
discord.py @client.command() doesn't seem to work
<p>I'm trying to switch my bot from using @client.event for everything to also using @client.command The problem is when running the command <strong>.commandtest</strong>, nothing happens. I put a print statement in the code to see if the problem was writing in the discord channel, but it doesn't print to the terminal ...
<p>This should work:</p> <pre><code>import discord client = discord.Client() </code></pre> <p>When, the bot is ready, it prints out that he's logged in</p> <pre><code>@client.event async def on_ready(): print('Logged in as ' + str(client.user)) </code></pre> <p>If you get a message in discord, that starts with '.'...
python|discord|discord.py
0
8,328
66,463,269
How can I connect loggin page to main page?
<p>I am working on a school. I am creating a library management system and I am done with the code and connect the login and the homepage but whenever i run the code and enter the correct username and password and click on the login button, the login page closes and does not open the main page. what should i do? help. ...
<p>dont use window.show() end of the page</p> <pre><code>from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * class widget(QWidget):     def __init__(self, parent):         super().__init__()         self.parent = parent         self.label1 = QLabel(&quot;Username&quot;)         self.l...
python|mysql|pyqt5
0
8,329
65,255,709
PermissionError: [WinError 5] Access is denied - Running the program in vs code
<p>I am trying to write a program for deleting all the temp files on my system. I have using <code>os module</code> from <code>python 3.9.1</code> and I am running it on <code>VS Code</code>. I tried to find out the solution, where it was suggested to run the terminal in <code>Administrator mode</code>, but I am using ...
<p>You can try running the file in administrator mode using <code>runas</code> command.</p> <pre><code>runas /user:Administrator your_Command </code></pre> <p>If your command includes spaces, don't forget to add quotes.</p> <pre><code>runas /user:Administrator &quot;your command&quot; </code></pre>
python|file|operating-system|shutil
0
8,330
65,137,769
How to count elements inside a time window in Apache beam, and emit the data when the count reach some threshold?
<p>I want to count elements per key from unbounded source (I am using Pub/Sub for my source) within a time window, and emit the count result when it reach some threshold. For example, I want to count the elements within 10 minutes fixed time window, and emit the results to another Pub/Sub when the count is &gt; 5.</p> ...
<p>You can see in <a href="https://beam.apache.org/documentation/programming-guide/#event-time-triggers" rel="nofollow noreferrer">the documentation</a> that you can add trigger on window.</p> <p>Go to the section 9.3 and you have the definition of the <code>AfterCount</code> trigger that emit the data every each &quot...
python|google-cloud-platform|google-cloud-dataflow|apache-beam
4
8,331
71,982,189
cv2.connectedComponentsWithStats source code
<p>Does anyone knows where to find the source code for cv2.connectedComponentWithStats? I would like to see exactly what's happening in this function to help me understand better.</p>
<p>It's <a href="https://github.com/opencv/opencv/blob/13a995cc1d2700812dfd979097924703ba2267bc/modules/imgproc/src/connectedcomponents.cpp#L5752-L5769" rel="nofollow noreferrer">here</a> in C++. The Python package calls the compiled C++ code.</p>
python|opencv
1
8,332
68,612,203
beautiful soup find tag within tag
<p>I read a bunch of articles and couldn't find anything really relevant. I promise :) This is with BS4 and the lxml parser under python 2.7.3.</p> <p>I had this:</p> <pre><code>self.chaptername = self.soup.find_all('center h3 b') </code></pre> <p>and in my html I have</p> <pre><code>&lt;center&gt;&lt;h3&gt;&lt;b&gt;Ch...
<p>You are making a call to BeautifulSoup's <code>.find_all()</code> function. This takes a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-name-argument" rel="nofollow noreferrer">name argument</a> which can be either a string, a regular expression, a list, a function, or the value True.</p> <p>For...
python|beautifulsoup
0
8,333
10,391,391
Matplotlib window appears at the back?
<p>Whenever I call <code>show()</code> in matplotlib the plot window appears behind all other windows and I have to minimize everything to see it. Is there any way I can prevent this or programmatically bring it to the front. On OSX Lion. Python 2.7</p>
<p>Well. This answer is presented in the comments to the accepted answer but I think it deserves to have a place as a separate one as it solves the issue nicely. Besides the author's problem I additionally had the problem that matplotlib window wasn't in the tray of active windows so I couldn't switch to it by <code>&l...
python|macos|plot|matplotlib
1
8,334
5,073,995
Obtaining indexes of changed data between two numpy arrays
<p>I have two 3d numpy arrays a1 and a2 where <code>len(a1) == len(a2)</code> and <code>a1[x, y, z] = id</code></p> <p>I'm using this code to find out if there is changed data in any of the z layers</p> <pre><code>eq = a1 == a2 if eq.any(): #find the indexes of the changed data </code></pre> <p>as the comment an...
<p>Two more options:</p> <pre><code>np.argwhere(a1!=a2) np.where(a1!=a2) </code></pre> <p>They both do the same thing but produce results in different formats (one suitable for indexing the arrays, the other more readable)</p>
python|arrays|numpy
4
8,335
4,859,292
How to get a random value from dictionary?
<p>How can I get a random pair from a <code>dict</code>? I'm making a game where you need to guess a capital of a country and I need questions to appear randomly.</p> <p>The <code>dict</code> looks like <code>{'VENEZUELA':'CARACAS'}</code></p> <p>How can I do this?</p>
<p>One way would be:</p> <pre><code>import random d = {'VENEZUELA':'CARACAS', 'CANADA':'OTTAWA'} random.choice(list(d.values())) </code></pre> <p><strong>EDIT</strong>: The question was changed a couple years after the original post, and now asks for a pair, rather than a single item. The final line should now be:<...
python|random|dictionary|key
350
8,336
62,595,160
Type Error: argument 1 has unexpected type 'QPushButton'
<p>I wrote this codes:</p> <pre><code>import sys import os from PyQt5 import QtWidgets class Notepad(QtWidgets.QWidget): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.yazi_alani = QtWidgets.QTextEdit() self.temizle = QtWidgets.QPushButton(&quot;Te...
<p>You should rename your buttons or funcions. You've got here method Notepad.temizle() AND button Notepad.temizle So when you expect to send a message, instead you send a button, which is typeError Also I can see the same error with other methods</p>
python|python-3.x|pyqt|pyqt5|typeerror
1
8,337
62,701,540
Import .py functions from Github into PyCharm
<p>I'm completely new to PyCharm and Python, so I might get some terminology wrong.</p> <p>I'd like to use a few .py functions (which a colleague of mine prepared) in my program in PyCharm. These functions are stored on GitHub. In a demo, which is stored in the same repo, she was able to simply import them with</p> <p>...
<p>This should provide an answer to your Question: <a href="https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path">How to import a module given the full path?</a> You can then set the absolute path to the files you want to import. Hope I could help you out.</p>
python|github|pycharm|python-import
0
8,338
61,703,506
Extract data faster from Redis and store in Panda Dataframe by avoiding key generation
<p>I am using Redis with Python to store my per second ticker data (price and volume of an instrument). I am performing <code>r.hget(instrument,key)</code> and facing the following issue.</p> <p>My <code>key</code> (string) looks like <code>01/01/2020-09:32:01</code> and goes on incrementing per second till the user s...
<p>redis sorted set's are good fit for such range queries, sorted sets are made up of unique member's with a score, in your case timestamp can be score in epoch seconds and price and volume can be member, however member in sorted set is unique you may consider adding timestamp to make it unique.</p> <pre><code>zadd in...
python|pandas|redis
1
8,339
61,835,823
How to work with more elements with same class in one page using Selenium Webdriver in Python
<p>so basically i am making a program in Python that is going to go to one site, click on one picture (than do something) and than move to another picture (and do the same thing) and so on.. well the problem is, there is like 10 pictures with same <code>img</code> class BUT <code>scr</code> is always changing and i hop...
<p>You can try to use x-path, I'm using a chrome extension: <a href="https://chrome.google.com/webstore/detail/xpath-finder/ihnknokegkbpmofmafnkoadfjkhlogph?hl=en" rel="nofollow noreferrer">https://chrome.google.com/webstore/detail/xpath-finder/ihnknokegkbpmofmafnkoadfjkhlogph?hl=en</a></p> <p>To locate the picture.</...
python-3.x|selenium-webdriver
0
8,340
61,788,378
The output halts when entered any positive integer. The problem must be in the while loop
<pre><code>height=int(input("Enter the height from which the ball is dropped: ")) count=0 travel_dist=0 index=0.6 if height&lt;=0: print("The ball cannot bounce...") else: while (height&gt;0): travel_dist=height+(height*index) count+=1 height=height*index ...
<p>As user @MichaelButscher mentioned above, multiplying a positive value repeatedly with the coefficient (0.6 in this scenario) will get close to zero but will never get there. You can see this if you print out <code>height</code> within the while loop. You'll have to set the limit of <code>height</code> to a differen...
python|loops|while-loop|execution
1
8,341
67,229,279
What can I use instead of using this for loop in python
<p><code>a</code> is a matrix of dimension n by m. <code>b</code> is a matrix of dimension n by m. each row of matrix is <code>a</code> one-hot-representation. Consider m=5, the first row of <code>a</code>, for example, is [0, 0, 0, 1, 0] and of <code>b</code> is [0, 0, 1, 0, 0].</p> <p>I want to compare <code>a</code>...
<p>I think this would work :</p> <pre><code># Dimensions n = 100 p = 100 # Example matrices a = np.random.choice([0,1], size=(n, p)) b = np.random.choice([0,1], size=(n, p)) # Compute the sum of true positives and true negatives tp_tn = np.multiply(a, b).sum() + np.multiply(1-a, 1-b).sum() # Compute accuracy acc = t...
python|matrix|vector
1
8,342
70,320,978
Selenium not Finding Xpath Button element on Twitter
<pre class="lang-py prettyprint-override"><code>Nextbut=self.driver.find_element(By.XPATH,'//*[@id=&quot;react-root&quot;]/div/div/div/main/div/div/div/div[2]/div[2]/div[1]/div/div[6]') Nextbut.click() </code></pre> <p>This is the path I am using to find the button on twitters website but selenium always returns this e...
<p>next button is dynamic in twitter web page u can't use xpath. use position indexing method to get the element. ex: //div[@role='button'][2] for twitter.</p>
python|selenium|twitter|bots
0
8,343
11,270,611
python convert unknown character to ascii
<p>In a text file I'm processing, I have characters like ����. Not sure what they are.</p> <p>I'm wondering how to remove/convert these characters.</p> <p>I have tried to convert it into ascii by using .encode(‘ascii’,'ignore’). python told me char is not whithin 0,128</p> <p>I have also tried unicodedata, unicodeda...
<p>You can always take a Unicode string an use the code you showed:</p> <pre><code>my_ascii = my_uni_string.encode('ascii', 'ignore') </code></pre> <p>If that gave you an error, then you didn't really have a Unicode string to begin with. If that is true, then you have a byte string instead. You'll need to know what...
python|character-encoding
7
8,344
70,411,436
tkinter: Set option command for Entry after declared it
<p>I need to declare the option command for an entry after declare it, here's my code:</p> <pre><code>import tkinter as tk import sys from utils import * import re def main(): #create window window=tk.Tk() #set window size, window title and window icon window.geometry(&quot;600x600&quot;) window.t...
<p>I have written a working solution. You should use the <code>validatecommand</code>, you can find the detailed documentation of it: <a href="https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/entry-validation.html" rel="nofollow noreferrer">https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/entry-validation.h...
python|python-3.x|user-interface|tkinter
0
8,345
55,621,916
Automate bulk loading of data from s3 to Aurora MySQL RDS instance
<p>I am relatively new to AWS so I am not sure how to go about doing this,</p> <p>I have CSV files on s3 and I have already set up the Aurora instance on RDS. The thing that I am unable to figure out is how do I automate the bulk loading of data, essentially doing like a <code>LOAD DATA FROM s3</code> kind of thing us...
<p>The approach is as stated above, have an S3 event trigger and a lambda job listening on the s3 bucket/object location. As soon as a file is uploaded to the s3 location, the lambda job will run, and in the lambda, you can configure to call an AWS Glue job. This is exactly we have done and has gone successfully live...
python|mysql|amazon-web-services|amazon-s3|aws-glue
4
8,346
56,685,928
spread array of values to parameters in function call
<p>I am getting an array of values and I want to send them to a predefined function with the same parameter count.</p> <p>The naive way is to do:</p> <pre><code> values = [1,2,3,4] # getting it from outside if len(values) == 1: func(values[0]) elif len(values) == 2: func(values[0], values[1]) . . . </c...
<p>You can use <a href="https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists" rel="nofollow noreferrer">arbitrary argument lists</a></p> <pre><code>def func(*args): for arg in args: print(arg) values = [1] func(*values) values = [1, 2] func(*values) func(1) func(1,2) </code></pre...
python
2
8,347
69,059,541
new value is the sum of old values
<p>I have 2 list A and B, list A contain values I want list B to be the sum of value from list a</p> <pre><code>A = [3,5,7,8,9,12,13,20] #Wanted result #B = [3, 8, 15, 23,...77] #so the new value will be the sum of the old value # [x1, x2+x1, x3+x2+x1,... xn+xn+xn] </code></pre> <p>what methods I could use to get the a...
<p>The easiest way IMO would be to use <code>numpy.cumsum</code>, to get the cumulative sum of your list:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.cumsum(A) array([ 3, 8, 15, 23, 32, 44, 57, 77]) </code></pre> <p>But you also could do it in a list comprehension like this:</p> <pre><code>&gt;&gt;&...
python-3.x
1
8,348
62,987,593
The view basicapp.views.register didn't return an HttpResponse object. It returned None instead)
<pre><code>from django.shortcuts import render,HttpResponse from basicapp.forms import UserForm,UserProfileInfoform # Create your views here. def index(request): return render(request,'basicapp/index.html') def register(request): registered = False if request.method == &quot;POST&quot;: user_form...
<p>Try using below code:</p> <pre><code>from django.shortcuts import render,HttpResponse from basicapp.forms import UserForm,UserProfileInfoform # Create your views here. def index(request): return render(request,'basicapp/index.html') def register(request): registered = False if request.method == &quot;...
python|html
0
8,349
62,361,741
ValueError when trying to use pipenv install
<p>I am totally new to this. So I installed pipenv using 'pip install pipenv'. I have python version 3.8.2, pip version 20.1.1 and pipenv version 2020.6.2 . But when I try to run 'pipenv install' it gives the following error. </p> <pre><code> C:\Users\rd463&gt;pipenv install Traceback (most recent call last): Fi...
<p>I think the newer version of <strong>pipenv</strong> is causing the error, I use this command when having the same issue and it worked for me, just use</p> <pre><code>pip install pipenv==2018.10.13 </code></pre>
python|valueerror|pipenv
7
8,350
35,639,658
Python regex, exclude matches in quotes
<p>I have this string:</p> <pre><code>s = MY_FUNC(AVG, WFC US EQUITY, WFC US EQUITY, "&gt;+3%", 1,1,7) </code></pre> <p>And this regex that searches for parens, commas, and simple operators. I need exclude any matches inside double quotes and be able to split on the matches. Note that the solution must still search f...
<p><code>re.split</code> is not a clean way to do tokenizing. There is a <a href="https://docs.python.org/3/library/re.html#writing-a-tokenizer" rel="nofollow">recipe</a> in the documentation of <code>re</code> which will serve you better. Basically, you first write a regex for each lexical type. For example:</p> <pre...
python|regex
1
8,351
58,697,163
Python + CSV files: How do I automatically create unique names for objects, and pull data from specific cells
<p>I have been taking an introduction to data science for archaeology course, and am currently struggling with the first (non-marked) piece of work. While I understand the overall logic of the code I’m meant to be writing and don't have problems writing it out in psudocode, I’m struggling a lot with syntax. I’ve asked ...
<p>Instead of storing each <code>Table()</code> object in varaibles, i would create a dictionary with the filename of each csv file as the key. </p> <p>So before the <code>for</code> loop declare an empty dictionary <code>csvs = {}</code></p> <p>Then for each csv file, I would save the table object as a value with th...
python|csv
0
8,352
73,209,881
How can I get the "!" as an item on this split list?
<p>This is my first question! </p> <p>What should the pattern be in order to make the last &quot;!&quot; appear as an item on this split list?</p> <pre class="lang-py prettyprint-override"><code> import re re.split(r'([.?!]) ', 'One sentence. Another one? And the last one!') </code></pre> <p>I get: <code>['One s...
<p>You can split using the following regex:</p> <pre><code>(?=[\.?!])|(?&lt;=[\.?!] ) </code></pre> <p>which will match</p> <ul> <li><code>(?=[\.?!])</code>: any place which is followed by a punctuation character</li> <li><code>(?&lt;=[\.?!] )</code>: any place which comes after a punctuation character + space</li> </u...
python|regex|split
2
8,353
73,278,593
Yellow underlines for libraries due to Pylance, even though they work without problem
<pre><code>import discord # it's yellow underlined print(discord.__version__) # ' out: 2.0.0 </code></pre> <p>Pylance can't find anything about it. Same thing happens with pygame and numpy too. And probably with all libraries. I tried in both 3.10 and 3.9. My interpreter path if needed: <code>C:\Python\Python310\python...
<p>Because the location of the package you installed successfully may not be the same as the python environment you are using.</p> <ul> <li><p>First, open the command palette with <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd></p> </li> <li><p>then search for <strong>Python:Select Interpreter</strong></p> </li> <li><p>C...
python|visual-studio-code
0
8,354
15,652,667
openerp 7 one2many and many2one
<p>please refer below code lines between 205 - 280</p> <p><a href="https://github.com/priyankahdp/openerp/blob/openerp/model%20class" rel="nofollow">https://github.com/priyankahdp/openerp/blob/openerp/model%20class</a></p> <p>and in my view xml lines between 255 - 337</p> <p><a href="https://github.com/priyankahdp/o...
<p>Why you are adding parent (tea_worker_line_id 'bpl.offer') in child (selected_tea_workers_line_ids 'bpl.selected.tea.workers.line'), it is not needed remove it from the view coz you already made tea.worker.lines as one2many of bpl.offer .</p>
python|xml|one-to-many|openerp|many-to-one
1
8,355
49,002,399
Shallow copy not working in python
<p>I tried to do shallow copy, but it's not working for me.</p> <pre><code>import copy a = [1,2,3,4] b = copy.copy(a) </code></pre> <p>Now both <code>a</code> and <code>b</code> will have same values [1,2,3,4]. But if I append <code>b.append(1)</code>, it is not reflected in a.</p> <pre><code>b.append(1) print(b) [1...
<p>First thing first: what you get is the expected behaviour. "shallow" copy means that you create a new copy of the object, so adding to list <code>b</code> will obviously NOT impact list <code>a</code>. </p> <blockquote> <p>I just want to understand difference between deepcopy and shallow copy. Because shallowcopy...
python|shallow-copy
2
8,356
60,150,950
How do I easily change the functionality of my code?
<p>I want to make my game "go back" to the main menu and I was wondering If I can use the gamewindow function "inside" its own so that it would create a "reset". Basically, If my sprite were to collide and it says "game over" I would like to press the "back" button and If I were to press play again it would show a "res...
<p>As you say, you've just started and are learning. Very good! You've just run into a problem that you can learn a lot from: <strong>adding new features</strong>. Generally, this question would be better suited on the <a href="https://codereview.stackexchange.com/">code review stack exchange</a> but I think it's also ...
python|pygame|pycharm
2
8,357
60,209,757
AttributeError: 'NoneType' object has no attribute 'text' | Beautifulsoup
<pre><code>import requests from bs4 import BeautifulSoup from requests_html import HTMLSession #Request URL page = requests.get('https://www.fifa.com/worldcup/players.html') #Fetch webpage soup = BeautifulSoup(page.content,"html.parser") player_age = soup.find("div",{"class":"fi-p__profile number__number"}).text.r...
<p>Error says us that <code>soup.find("div",{"class":"fi-p__profile number__number"})</code> found nothing. And nothing (None or NoneType) can't have any attributes.</p> <p>By the way, link you provided returns 404 error. It seems like you try to parse page without requested data.</p>
web-scraping|beautifulsoup|python-3.8
0
8,358
60,328,125
How to remove WindowsPath and parantheses from a string
<p>I need to remove <code>WindowsPath(</code> and some of the closing parentheses <code>)</code> from a directory string.</p> <pre><code>x= (WindowsPath('D:/test/1_birds_bp.png'),WindowsPath('D:/test/1_eagle_mp.png')) </code></pre> <p>What I need to have is </p> <pre><code>x= ('D:/test/1_birds_bp.png', 'D:/test/1_ea...
<p>You can easily target the paths with:</p> <pre><code>(?&lt;=WindowsPath\(').*?(?='\)) </code></pre> <ul> <li><code>(?&lt;=WindowsPath\(')</code> - left side needs to literally be <code>WindowsPath('</code></li> <li><code>.*?</code> - lazily capture everything until we hit the positive lookahead</li> <li><code>(?='...
python|regex|string|split|strip
1
8,359
2,442,580
Python: Removing tuples from a list of lists
<p>I have a list of lists containing tuples:</p> <pre><code>[[(1L,)], [(2L,)], [(3L,)], [(4L,)], [(5L,)] </code></pre> <p>how do i edit the list so the list looks like:</p> <pre><code>l = [[1][2][3][4][5]] </code></pre>
<pre><code>&gt;&gt;&gt; a [[(1L,)], [(2L,)], [(3L,)], [(4L,)], [(5L,)]] &gt;&gt;&gt; a = [[x[0][0]] for x in a] &gt;&gt;&gt; a [[1L], [2L], [3L], [4L], [5L]] </code></pre>
python|list|tuples
6
8,360
66,960,356
SQLAlchemy many to many query filter (tag system)
<p>I have a Django App and a Telegram bot that uses same database. There are 2 tables Link and Tag have many to many relation (models are below). I'm trying to query <code>link_id</code>'s where all <code>tag_id</code>'s are <code>[1, 8, 10]</code>. Query result should be <code>[1,4]</code>.</p> <p>Using: SQLAlchemy 1....
<p>Finally solved.</p> <p>SQL:</p> <pre class="lang-sql prettyprint-override"><code>SELECT link_id FROM link_tags WHERE tag_id IN (1,8,9,10) GROUP BY link_id HAVING COUNT(tag_id)=3 </code></pre> <p>SQLAlchemy:</p> <pre class="lang-py prettyprint-override"><code>session.query(link_tag_table.c.link_id) .filter(link_tag_t...
python|sqlalchemy
0
8,361
65,672,418
Python Regular Expression works on MacOS but not Ubuntu
<p>I am running a Python script on a GitHub action that runs on a Ubuntu 18.04 machine.</p> <p>The script splits a Markdown file into several markdown files based on matching level one headers (i.e <code># Header {header-anchor}</code>), so I use</p> <pre class="lang-py prettyprint-override"><code>for match in re.findi...
<p>Turns out the file I was parsing on the ubuntu machine used a different markdown flavor that didn't have level one headers specified by <code>#</code>.</p>
python-3.x|regex|github-actions
0
8,362
51,019,668
How to format Python when using for loop inside with block
<p>I've only recently starting using <code>with</code> to open files, instead of the more old-school separate open/close calls.</p> <p>However, I'm finding this means all my code to iterate through files now has double-indentation:</p> <pre><code>with open('filename', 'rb') as f: for line in f: # do stuff...
<p>You don't have to put the logic inside the <code>with</code> block:</p> <pre><code>with open('filename', 'rb') as f: file_content = f.readlines() for line in file_content: # do stuff </code></pre> <p>The downside with this approach is that the whole file would need to be saved into the <code>file_content<...
python|iteration
4
8,363
26,634,843
Django: How do I dynamically filter a dropdown box?
<p>Say for example I have a three models. <code>Content</code>, <code>Chapter</code> and <code>Page</code>. Within the <code>Content</code> form there will be two dropdown boxes. One for <code>chapters</code> and the other for <code>pages</code>. If I was to select a <code>chapter</code> from the dropdown box, how do I...
<p>I suggest you two option:</p> <ol> <li>using <a href="http://django-autocomplete-light.readthedocs.org/en/latest/dependant.html" rel="nofollow">django-autocomplete-light</a></li> <li>using jquery like <a href="http://www.devinterface.com/blog/en/2011/02/how-to-implement-two-dropdowns-dependent-on-each-other-using-d...
python|django
1
8,364
44,824,557
Pandas merging dataframes
<p>I have several dataframes that I want to merge, but the problems is that the don't have the same columns and that I want to merge only specific rows. I will show an example so it will be easier:</p> <p><strong>MAIN_DF</strong> that I want all to be merge to it:</p> <pre><code>key A B C 0001 1 0 0 ...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow noreferrer"><code>DataFrame.combine_first</code></a>:</p> <pre><code>MAIN_DF = MAIN_DF.set_index('key') DF_1 = DF_1.set_index('key') DF_2 = DF_2.set_index('key') df = MAIN_DF.combine_f...
python|pandas|dataframe
3
8,365
61,424,212
Get user input and output Flask and HTML
<p>I'm trying to develop a web-app with Flask and HTML and right now I need to get the user input, pass it to the Python back-end, execute a function and return its output, placing it inside an HTML element. I also want this to happen without refreshing the HTML page. </p> <p>How can I do this? Bellow I have the code...
<p><code>$.getJSON</code> is designed to load the JSON data from endpoint using GET request, however, your Python code example responds to only POST requests.</p> <p>Here is the working code:</p> <p>HTML</p> <pre class="lang-html prettyprint-override"><code>&lt;div id="ThroughputRate" class="data_entry"&gt; &lt;...
javascript|python|html|python-3.x|flask
0
8,366
60,756,094
Keep sorted list of mutable elements up to date
<p>I can use <code>sorted</code> or <code>list.sort</code> in python to sort a list that was not sorted before.</p> <p>If I want my list to remain sorted as I add elements in it, I can use <a href="http://www.grantjenks.com/docs/sortedcontainers/sortedlist.html" rel="nofollow noreferrer"><code>SortedList</code></a> fr...
<p>There is no mechanism to do what you want. Even if you were to resort a list after mutating an element, it'd have O(nlogn) complexity. But because <code>add()</code> uses bisect behind the scenes, it only has O(logn). So it's better to do something like you suggested, i.e., remove the to-be-mutated element and readd...
python|python-3.x|list|sorting|mutable
2
8,367
57,790,277
Pycryptodome Python3 RSA.importKey blocking/hangs
<p>I am running Python 3.5.2 with the latest version of Pycryptodome.</p> <p>When importing my RSA private key using <code>RSA.importKey</code> there is an infinite hang or block. I've tried to step through the lib and cannot find any reason why.</p> <p>The private key is an RSA private key in PEM format. i.e. I am p...
<p>One neat solution is taken from another <a href="https://stackoverflow.com/questions/3443607/how-can-i-tell-where-my-python-script-is-hanging/3443779">SO question</a> and it is based on <a href="http://khamidou.com/lptrace/" rel="nofollow noreferrer">lptrace</a>. You get the PID of the python process and then run:</...
python-3.x|cryptography|rsa|pycryptodome
0
8,368
56,250,594
Can we use Expressions delimiters "{{ }}" within Statement delimiter "{% %}"
<p>I want to use "jinja2" for showing comments and reply functionality for my blog website using "Flask" so i was trying to show reply within comments section as show in example or please suggest if anyone have better way to manage comments and its reply with flask: This is what i mean if comment have reply then its go...
<p>I found the answer i don't need to use expression delimiters if i want to use jinja2 var in within statement delimiter: {%if comments[0] ==reply[0]%} </p>
python|flask|jinja2
0
8,369
55,176,830
Need help figuring out which youtube html tag to get in order to load a video in python
<p>I'm writing a script that loads the first youtube video that appears after entering a search query using <code>requests</code> and <code>bs4.BeautifulSoup</code>. It seems all youtube videos have an <code>a</code>tag with an id of <code>#video-title</code>. Therefore I would think the simplest solution is to use <co...
<pre class="lang-py prettyprint-override"><code>video = soup.findAll('a',attrs={'class':'yt-uix-tile-link'}) </code></pre> <p><a href="https://allofyourbases.com/2017/10/08/web-scraping-youtube-in-python/" rel="nofollow noreferrer">For more information check this article</a></p>
python|beautifulsoup
0
8,370
42,347,569
Not able to eval an image in CNTK python
<p>Below is the code I am using:</p> <pre><code>import sys,os import numpy as np # import dicom import glob import cv2 import time import cntk import pandas as pd from PIL import Image from sklearn import cross_validation from cntk import load_model from cntk.ops import combine from cntk.io import MinibatchSource, Ima...
<p>Can you try: </p> <pre><code>output_nodes.eval({output_nodes.arguments[0]:[imag3]})) </code></pre>
python|cntk
3
8,371
59,227,239
Python pygame how to set the FPS
<p>I am making a python game and I don't know what should I set my FPS to. My game is stuck and not smooth. How do I know what should the FPS be?</p> <p>This is my code:</p> <p><a href="http://bin.shortbin.eu:8080/x87bSUKUiN" rel="nofollow noreferrer">http://bin.shortbin.eu:8080/x87bSUKUiN</a></p>
<p>After running your code I have also noticed frame rate drops which hurt the smoothness of the game.</p> <p>There are two separate issues here:</p> <p><strong>1. The FPS drops</strong></p> <p>The FPS drops probably happen because of something you cannot control, like the garbage collector working. Even though you ...
python|python-2.7|pygame|pycharm|frame-rate
3
8,372
22,579,034
django adding static path to current url
<p>I have my static files in a folder <code>assets</code> in the application directory. When I go to the main page (<code>/</code>), the static files are being loaded perfectly fine from <code>/assets/</code>. If I go to <code>/house/</code>, it tries to load the static files from <code>/house/assets/</code>, which obv...
<p>You should change the HTML tag in your template from</p> <pre><code>&lt;link href="assets/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css"/&gt; </code></pre> <p>to</p> <pre><code>&lt;link href="/assets/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css"/&...
python|django|django-views|django-staticfiles
4
8,373
22,636,333
Raster and world file import to ArcGis, What are the map units?
<p><strong>In short:</strong> I thought the map units would be in meter or km, but this doesn't seem right. Are they in decimal degrees? Can this be set as an option in ArcGis?</p> <hr> <p>Hi, </p> <p>I'm cooperating with a researcher using ArcGIS to overlay some computer vision images on a map. I've created a world...
<blockquote> <p>In short: I thought the map units would be in meter or km, but this doesn't seem right. Are they in decimal degrees? Can this be set as an option in ArcGis?</p> </blockquote> <p>Look at your first picture, bottom left. Obviously map units are in decimal degrees. Map units depends on coordinate system...
python|arcgis|raster
0
8,374
45,357,862
Scipy optimize newton secant method
<p>Scipy optimize.newton has initial step size hard-coded as 1e-4. What's the best way to utilize this function with a different step size (ideally, specified as a parameter)?</p> <pre><code># https://github.com/scipy/scipy/blob/v0.19.0/scipy/optimize/zeros.py#L160 else: # Secant method p0 = x0 if x0 &gt;...
<p>The initial step size is not <code>1e-4</code>, it is <code>abs(x0)*1e-4 + 1e-4</code>. For example, x0 = 1000 will result in the initial step 0.1001. </p> <p>If the goal is to have certain initial step size <code>h</code>, that can be achieved with a linear change of variable, <code>x = x0 + 1e4*h*t</code> where <...
python|optimization|scipy|newtons-method
2
8,375
45,309,892
Redirect output to file after os.exec*
<p>I have a python script, whose output is piped into a log file. I can restart the file from within with an os.exec call, but if i do that, the new process doesnt write its output into the log file. How can i keep the output redirection after restarting the process?</p> <p>My script start:</p> <pre><code>python3.6 s...
<p>I can't reproduce this problem. Here's my <code>first.py</code>:</p> <pre><code>import os import sys os.execv(sys.executable, [sys.executable, "second.py"]) </code></pre> <p>Here's <code>second.py</code>:</p> <pre><code>print("Hello") </code></pre> <p>Here's how I run it and check the result. As you can see, it ...
python|linux
0
8,376
6,752,763
Python "if modified since" detection?
<p>I wrote some code to tackle a work-related problem. The idea is that the program is in an infinite loop and every 10 minutes it checks a certain folder for new files and if there are any, it copies them to another folder. My code reads all the files in the folder and drops the list into a txt file. After 10 minutes ...
<p>The cleanest solution is file alteration monitoring. See <a href="https://stackoverflow.com/questions/597903/monitoring-files-directories-with-python">this question</a> for information for both *ix and Windows. To summarize, on Linux, you could use libfam, and Windows has <code>FindFirstChangeNotification</code> a...
python
2
8,377
23,768,612
Python, can i get a return true or false, if a file TYPE exists or not?
<p>ive read through the path.exists() and path.isdir() questions on here, but none that ive found so far, deal with check if a particular file type exists in a directory or not... maybe im not searching the correct terms for this. </p> <p>basically, i want to poll a set of folders to see if there are txt files there.....
<p>You want to use <a href="https://docs.python.org/2/library/glob.html" rel="nofollow noreferrer"><code>glob</code></a>.</p> <pre><code>import glob if glob.glob("/mnt/path/to/shared/folder/*.txt"): # there are text files else: # No text files </code></pre> <p>Glob will return a list of files matching the wi...
python
6
8,378
36,030,963
Dot product along third axis
<p>I'm trying to take a tensor dot product in numpy using <code>tensordot</code>, but I'm not sure how I should reshape my arrays to achieve my computation. (I'm still new to the mathematics of tensors, in general.)</p> <p>I have</p> <pre><code>arr = np.array([[[1, 1, 1], [0, 0, 0], [2...
<p>The reduction is along <code>axis=2</code> for <code>arr</code> and <code>axis=0</code> for <code>w</code>. Thus, with <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.tensordot.html" rel="noreferrer"><code>np.tensordot</code></a>, the solution would be -</p> <pre><code>np.tensordot(arr,w,a...
python|numpy|tensor|dot-product
18
8,379
46,625,750
Fitting an un-normalised distribution with scipy.stats
<p>I'm tryng to fit a histogram but the fit only works with normalised data, i.e. with option <code>normed=True</code> in the histogram. Is there a way of doing this with scipy stats (or other method)? Here is a MWE using a uniform distribution:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import ...
<p>Note that it is generally a bad idea to fit a distribution to the histogram. Compared to the raw data the histogram contains less information so the fit will most likely be worse. Thus, the first MWE in the question actually contains the best approach. Simply normalize the histogram and it will match the distributio...
python|scipy|data-fitting
3
8,380
46,271,729
feature extraction in python for nlp
<p>I am trying to extract features like "delhi police" , "newyork police" using python regular expression. in short city and police name separated by space. so city name will be differed and "police" will be constant.</p> <p>Can I do using named entity recognition for location + "police" as a constant.</p> <p>if ye...
<pre><code>import re test_string = "The New York Police, New Delhi police and other police departments are fighting crime".lower() cities = ['new delhi', 'new york'] regex = "(("+"|".join(cities)+") police)" regex = regex.lower() results = re.findall(regex, test_string) print([res[0] for res in results]) #['new york po...
python|regex|nlp
0
8,381
49,563,042
Is it possible to achieve this without defining a function?
<p>I'm trying to write a Python program which would take a string and print the longest substring in it which is also in alphabetical order. For example:</p> <p>the_string = "abcdefgghhisdghlqjwnmonty" The longest substring in alphabetical order here would be "abcdefgghhis"</p> <p>I'm not allowed to define my own fun...
<p>just going by your code you can move the operation of the function into the loop and use a variable to store what would have been the return value.</p> <p>I would recommend listening to bill the lizard to help with the way you solve the problem</p> <pre><code>s = "somestring" count = 0 longest_string = '' for ch...
python|python-3.x
2
8,382
62,574,955
Obtaining a list of JSONs with re.split
<p>I'm trying to parse a string containing multiple json objects using the re.split method. However I can't find a pattern that works as I want.</p> <p><strong>Received string</strong></p> <pre><code>'{&quot;project&quot;:&quot;rapidjson&quot;,&quot;stars&quot;:10}{&quot;project&quot;:&quot;rapidjson&quot;,&quot;stars&...
<p>Expression <code>'(?&lt;=})'</code> working for it, which means that you are looking for every pattern that ends with <code>}</code>. See <a href="https://docs.python.org/2/library/re.html" rel="nofollow noreferrer">positive lookbehind assertion</a>.</p> <p><strong>Actual result</strong></p> <pre><code>['{&quot;proj...
python|string|parsing|split|python-re
2
8,383
53,419,142
python REST server PUT does not update value
<p>I have python REST server running and i am trying to update a string via PUT method and after that use a GET method (different client) to retrieve said updated string. But the problem is that GET method gets the old string( in this case "0"). Which one of the methods might be wrong?</p> <pre><code>from flask import...
<p>The <code>get_bad_packets()</code> function only knows about the <em>global</em> variable named <code>badpackets</code>. The variable of the same name inside the <code>post_bad_packets()</code> function is a <em>local</em> variable.</p> <p>If you want to change the value of a global variable inside a function, use...
python|rest|get|put
0
8,384
45,778,860
How can i use internal iteration within function in python?
<p>I need this code to run : </p> <pre><code>pp = ["first", "second", "third"] sum(d for d in pp) </code></pre> <p>I get the <code>error</code>:</p> <pre><code>TypeError: unsupported operand type(s) for +: 'int' and 'str' </code></pre> <p>I guess there is something to do with lazy evaluation. Could you please help ...
<p><code>sum()</code> buildin function that is by default <code>start</code> is <code>0</code>. It takes only numbers and return the total. It is not allowed <code>string</code>. So, you get above <code>error</code>. Rather, you can join the list using <code>''.join()</code> function.</p> <p>Like : </p> <pre><code>...
python
1
8,385
54,801,043
python making a post file request
<p>Hi guys I'm developing a Python 3 quart asyncio application and I'm trying to setup a test framework around my http API.</p> <p>Quart has methods to build json, form and raw requests but no files request. I believe I need build the request packet myself and post a "raw" request. Using postman I can see that the req...
<p>Python's requests module provides a prepare function that you can use to get the raw data it would send for the request.</p> <pre><code>import requests url = 'http://localhost:8080/' files = {'file' : open('z', 'rb'), 'file2': open('zz', 'rb')} req = requests.Request('POST',url, files=files) r = req.pre...
python|python-asyncio|quart
0
8,386
33,130,097
Python all combinations of a list of lists
<p>So I have a list of lists of strings</p> <pre><code>[['a','b'],['c','d'],['e','f']] </code></pre> <p>and I want to get all possible combinations, such that the result is</p> <pre><code>[['a','b'],['c','d'],['e','f'], ['a','b','c','d'],['a','b','e','f'],['c','d','e','f'], ['a','b','c','d','e','f']] </code></pre>...
<p>You can use <a href="https://docs.python.org/2/library/itertools.html#itertools.chain.from_iterable" rel="nofollow"><code>itertools.chain.from_iterable</code></a> to flatten the tuple of lists into a list. Example -</p> <pre><code>import itertools input = [['a','b'],['c','d'],['e','f']] combs = [] for i in xrange(1...
python|list|tuples|combinations|itertools
7
8,387
13,097,807
Accessing specific python defaultdict
<p>Say I have a defaultdict with values:</p> <pre><code>x = defaultdict(int) x[a,1] = 1 x[a,2] = 2 x[a,3] = 3 x[b,1] = 4 x[b,2] = 5 x[b,3] = 6 x[c,1] = 7 x[c,2] = 8 x[c,3] = 9 </code></pre> <p>How do I access only those elements with the first index as c</p> <p>Or rather, how do I implement something like this:</p> ...
<p>Defaultdicts, like ordinary dicts, don't have any special slicing behavior on the keys. The keys are just objects, and in your case they're just tuples. The dict doesn't know or enforce anything about the internal structure of the keys. (It's possible to have different keys with different lengths, for instance.) ...
python|defaultdict
1
8,388
13,199,329
Python dynamically created custom named functions
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/13184281/python-dynamic-function-creation-with-custom-names">Python dynamic function creation with custom names</a> </p> </blockquote> <p>I have written a little script to determine whether what I wanted to do ...
<p>In Python this is the most reasonable approach for generic metaprogramming.</p> <p>If you need just some constants in the code then however a closure may do the trick... for example:</p> <pre><code>def multiplier(k): "Returns a function that multiplies the argument by k" def f(x): return x*k re...
python|python-2.7|metaprogramming|dynamic-function
1
8,389
41,174,831
Telegram Bot "chat not found"
<p>I have the following code in Python to send a message to myself from a bot.</p> <pre><code>import requests token = '123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHI' method = 'sendMessage' myuserid = 1949275XX response = requests.post( url='https://api.telegram.org/bot{0}/{1}'.format(token, method), data={'cha...
<p>As @maak pointed out, you need to first send a message to the bot before the bot can send messages to you.</p>
python|python-requests|telegram|telegram-bot
32
8,390
40,293,967
matplotlib: space between point and decimal digits in TeX mode
<p>Why has matplotlib inserted a space between the decimal digit and the point in the legend? How do I get rid of it?</p> <pre><code>import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 1, 100) y = np.sin(x) plt.plot(x, y, label='$a = 1.0$') plt.legend(loc='lower right') plt.show() </code></pre> <p>...
<p>It seem to be a <a href="https://github.com/matplotlib/matplotlib/issues/4335/" rel="nofollow">bug</a> in matplotlib. As far as I understand, the fix is available but not yet merged with the default branch.</p> <p>As for now, you can use <code>usetex</code> option to use the real TeX (if it is available in your env...
python|matplotlib
3
8,391
39,955,222
Mapping Python list values to dictionary values
<p>I have a list of rows...</p> <p><code>rows = [2, 21]</code></p> <p>And a dictionary of data...</p> <p><code>data = {'x': [46, 35], 'y': [20, 30]}</code></p> <p>I'd like to construct a second dictionary, <code>dataRows</code>, keyed by the row that looks like this...</p> <p><code>dataRows = {2: {'x': 46, 'y': 20...
<p>Your issue is that you are not puting sub-dictionaries inside dataRows. The fix would be this:</p> <pre><code>for i, row in enumerate(rows): dataRows[row] = {} for key, value in data.items(): dataRows[row][key] = value[i] </code></pre>
python
7
8,392
8,933,872
Loop on Select_Analysis tool (Python and ArcGIS 9.3)
<p>First, I'm new in Python and I work on Arc GIS 9.3.</p> <p>I'd like to realize a loop on the "Select_Analysis" tool. Indeed I have a layer "stations" composed of all the bus stations of a city. The layer has a field "rte_id" that explains on what line a station is located.</p> <p>And I'd like to save in distinct l...
<p>You will need to make substantial changes to this code in order to get it to do what you want. You may just want to download the <a href="http://arcscripts.esri.com/details.asp?dbid=14127" rel="nofollow">Split Layer By Attribute</a> Code from ArcGIS online which does the exact same thing. </p>
python|loops|arcgis|arcpy
1
8,393
58,719,800
I want to change for to while
<p>I want to write this code using <code>while</code> loop, not <code>for</code> loop I tried doing everything, turning dict to list and then removing items but it didn't work.</p> <pre><code>Journal = {12: 'ASUS', 2: 'HP', 57: 'IBM', 3: 'DELL', 689: 'APPLE'} inputi = input("five keys ").split(",") num = len(inputi) f...
<h2>Original For-Loop:</h2> <pre><code>for keys, values in list(Journal.items()): Journal.pop(keys) num -= 1 Journal[inputi[num]] = values </code></pre> <h2>A While-Loop Equivalent:</h2> <pre><code>jit = Journal.items() while(True): try: key, value = next(jit) except StopIteration: ...
python
0
8,394
51,903,087
Understanding the most_similar method for an AnnoyIndexer in gensim.similarities.index
<p>So I have made an AnnoyIndexer and am running some most_similar queries to find the nearest neighbours of some vectors in a 300dimensional vector space. This is the code for it:</p> <pre><code>def most_similar(self, vector, num_neighbors): """Find the approximate `num_neighbors` most similar items. Paramete...
<p>From the documentation of gensim:</p> <pre><code>"List of most similar items in format [(`item`, `cosine_distance`), ...]" </code></pre> <p>The distances returned by the AnnoyIndex are the euclidean distance between the vectors. So the method needs to transform the euclidean distances in cosine distances. The cosi...
python|nlp|gensim|word2vec|annoy
3
8,395
51,705,583
Pandas resample timeseries data to 15 mins and 45 mins - using multi-index or column
<p>I have some timeseries data as a Pandas dataframe which starts off with observations at 15 mins past the hour and 45 mins past (time intervals of 30 mins) then changes frequency to every minute. I want to resample the data so that it has a regular frequency of every 30 minutes, at 15 past and 45 past the hours for t...
<p>Starting from your second last dataframe (after using <code>weather.reset_index(Station, inplace=True)</code>):</p> <pre><code> Station Pressure Temp Hum parsed_time 2018-04-15 14:15:00 Bow 1012.0 20.0 87.0 2018-04-15 14:45:00 ...
python|pandas|dataframe|time-series|multi-index
5
8,396
18,779,118
Testing an executable in a Python package
<p>I'm a Ruby programmer working on my first Python package (let's call it <strong>foo</strong>). Its primary purpose is as a command line tool. I'm specifying that it should be installed as an executable in <code>setup.py</code> using: </p> <pre><code>setup( entry_points={ 'console_scripts': [ ...
<p>Within the package, you can directly import <code>__init__</code> and then rename with <code>as</code>. Try this</p> <pre><code>import __init__ as foo </code></pre> <p>in place of </p> <pre><code>import foo </code></pre>
python|command-line-interface|package|setuptools|python-module
1
8,397
62,439,711
Creating a subclass of int, unexpected behaviour with json.dumps()
<p>I'm trying to create a subclass of <code>int</code> that prints as a string but can still be used as a math variable.</p> <p>This is what I have so far:</p> <pre><code>class xint(int): def __new__(self, value): self.value = value return super(xint, self).__new__(self) def __str__(self): ...
<p>This example fixes your mistakes, but it doesn't solve your problem:</p> <pre><code>import json class Xint(int): def __str__(self): return f"'{int(self)}'" # I'm leaving this in, but I think it's wrong # a representation like f'Xint({int(self)})' would be better __repr__ = __str__ x = X...
python|json
1
8,398
67,494,105
Error in ceres when trying to install opencv-python on Mac m1
<p>I am trying to install opencv-python on the Mac m1.</p> <p>I have followed the instructions here:</p> <p><a href="https://sayak.dev/install-opencv-m1/" rel="nofollow noreferrer">https://sayak.dev/install-opencv-m1/</a></p> <p>However I am getting an error in a c++ library when running the make -j8 command:</p> <pre>...
<p>I think the error was in the CMakeLists.txt in the opencv repo.</p> <p>I had to edit this file and set(CMAKE_CXX_STANDARD 14) to get it to work</p>
python|c++|opencv
1
8,399
36,605,073
Removing cycles from an undirected multi graph using Python networkx
<p>So I have a undirected multi graph (derived from an ontology), I wish to remove the edges that create cycles (but not all edges, the constituents of the multi graph have to remain connected). Is there a good way of doing this with the networkx package?</p>
<p>There may not be a unique way to do that for your graph. But maybe finding a spanning tree will solve your problem? <a href="https://networkx.github.io/documentation/latest/reference/generated/networkx.algorithms.mst.minimum_spanning_tree.html" rel="nofollow">https://networkx.github.io/documentation/latest/referenc...
python|graph|networkx
2