Dataset Viewer
input_text_instruct
stringlengths 282
37.9k
| output_text
stringlengths 37
27.3k
|
---|---|
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
GPFlow Multiclass classification with vector inputs causes value error on shape mismatch<p>I am trying to follow the Multiclass classification in GPFlow (using v2.1.3) as described here:</p>
<p><a href="https://gpflow.readthedocs.io/en/master/notebooks/advanced/multiclass_classification.html" rel="nofollow noreferrer">https://gpflow.readthedocs.io/en/master/notebooks/advanced/multiclass_classification.html</a></p>
<p>The difference with the example is that the <em>X</em> vector is 10-dimensional and the number of classes to predict is 5. But there seems to be error in dimensionality when using the inducing variables. I changed the kernel and use dummy data for reproducability, just looking to get this code to run. I put the dimensions of the variables in case that is the issue. Any calculation of loss causes an error like:</p>
<pre><code> ValueError: Dimensions must be equal, but are 10 and 5 for '{{node truediv}} = RealDiv[T=DT_DOUBLE](strided_slice_2, truediv/softplus/forward/IdentityN)' with input shapes: [200,10], [5].
</code></pre>
<p>It is as if it requires the <em>Y</em> results for the inducing variables, but the example on the gpflow site does not require it or it is confusing the length of the <em>X</em> input with the number of classes to predict.</p>
<p>I tried expanding the dimension of <em>Y</em> as in <a href="https://stackoverflow.com/questions/68419128/gpflow-classification-implementation">gpflow classification implementation</a>, but did not help.</p>
<p>Reproducible Code:</p>
<pre class="lang-py prettyprint-override"><code>import gpflow
from gpflow.utilities import ops, print_summary, set_trainable
from gpflow.config import set_default_float, default_float, set_default_summary_fmt
from gpflow.ci_utils import ci_niter
import random
import numpy as np
import tensorflow as tf
np.random.seed(0)
tf.random.set_seed(123)
num_classes = 5
num_of_data_points = 1000
num_of_functions = num_classes
num_of_independent_vars = 10
data_gp_train = np.random.rand(num_of_data_points, num_of_independent_vars)
data_gp_train_target_hot = np.eye(num_classes)[np.array(random.choices(list(range(num_classes)), k=num_of_data_points))].astype(bool)
data_gp_train_target = np.apply_along_axis(np.argmax, 1, data_gp_train_target_hot)
data_gp_train_target = np.expand_dims(data_gp_train_target, axis=1)
data_gp = ( data_gp_train, data_gp_train_target )
lengthscales = [0.1]*num_classes
variances = [1.0]*num_classes
kernel = gpflow.kernels.Matern32(variance=variances, lengthscales=lengthscales)
# Robustmax Multiclass Likelihood
invlink = gpflow.likelihoods.RobustMax(num_of_functions) # Robustmax inverse link function
likelihood = gpflow.likelihoods.MultiClass(num_of_functions, invlink=invlink) # Multiclass likelihood
inducing_inputs = data_gp_train[::5].copy() # inducing inputs (20% of obs are inducing)
# inducing_inputs = data_gp_train[:200,:].copy() # inducing inputs (20% of obs are inducing)
m = gpflow.models.SVGP(
kernel=kernel,
likelihood=likelihood,
inducing_variable=inducing_inputs,
num_latent_gps=num_of_functions,
whiten=True,
q_diag=True,
)
set_trainable(m.inducing_variable, False)
print_summary(m)
opt = gpflow.optimizers.Scipy()
opt_logs = opt.minimize(
m.training_loss_closure(data_gp), m.trainable_variables, options=dict(maxiter=ci_niter(1000))
)
print_summary(m, fmt="notebook")
</code></pre>
<p>Dimensions:</p>
<pre><code>data_gp[0].shape
Out[132]: (1000, 10)
data_gp[1].shape
Out[133]: (1000, 5)
inducing_inputs.shape
Out[134]: (200, 10)
</code></pre>
<p>The error:</p>
<pre><code> ValueError: Dimensions must be equal, but are 10 and 5 for '{{node truediv}} = RealDiv[T=DT_DOUBLE](strided_slice_2, truediv/softplus/forward/IdentityN)' with input shapes: [200,10], [5].
</code></pre> | <p>When running your example I get a slightly different bug, but the issue is in how you define lengthscales and variances. You write:</p>
<pre class="lang-py prettyprint-override"><code>lengthscales = [0.1]*num_classes
variances = [1.0]*num_classes
kernel = gpflow.kernels.Matern32(variance=variances, lengthscales=lengthscales)
</code></pre>
<p>But the standard kernels require a scalar variance and the lengthscales to be a scalar or to match the number of <em>features</em>, so if you replace that code with the following:</p>
<pre class="lang-py prettyprint-override"><code>lengthscales = [0.1]*num_of_independent_vars
kernel = gpflow.kernels.Matern32(variance=1.0, lengthscales=lengthscales)
</code></pre>
<p>then it all runs fine.</p>
<p>This would give you a <em>shared</em> kernel for each output (class probability) with <em>independent</em> lengthscales per input dimension ("ARD").</p>
<p>If you want different kernels for each output (but, for example, isotropic lengthscale), you can achieve this with a <code>SeparateIndependent</code> multi-output kernel, see the <a href="https://gpflow.readthedocs.io/en/master/notebooks/advanced/multioutput.html#2.-Separate-independent-MOK-and-shared-independent-inducing-variables" rel="nofollow noreferrer">multioutput notebook example</a>.</p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
How to store the outcome of a method<p>I am trying to draw squares in random positions and random rgb values and I want 1000 of them to be created. The problem I'm facing is that everytime the loop for drawing occurs, it randomizes it all again, is there any way to make this not happen</p>
<pre><code>import pygame
import sys
import random
pygame.init()
win = pygame.display.set_mode((800,600))
pygame.display.set_caption("Simulation")
def safeZone():
#Draws a top rectangle
pygame.draw.rect(win, (50,205,50), (0, 0, 800, 100))
def dot():
width = 10
height = 10
spawnX = random.randrange(1, 801)
spawnY = random.randrange(1, 601)
r = random.randrange(1, 256)
g = random.randrange(1, 256)
b = random.randrange(1, 256)
pygame.draw.rect(win, (r, g, b), (spawnX, spawnY, width, height))
def population(size):
for x in range(size):
dot()
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
win.fill((255, 255, 255))
safeZone() # Always draw dots after safe zone
population(1000)
pygame.display.update()
pygame.quit()
</code></pre> | <p>Create a dot collection, then just draw that dot collection. Now you can update the dot positions separately, and they will redraw in the new positions. Here, I'm having each dot move a random amount in every loop.</p>
<pre><code>import pygame
import sys
import random
pygame.init()
win = pygame.display.set_mode((800,600))
pygame.display.set_caption("Simulation")
class Dot:
def __init__(self):
self.spawnX = random.randrange(0, 800)
self.spawnY = random.randrange(0, 600)
self.r = random.randrange(0, 256)
self.g = random.randrange(0, 256)
self.b = random.randrange(0, 256)
def safeZone():
#Draws a top rectangle
pygame.draw.rect(win, (50,205,50), (0, 0, 800, 100))
def drawdot(dot):
width = 10
height = 10
pygame.draw.rect(win, (dot.r, dot.g, dot.b), (dot.spawnX, dot.spawnY, width, height))
def population(dots):
for dot in dots:
dot.spawnX += random.randrange(-3,4)
dot.spawnY += random.randrange(-3,4)
drawdot(dot)
alldots = [Dot() for _ in range(1000)]
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
win.fill((255, 255, 255))
safeZone() # Always draw dots after safe zone
population(alldots)
pygame.display.update()
</code></pre>
<p>A worthwhile modification is to store the whole rectangle in the object:</p>
<pre><code>...
class Dot:
def __init__(self):
self.location = [
random.randrange(0, 800),
random.randrange(0, 600),
10, 10
]
self.color = (
random.randrange(0, 256),
random.randrange(0, 256),
random.randrange(0, 256)
)
def move(self, dx, dy ):
self.location[0] += dx
self.location[1] += dy
def drawdot(dot):
pygame.draw.rect(win, dot.color, dot.location)
def population(dots):
for dot in dots:
dot.move( random.randrange(-3,4), random.randrange(-3,4) )
drawdot(dot)
...
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Subtraction assignment gives 0 and not a negative number<p>I'm messing around with probability and I'm simulating something where a user can bet <code>x</code> amount, if the user loses I want it to drain their overall "<code>bank</code>". If they win it adds money.</p>
<p>As you can see in the code when they win the money gets "added" using <code>+=</code> but how can I do this so the number becomes a negative when they lose (for example <code>-=</code>, that didn't work for me).</p>
<p>Code</p>
<pre class="lang-py prettyprint-override"><code>import random
def get_possible(x):
return random.randrange(x)
def loop(possibilities, number, loop, bet):
success = 0
fail = 0
for i in range(loop):
if get_possible(x=possibilities) == number:
success += 1
bet += bet * 8
else:
fail += 1
bet -= bet
print("Success: " + str(success))
print("Fail: " + str(fail))
print("Total earned: " + str(bet))
loop(possibilities=14, number=1, loop=100, bet=100)
</code></pre>
<p>Here when they lose it says the total earned is <code>0</code>, I want it to say <code>- bet_amount</code></p> | <p>Introduce a new variable sum</p>
<pre><code>def loop(possibilities, number, loop, bet):
success = 0
fail = 0
sum = 0
for i in range(loop):
if get_possible(x=possibilities) == number:
success += 1
sum += bet * 8
else:
fail += 1
sum -= bet
print("Success: " + str(success))
print("Fail: " + str(fail))
print("Total earned: " + str(sum))
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
mean of a column in pandas dataframe when the 'count' value is total<p>I have a dataframe like this</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody>
<tr>
<td>yes</td>
<td>4</td>
</tr>
<tr>
<td>yes</td>
<td>3</td>
</tr>
<tr>
<td>yes</td>
<td>3</td>
</tr>
<tr>
<td>total</td>
<td>nan</td>
</tr>
<tr>
<td>yes</td>
<td>5</td>
</tr>
<tr>
<td>yes</td>
<td>5</td>
</tr>
<tr>
<td>total</td>
<td>nan</td>
</tr>
</tbody>
</table>
</div>
<p>Desired output when the value of count column is total then replace the nan with mean of above values that is 4+3+3/3 ,, 5+5/2</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody>
<tr>
<td>yes</td>
<td>4</td>
</tr>
<tr>
<td>yes</td>
<td>3</td>
</tr>
<tr>
<td>yes</td>
<td>3</td>
</tr>
<tr>
<td>total</td>
<td>3.33</td>
</tr>
<tr>
<td>yes</td>
<td>5</td>
</tr>
<tr>
<td>yes</td>
<td>5</td>
</tr>
<tr>
<td>total</td>
<td>5.0</td>
</tr>
</tbody>
</table>
</div> | <p>Let's load the data</p>
<pre><code>from io import StringIO
data = StringIO(
"""
A B
yes 4
yes 3
yes 3
total nan
yes 5
yes 5
total nan
""")
df = pd.read_csv(data, delim_whitespace=True)
df['B'] = df['B'].astype('float')
</code></pre>
<p>First we calculate the mean by group -- groups are defined as being separated by NaN</p>
<pre><code>dfm = df.groupby((df['B'].shift().isna()).cumsum(), as_index = False).mean()
dfm
</code></pre>
<p>we get</p>
<pre><code>
B
0 3.333333
1 5.000000
</code></pre>
<p>now we can asign these to the right cells in df:</p>
<pre><code>df.loc[df['A'] == 'total','B'] = dfm['B'].values
df
</code></pre>
<p>for the end result</p>
<pre><code>
A B
0 yes 4.000000
1 yes 3.000000
2 yes 3.000000
3 total 3.333333
4 yes 5.000000
5 yes 5.000000
6 total 5.000000
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Python subprocess terminal/space need to be adjusted to a value other than 80/24<p>I am working on invoking and executable as a part of script in python using subprocess.Popen. <code>subprocess.Popen(command,stdin=subprocess.PIPE, stdout=subprocess.PIPE)</code>. The executable need to open in a subprocess terminal/window/space larger than 80/24 else the results get truncated. I need to adjust the input/flags to subprocess so that columns number is changed. I have tried <code>env= {'COLUMNS':'300'}</code> but that doesn't help.</p>
<p>I use python 2.7 </p> | <p><code>subprocess.Popen(command,stdin=subprocess.PIPE, stdout=subprocess.PIPE)</code> executes a command and returns the result text.</p>
<pre><code>import os
command = "some command"
res = os.popen(command).read() # get all content as text
res = list(os.popen(command)) # get lines as array elements
</code></pre>
<p>To change the terminal size, use</p>
<pre><code>import os
rows = raw_input("rows: ")
cols = raw_input("cols: ")
os.system("resize -s {row} {col}".format(row=rows, col=cols))
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Dictionary of Words as keys and the Sentences it appears in as values<p>I have a text which I split into a list of unique words using set. I also have split the text into a list of sentences. I then split that list of sentences into a list of lists (of the words in each sentence / maybe I don't need to do the last part)</p>
<pre><code>text = 'i was hungry. i got food. now i am not hungry i am full'
sents = ['i was hungry', 'i got food', 'now i am', 'not hungry i am full']
words = ['i', 'was', 'hungry', 'got', 'food', 'now', 'not', 'am', 'full']
split_sents = [['i', 'was', 'hungry'], ['i', 'got', 'food'], ['now', 'i', 'am', 'not','hungry','i','am','full']]
</code></pre>
<p>I want to write a loop or a list comprehension that makes a dictionary where each word in words is a key and if the word appears in a sentence each sentence is captured as a list value so I can then get some statistics like the count of sentences but also the average length of the sentences for each word...so far I have the following but it's not right.</p>
<pre><code>word_freq = {}
for sent in split_sents:
for word in words:
if word in sent:
word_freq[word] += sent
else:
word_freq[word] = sent
</code></pre>
<p>it returns a dictionary of word keys and empty values. Ideally, I'd like to do it without collections/counter though any solution is appriciated. I'm sure this question has been asked before but I couldn't find the right solution so feel free to link and close if you link to a solution.</p> | <p>Here is an approach using list and dictionary comprehension</p>
<p><strong>Code:</strong></p>
<pre><code>text = 'i was hungry. i got food. now i am not hungry i am full'
sents = ['i was hungry', 'i got food', 'now i am', 'not hungry i am full']
words = ['i', 'was', 'hungry', 'got', 'food', 'now', 'not', 'am', 'full']
word_freq = {w:[s for s in sents if w in s.split()] for w in words }
print(word_freq)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>{
'i': ['i was hungry', 'i got food', 'now i am', 'not hungry i am full'],
'was': ['i was hungry'], '
hungry': ['i was hungry', 'not hungry i am full'],
'got': ['i got food'],
'food': ['i got food'],
'now': ['now i am'],
'not': ['not hungry i am full'],
'am': ['now i am', 'not hungry i am full'],
'full': ['not hungry i am full']
}
</code></pre>
<p><strong>Or if you want output sentences as list of words:</strong></p>
<pre><code>word_freq = {w:[s.split() for s in sents if w in s.split()] for w in words }
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>{
'i': [['i', 'was', 'hungry'], ['i', 'got', 'food'], ['now', 'i', 'am'], ['not', 'hungry', 'i', 'am', 'full']],
'was': [['i', 'was', 'hungry']],
'hungry': [['i', 'was', 'hungry'], ['not', 'hungry', 'i', 'am', 'full']],
'got': [['i', 'got', 'food']],
'food': [['i', 'got', 'food']],
'now': [['now', 'i', 'am']],
'not': [['not', 'hungry', 'i', 'am', 'full']],
'am': [['now', 'i', 'am'], ['not', 'hungry', 'i', 'am', 'full']],
'full': [['not', 'hungry', 'i', 'am', 'full']]}
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
efficient way to check every value in a 2d python array<p>I have a 2D numpy array of values, a list of x-coordinates, and a list of y-coordinates. the x-coordinates increase left-to-right and the y-coordinates increase top-to-bottom.</p>
<p>For example:</p>
<pre><code>a = np.random.random((3, 3))
a[0][1] = 9.0
a[0][2] = 9.0
a[1][1] = 9.0
a[1][2] = 9.0
xs = list(range(1112, 1115))
ys = list(range(1109, 1112))
</code></pre>
<p>Output:</p>
<pre><code>[[0.48148651 9. 9. ]
[0.09030393 9. 9. ]
[0.79271224 0.83413552 0.29724989]]
[1112, 1113, 1114]
[1109, 1110, 1111]
</code></pre>
<p>I want to remove the values from the 2D array that are greater than 1. I also want to combine the lists <code>xs</code> and <code>ys</code> to get a list of all the coordinate pairs for points that are kept.</p>
<p>In this example I want to remove <code>a[0][1], a[0][2], a[1][1], a[1][2]</code> and I want the list of coordinate pairs to be</p>
<pre><code>[[1112, 1109], [1112,1110], [1112, 1111], [1113, 1111], [1114, 1111]]
</code></pre>
<p>I have been able to accomplish this using a double <code>for</code> loop and <code>if</code> statements:</p>
<pre><code>a_values = []
point_pairs = []
for i in range(0, a.shape[0]):
for j in range(0, a.shape[1]):
if (a[i][j] < 1):
a_values.append(a[i][j])
point_pairs.append([xs[j], ys[i]])
print(a_values)
print(point_pairs)
</code></pre>
<p>Output:</p>
<pre><code>[0.48148650831317796, 0.09030392566133771, 0.7927122386213029, 0.8341355206494774, 0.2972498933037804]
[[1112, 1109], [1112, 1110], [1112, 1111], [1113, 1111], [1114, 1111]]
</code></pre>
<p>What is a more efficient way of doing this?</p> | <p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.nonzero.html" rel="nofollow noreferrer"><code>np.nonzero</code></a> to get the indices of the elements you removed:</p>
<pre><code>mask = a < 1
i, j = np.nonzero(mask)
</code></pre>
<p>The fancy indices <code>i</code> and <code>j</code> can be used to get the elements of <code>xs</code> and <code>ys</code> directly if they are numpy arrays:</p>
<pre><code>xs = np.array(xs)
ys = np.array(ys)
point_pairs = np.stack((xs[j], ys[i]), axis=-1)
</code></pre>
<p>You can also use <a href="https://numpy.org/doc/stable/reference/generated/numpy.take.html" rel="nofollow noreferrer"><code>np.take</code></a> to make the conversion happen under the hood:</p>
<pre><code>point_pairs = np.stack((np.take(xs, j), np.take(ys, i)), axis=-1)
</code></pre>
<p>The remaining elements of <code>a</code> are those not covered by the mask:</p>
<pre><code>a_points = a[mask]
</code></pre>
<p>Alternatively:</p>
<pre><code>i, j = np.nonzero(a < 1)
point_pairs = np.stack((np.take(xs, j), np.take(ys, i)), axis=-1)
a_points = a[i, j]
</code></pre>
<p>In this context, you can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a> as a drop-in alias for <code>np.nonzero</code>.</p>
<p><strong>Notes</strong></p>
<ul>
<li><p>If you are using numpy, there is rarely a need for lists. Putting <code>xs = np.array(xs)</code>, or even just initializing it as <code>xs = np.arange(1112, 1115)</code> is faster and easier.</p>
</li>
<li><p>Numpy arrays should generally be indexed through a single index: <code>a[0, 1]</code>, not <code>a[0][1]</code>. For your simple case, the behavior just happens to be the same, but it will not be in the general case. <code>a[0, 1]</code> is an index into the original array. <code>a[0]</code> is a view of the first row of the array, i.e., a separate array object. <code>a[0][1]</code> is an index into that new object. You just happened to get lucky that you are getting a view that shares the base memory, so the assignment is visible in <code>a</code> itself. This would not be the case if you tried a mask or fancy index, for example.</p>
</li>
<li><p>On a related note, setting a rectangular swath in an array only requires one line: <code>a[1:, :-1] = 9</code>.</p>
</li>
</ul>
<p>I would write your example something like this:</p>
<pre><code>a = np.random.random((3, 3))
a[1:, :-1] = 9.0
xs = np.arange(1112, 1115)
ys = np.arange(1109, 1112)
i, j = np.nonzero(a < 1)
point_pairs = np.stack((xs[j], ys[i]), axis=-1)
a_points = a[i, j]
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Tests in Python of a class that requests to REST API<p>I am working in a desktop client application that accesses the OneDrive (Microsoft Graph) REST API to download and upload files.
The Onedrive class checks if the access token needs to be renewed before each request.</p>
<p>Should I unit test this class? Is there a way to mock these requests?</p>
<p>Here is the source code of the class:</p>
<pre class="lang-py prettyprint-override"><code>import json
from datetime import datetime, timedelta
from urllib.request import Request, urlopen
TOKEN_URL = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'
DRIVE_BY_ID_URL = 'https://graph.microsoft.com/v1.0/drives/'
CLIENT_ID = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
class Onedrive:
def __init__(self, access_token, refresh_token, expire_date):
self._access_token = access_token
self._refresh_token = refresh_token
self._expire_date = expire_date
self.timeout = 5
def download(self, drive_id, file_id, filename):
self._renew_token()
url = f'{DRIVE_BY_ID_URL}/{drive_id}/items/{file_id}/content?AVOverride=1'
with open(filename, 'wb+') as fp:
headers = {'Authorization': self._access_token}
request = Request(url, headers=headers)
with urlopen(request, timeout=self.timeout) as response:
fp.write(response.read())
def upload(self, local_path, parent_drive_id, parent_id, filename):
self._renew_token()
url = f'{DRIVE_BY_ID_URL}/{parent_drive_id}/items/{parent_id}:/{filename}:/content'
headers = {'Authorization': self._access_token, "Content-Type": "application/octet-stream"}
with open(local_path, 'rb') as fp:
data = fp.read()
request = Request(url, headers=headers, data=data, method='PUT')
with urlopen(request, timeout=self.timeout) as response:
return json.load(response)
def _renew_token(self):
if self._expire_date <= datetime.now():
body = f'client_id={CLIENT_ID}&refresh_token={self._refresh_token}&grant_type=refresh_token'
self._acquire_token(body)
def _acquire_token(self, body):
now = datetime.now()
request = Request(TOKEN_URL, data=body.encode(), method='POST')
with urlopen(request, timeout=self.timeout) as response:
data = json.load(response)
self._access_token = data['access_token']
self._refresh_token = data['refresh_token']
expire = data['expires_in']
self._expire_date = now + timedelta(seconds=int(expire))
</code></pre> | <p>here's attached how you can improve the code above: </p>
<ol>
<li><p>First on constructor or <strong>init</strong> you don't need to access_token, refresh_token and expired date. To make it simple for any modules that consume this class, all of token related stuff is handled inside OneDrive Class. The class will simply get token every time you use download or upload methods. this will remove <code>self._renew_token()</code> on every other methods.</p>
<ol start="2">
<li>You could extract line below: </li>
</ol></li>
</ol>
<pre><code>request = Request(url, headers=headers)
with urlopen(request, timeout=self.timeout) as response:
</code></pre>
<p>Which used in few methods into his own function. this will adhere to single responsibility so later new method called <code>request</code> is the one responsible handling HTTP Request and other method that consume this method only care about the return. With this design it's also possible later in the future if you decide to change library into something else like Requests or AIOHTTP you only need to modify this method. </p>
<ol start="3">
<li>For testing, now you can just the the <code>request</code> methods by patching the urllib, and now for <code>upload</code> or <code>download</code> there's few approach you can do, you could mock the <code>request</code> or still just patch the urllib that used inside request method. I recommend that you try the unit-test (test all module and mock other module that this module relying) and later integration-test (all module connecting with other module)</li>
</ol>
<p>onedrive.py</p>
<pre><code>import json
from datetime import datetime, timedelta
from urllib.request import Request, urlopen
TOKEN_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
DRIVE_BY_ID_URL = "https://graph.microsoft.com/v1.0/drives/"
CLIENT_ID = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
class Onedrive:
def __init__(self):
access_token, refresh_token, expire_date = self._renew_token()
self._access_token = access_token
self._refresh_token = refresh_token
self._expire_date = expire_date
@staticmethod
def request(url, headers, method="GET", data=None):
"""
this function handle the actual HTTP request to actual endpoint
behind by providing url, headers, method and data
"""
request = Request(url, headers=headers, data=data, method=method)
with urlopen(request, timeout=5) as response:
return response
def download(self, drive_id, file_id, filename):
url = f"{DRIVE_BY_ID_URL}/{drive_id}/items/{file_id}/content?AVOverride=1"
with open(filename, "wb+") as fp:
headers = {"Authorization": self._access_token}
response = self.request(url, headers)
fp.write(response.read())
def upload(self, local_path, parent_drive_id, parent_id, filename):
url = f"{DRIVE_BY_ID_URL}/{parent_drive_id}/items/{parent_id}:/{filename}:/content"
headers = {
"Authorization": self._access_token,
"Content-Type": "application/octet-stream",
}
with open(local_path, "rb") as fp:
response = self.request(
url=url, headers=headers, data=fp.read(), method="PUT"
)
return json.load(response)
def _renew_token(self):
access_token = self._access_token
refresh_token = self._refresh_token
expire_date = self._expire_date
if self._expire_date <= datetime.now():
body = f"client_id={CLIENT_ID}&refresh_token={self._refresh_token}&grant_type=refresh_token"
access_token, refresh_token, expire_date = self._acquire_token(body)
return access_token, refresh_token, expire_date
def _acquire_token(self, body):
now = datetime.now()
response = self.request(
url=TOKEN_URL, headers=None, data=body.encode(), method="POST"
)
data = json.load(response)
access_token = data["access_token"]
refresh_token = data["refresh_token"]
expire = data["expires_in"]
expire_date = now + timedelta(seconds=int(expire))
return access_token, refresh_token, expire_date
</code></pre>
<p>test_onedrive.py</p>
<pre><code>from unittest import TestCase
from unittest.mock import patch, MagicMock
from example import Onedrive
class TestOneDrive(TestCase):
@patch("urllib.request.urlopen")
def test_request(self, mock_urlopen):
mock = MagicMock()
mock.getcode.return_value = 200
mock.read.return_value = "some-contents"
mock.__enter__.return_value = mock
mock_urlopen.return_value = mock
response = Onedrive.request(
url="https://login.microsoftonline.com/common/oauth2/v2.0/token",
headers={"Content-Type": "application/x-www-form-urlencoded"},
method="POST",
data={"data": "some_data"},
)
self.assertEqual(response.getcode(), 200)
self.assertEqual(response.read(), "some-contents")
@patch("urllib.request.urlopen")
def test_download(self, mock_urlopen):
mock = MagicMock()
mock.getcode.return_value = 200
mock.read.return_value = "some-contents"
mock.__enter__.return_value = mock
mock_urlopen.return_value = mock
Onedrive().download(
drive_id="drive-id", file_id="file_id", filename="some_filename"
)
# now you just check whether the file actual written
</code></pre>
<p>reference:
<a href="https://docs.python.org/3/howto/urllib2.html" rel="nofollow noreferrer">https://docs.python.org/3/howto/urllib2.html</a>
<a href="https://docs.python.org/3/library/unittest.mock.html" rel="nofollow noreferrer">https://docs.python.org/3/library/unittest.mock.html</a></p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Converting a tensorflow object into a jpeg on local drive<p>I'm following the tutorial <a href="https://www.tensorflow.org/tutorials/generative/deepdream" rel="nofollow noreferrer">here</a>:</p>
<p>in order to create a python program that will create a deep-dream style img and save in onto disk. I thought that changes to the following lines should do the trick:</p>
<pre><code> img = run_deep_dream_with_octaves(img=original_img, step_size=0.01)
display.clear_output(wait=True)
img = tf.image.resize(img, base_shape)
img = tf.image.convert_image_dtype(img/255.0, dtype=tf.uint8)
tf.compat.v1.enable_eager_execution()
fname = '2.jpg'
with tf.compat.v1.Session() as sess:
enc = tf.io.encode_jpeg(img)
fwrite = tf.io.write_file(tf.constant(fname), enc)
result = sess.run(fwrite)'
</code></pre>
<p>the key line being encode_jpeg, however this gives me the following error:</p>
<pre><code> Traceback (most recent call last):
File "main.py", line 246, in <module>
enc = tf.io.encode_jpeg(img)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-
packages/tensorflow/python/ops/gen_image_ops.py", line 1496, in encode_jpeg
name=name)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-
packages/tensorflow/python/framework/op_def_library.py", line 470, in
_apply_op_helper
preferred_dtype=default_dtype)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-
packages/tensorflow/python/framework/ops.py", line 1465, in convert_to_tensor
raise RuntimeError("Attempting to capture an EagerTensor without "
RuntimeError: Attempting to capture an EagerTensor without building a function.
</code></pre> | <p>You can simply convert the "img" tensor into numpy array and then save it as you have eager execution enabled (its enabled by default in tf 2.0)</p>
<p>So, the modified code for saving the image will be:</p>
<pre><code>img = run_deep_dream_with_octaves(img=original_img, step_size=0.01)
display.clear_output(wait=True)
img = tf.image.resize(img, base_shape)
img = tf.image.convert_image_dtype(img/255.0, dtype=tf.uint8)
fname = '2.jpg'
PIL.Image.fromarray(np.array(img)).save(fname)
</code></pre>
<p>You don't have to use sessions in tf2.0 to get the values from tensor.</p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Pickleable partial class<p>I need to partially instantiate a class and later use in multiprocessing.
Multiprocessing pickles classes to pass between processes.
How can I pickle a partially instantiated class?</p>
<p>I'm targeting Python 3.8+</p>
<p>P.S. Here is my <code>partialclass</code> implementation:</p>
<pre class="lang-py prettyprint-override"><code>def partialclass(cls, *args, **kwargs):
new_cls = type(cls.__name__, (cls,), {})
new_cls.__init__ = partialmethod(cls.__init__, *args, **kwargs)
return new_cls
</code></pre>
<p>EDIT: I thought about overriding <code>__reduce__</code> method, but class can potentially take arguments, which I don't know at the time of definition.</p> | <p>You are creating a <em>class</em>, not a 'partial instance'. Pickle doesn't serialise classes, as it assumes that all <em>code</em> can be loaded from source instead.</p>
<p>Instead, produce <em>instances</em> of a utility class, one that can be pickled, and when called does the same thing as calling your generated class:</p>
<pre><code>class Partial:
def __init__(self, cls, *args, **kwargs):
self.cls, self.args, self.kwargs = cls, args, kwargs
def __call__(self, *args, **kwargs):
return self.cls(*self.args, *args, **self.kwargs, **kwargs)
</code></pre>
<p>The class attributes are then pickled (here, a reference to a class object, a tuple and a dictionary), and you can call the instance to produce the actual class:</p>
<pre><code>>>> import pickle
>>> class Foo:
... def __init__(self, *args, **kwargs):
... self.a, self.k = args, kwargs
... def __repr__(self):
... return f"<Foo(*{self.a!r}, **{self.k!r})>"
...
>>> pickled = pickle.dumps(Partial(Foo, "bar", monty="python"))
>>> partial = pickle.loads(pickled)
>>> partial("baz", spam="ham")
<Foo(*('bar', 'baz'), **{'monty': 'python', 'spam': 'ham'})>
</code></pre>
<p>However, the above is <strong>basically</strong> re-inventing the <a href="https://docs.python.org/3/library/functools.html#functools.partial" rel="nofollow noreferrer"><code>functools.partial()</code> object</a>, which are instances of a utility class that can be pickled, and called, just like the above Python re-implementation:</p>
<pre><code>>>> import pickle
>>> from functools import partial
>>> pickled = pickle.dumps(partial(Foo, "bar", monty="python"))
>>> fpartial = pickle.loads(pickled)
>>> fpartial("baz", spam="ham")
<Foo(*('bar', 'baz'), **{'monty': 'python', 'spam': 'ham'})>
</code></pre>
<p><code>functools.partial()</code> is more memory efficient and faster, however.</p>
<p>The only possible advantage would be that you could use <code>isinstance(object, Partial)</code> to distinguish it from <code>functools.partial()</code>. But you could just use subclassing for that too:</p>
<pre><code>import functools
class CPartial(functools.partial): pass
</code></pre>
<p>and it'd work just the same.</p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Panda dataframe conversion of series of 03Mar2020 date format to 2020-03-03<p>I'm not able to convert input</p>
<pre><code>Dates = {'dates': ['05Sep2009','13Sep2011','21Sep2010']}
</code></pre>
<p>to desired output</p>
<pre><code>Dates = {'dates': [2019-09-02,2019-09-13,2019-09-21]}
</code></pre>
<p>using Pandas Dataframe.</p>
<pre><code>data = {'dates': ['05Sep2009','13Sep2011','21Sep2010']}
df = pd.DataFrame(data, columns=['dates'])
df['dates'] = pd.to_datetime(df['dates'], format='%Y%m%d')
print (df)
</code></pre>
<p>Output:</p>
<pre><code>ValueError: time data '05Sep2009' does not match format '%Y%m%d' (match)
</code></pre>
<p>I'm new to this library. Help is appreciated.</p> | <p>Currently the months are abbreviated and are not numeric, so you can't use <code>%m</code>.
To convert abbreviated months and get the expected output use <code>%b</code>, like this:</p>
<pre><code>df['dates'] = pd.to_datetime(df['dates'], format='%d%b%Y')
</code></pre>
<p><strong>Update:</strong> to convert the DataFrame back to a dictionary you can use the function <code>to_dict()</code> but first, to get the desidered output, you need to convert the column from <code>datetime</code> back to <code>string</code> type. You can achieve it through this:</p>
<pre><code>df['dates'] = df['dates'].astype(str)
df.to_dict('list')
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Add diagonal line to hist2d with matplotlib<p>I am analyzing the heights/widths of some ML label boxes by creating a 2D histogram with matplotlib:</p>
<pre><code>plt.hist2d(widths, heights, 100, [(0, 0.1), (0, 0.1)])
plt.gca().set_aspect(aspect=1)
plt.savefig(outimage)
</code></pre>
<p><a href="https://i.stack.imgur.com/vAYVl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vAYVl.png" alt="enter image description here" /></a></p>
<p>But I want to add a semi-transparent diagonal line from (0,0) to (0.1,0.1)--the line indicating a square label box--to emphasize how the majority of the aspect ratios tend towards the tall and narrow.</p>
<p>I've tried adding this line both before the <code>hist2d()</code> call and after:</p>
<pre><code>plt.plot(0, 0, 0.1, 0.1, marker = "o")
</code></pre>
<p>But as you can see in the picture, it just creates the endpoint dots, not the line. How do I add a line <em>on top of the existing plot</em>, ideally a semi-transparent line?</p> | <p>You should pass the coordinates of the line plot as a list of x values and a list of y values. For the transparency you can use the <code>alpha</code> parameter. So your code for the line should be</p>
<pre><code>plt.plot([0, 0.1], [0, 0.1], marker="o", alpha=0.5)
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Python: separate utilities file or use static methods?<p>In python I have getters and setters, and calculate utilities. The getters return the property, the setters set the property and the calculate utilities are functions that calculate stuff with the arguments. E.g.</p>
<p><code>obj.property = calculate_property(arguments)</code></p>
<p>However, there are various ways to implement <code>calculate_property</code>, it could</p>
<ol>
<li>be a part of the class <code>calculate_property(self)</code> and return <code>_property</code></li>
<li>It could be an independent function which could be moved to a separate file</li>
<li>It could be a static method</li>
</ol>
<p>My problem with 1) is that the arguments to calculate_property can be obscured because they might be contained within the object itself, and it is not possible to use the function outside of the object. In both 2 and 3 the functional form of <code>calculate</code> is retained but the namespaces are different.</p>
<p>So I'm ruling out 1) for this reason.</p>
<p>IIf I go with 2) the advantage is that I can split all my utilities up into small files e.g. utilities_a.py, utilities_b.py and import them as modules.</p>
<p>If I go with 3) the functions remain in the same file making it overall longer, but the functions are encapsulated better.</p>
<p>Which is preferred between 2) and 3)? Or am I missing a different solution?</p> | <p>You can achieve both <code>2</code> and <code>3</code> with this example of adding a static method to your class that is defined in a separate file.</p>
<p><code>helper.py</code>:</p>
<pre><code>def square(self):
self.x *= self.x
</code></pre>
<p><code>fitter.py</code>:</p>
<pre><code>class Fitter(object):
def __init__(self, x: int):
self.x = x
from helper import square
if name == '__main__':
f = Fitter(9)
f.square()
print(f.x)
</code></pre>
<p>Output:</p>
<pre><code>81
</code></pre>
<p>Adapted from this <a href="https://stackoverflow.com/a/47562412/2359945">answer</a> which was doing this for a class method. Seems to work for static method, too.</p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Problem loading a web app using flask, python, HTML and PostgreSQL; not able to connect python and html scripts plus Internal Server Error message<p>Recently, I have started working on a new project : a web app which will take a name as an input from a user and as result outputs the database rows related to the user input. The database is created using PostgreSQL and in order to complete the task I am using Python as a programming language, followed by Flask (I am new to it) and HTML. I have created 2 source codes, 1 in Python as below :</p>
<pre><code>import os
import psycopg2 as pg
import pandas as pd
import flask
app = flask.Flask(__name__)
@app.route('/')
def home():
return "<a href='/search'>Input a query</a>"
@app.route('/search')
def search():
term = flask.request.args.get('query')
db = pg.connect(
host="***",
database="***",
user ="***",
password="***")
db_cursor = db.cursor()
q = ('SELECT * FROM table1')
possibilities = [i for [i] in db_cursor.execute(q) if term.lower() in i.lower()]
return flask.jsonify({'html':'<p>No results found</p>' if not possibilities else '<ul>\n{}</ul>'.format('\n'.join('<li>{}</li>'.format(i) for i in possibilities))})
if __name__ == '__main__':
app.run()
</code></pre>
<p>and HTML code :</p>
<pre><code><html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<input type='text' name ='query' id='query'>
<button type='button' id='search'>Search</button>
<div id='results'></div>
</body>
<script>
$(document).ready(function(){
$('#search').click(function(){
var text = $('#query').val();
$.ajax({
url: "/search",
type: "get",
data: {query: text},
success: function(response) {
$("#results").html(response.html);
},
error: function(xhr) {
//Do Something to handle error
}
});
});
});
</script>
</html>
</code></pre>
<p>For these scripts I read the discussion<a href="https://stackoverflow.com/questions/50244721/how-to-take-html-user-input-and-query-it-via-python-sql"> here</a>.
These scripts are giving me troubles and I have two main questions :
First : How are these two source codes connected to each other? whenever I run the python script or the html, they look completly disconnected and are not functioning.Moreover, when I run the Python script it gives me this error message on the webpage :</p>
<blockquote>
<p>Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>
</blockquote>
<p>and this message on terminal :</p>
<blockquote>
<p>Serving Flask app 'userInferface' (lazy loading)
Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
Debug mode: off
Running on....</p>
</blockquote>
<p>Can someone please help me by showing how can these 2 scripts connect and why am I getting such errors. Thank you.</p> | <p>You need to use <code>render_template</code> to connect Flask and your HTML code. <br> For example:</p>
<pre><code>from flask import render_template
@app.route("/", methods=['GET'])
def index():
return render_template('index.html')
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
How to use a list to print out a sentence in Python<p>I have this list of data</p>
<pre><code>[
{"type": "Square", "area": 150.5},
{"type": "Rectangle", "area": 80},
{"type": "Rectangle", "area": 660},
{"type": "Circle", "area": 68.2},
{"type": "Triangle", "area": 20}
]
</code></pre>
<p>I want to define an object to represent this data, which takes the values from 'type' and 'area' and store it in a class (I call this class Object).</p>
<p>Here is what I tried to do:</p>
<pre><code> def __init__(self, list):
self.list = list
</code></pre>
<p>Then from this class I want to print out type and area for each object in the class.</p> | <p>If you want to print it then use <code>f string</code></p>
<pre><code>listt = [
{"type": "Square", "area": 150.5},
{"type": "Rectangle", "area": 80},
{"type": "Rectangle", "area": 660},
{"type": "Circle", "area": 68.2},
{"type": "Triangle", "area": 20}
]
for i in range(len(listt)):
print(f'{i+1}- {listt[i]["type"]} with area size {listt[i]["area"]}')
>> 1- Square with area size 150.5
2- Rectangle with area size 80
3- Rectangle with area size 660
4- Circle with area size 68.2
5- Triangle with area size 20
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
TypeError: 'type' object is not subscriptable during reading data<p>I'm pretty new importing data and I´m trying to make def that reads in the presented order. The error is in the fuction, not in the data.</p>
<pre class="lang-py prettyprint-override"><code>def read_eos(filename: str, order: dict[str, int] = {"density": 0, "pressure": 1,
"energy_density": 2}):
# Paths to files
current_dir = os.getcwd()
INPUT_PATH = os.path.join(current_dir, "input")
in_eos = np.loadtxt(os.path.join(INPUT_PATH, filename))
eos = np.zeros(in_eos.shape)
# Density
eos[:, 0] = in_eos[:, order["density"]]
eos[:, 1] = in_eos[:, order["pressure"]]
eos[:, 2] = in_eos[:, order["energy_density"]]
return eos
</code></pre> | <p>Looks like the problem is right in the type hint of one of your function parameters: <code>dict[str, int]</code>. As far as Python is concerned, <code>[str, int]</code> is a <em>subscript</em> of the type <code>dict</code>, but <code>dict</code> can't accept that subscript, hence your error message.</p>
<p>The fix is fairly simple. First, if you haven't done so already, add the following import statement above your function definition:</p>
<pre class="lang-py prettyprint-override"><code>from typing import Dict
</code></pre>
<p>Then, change <code>dict[str, int]</code> to <code>Dict[str, int]</code>.</p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
instances.setMetadata() - nothing changes<p>I'm trying to add startup-script for an existing machine, when I do it from Google's tester ('Try this API') it works, with the client seems like nothing's changing...
Here's the code (just an example of the request) + the response I get (which looks fine) and the machine's data after sending the request.</p>
<h1>My Request:</h1>
<pre><code>from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from pprint import pprint
jsonPath = "myJSON.json"
credentials = GoogleCredentials.from_stream(jsonPath)
# Define gcp service
service = discovery.build('compute', 'v1', credentials=credentials)
#Request Body
bodyData = {"fingerprint": "***","items": [{"key": "startup-script","value": "#! /bin/bash\n\nservice start sshguard"}]}
#setMeta Data Request
instance = service.instances().setMetadata(project="<PROJECT>", zone="europe-west1-b", instance="<ID>", body=bodyData)
#Execute request
response = instance.execute()
# Get instacne details
instanceget = service.instances().get(project="<PROJECT>", zone="europe-west1-b", instance="<ID>").execute()
#Print response + New Metadata
pprint(response)
print("'New Metadata:", instanceget['metadata'])
</code></pre>
<h1>Response I Get</h1>
<pre><code>{'id': '6099825023953066427',
'insertTime': '2020-03-16T04:47:32.880-07:00',
'kind': 'compute#operation',
'name': 'operation-84359252330-5a0f7626e861e-cf743913-4f05cd',
'operationType': 'setMetadata',
'progress': 0,
'selfLink': 'https://www.googleapis.com/compute/v1/projects/<Project>/zones/europe-west1-b/operations/operation-1584359252330-5a0f7626e861e-cf743913-4f05cd31',
'startTime': '2020-03-16T04:47:32.899-07:00',
'status': 'RUNNING',
'targetId': '<ID>',
'targetLink': 'https://www.googleapis.com/compute/v1/projects/<Project>/zones/europe-west1-b/instances/<ID>',
'user': 'pubsub-aws@<Project>.iam.gserviceaccount.com',
'zone': 'https://www.googleapis.com/compute/v1/projects/<Project>/zones/europe-west1-b'}
'New Metadata: {'fingerprint': '***', 'kind': 'compute#metadata'}
</code></pre>
<p>As you can see, the startup-script never added to the Metadata... I thought maybe its something with the json format? maybe the request body needs to be encoded or something?
Will appreciate any help!
Thanks in advance.</p> | <p>Solved. Gave it 'Owner' permissions and it worked.
Means that I had wrong permissions.
Thanks everyone! </p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Load a gpx file on python<p>I'm a Mac user. I'm trying to load a .gpx file on python,using the following code:</p>
<pre><code>import gpxpy
import gpxpy.gpx
gpx_file = open('Downloads/UAQjXL9WRKY.gpx', 'r')
</code></pre>
<p>And I get the following message:</p>
<pre><code>FileNotFoundError: [Errno 2] No such file or directory: 'Downloads/UAQjXL9WRKY.gpx'
</code></pre>
<p>Could someone help me figure out why? Thanks in advance.</p> | <p>Obviously, one reason would be that the file does not, in fact, exist, but let us assume that it does.</p>
<p>A relative filename (i.e, one that does not start with a <code>/</code>) is interpreted relative to the current working direcory of the process. You are apparently expecting that to be the user's home directory, and you are apparently wrong.</p>
<p>One way around this would be to explicitly add the user's home directory to the filename:</p>
<pre><code>import os
home = os.path.expanduser('~')
absfn = os.path.join(home, 'Downloads/whatever.gpx')
gpx_file = open(absfn, ...)
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
'Main' object has no attribute 'TabWidget' between parent Ui class "Ui_MainWindow" and child class "Ui_dialog_List"<p>According to the code below, when I try to take the MainTabIndex value from the addLineDialoge function, which is part of the parent Main () class, and try to use it in the child Dialoge_list class, an 'AttributeError:' Main 'object has no attribute' MainTabIndex 'error occurs.
Please tell me how to solve this problem.</p>
<p>Parent class:</p>
<pre><code>class Main(QMainWindow, Ui_MainWindow):
def __init__(self):
super(Main, self).__init__()
self.setupUi(self)
self.addLineButt.clicked.connect(self.addLineDialoge)
def addLineDialoge(self):
self.**MainTabIndex** = self.MainTab.currentIndex()
self.**ListTabIndex** = self.ListTab.currentIndex()
print(self.ListTabIndex)
addList = Dialoge_list()
addWaste = Dialoge_Waste()
if self.MainTab.currentIndex() == 0:
addList.exec()
elif self.MainTab.currentIndex() == 1:
addWaste.exec()
</code></pre>
<p>Child class:</p>
<pre><code>class Dialoge_list(QDialog, Ui_dialog_List):
def __init__(self):
super(Dialoge_list, self).__init__()
self.setupUi(self)
self.addItemButt.clicked.connect(self.addListToBase)
def addListToBase(self):
numCell = self.numLine.text()
thikCell = self.thikLine.text()
matCell = self.matLine.text()
sizeCell = self.sizeLine.text()
quantityCell = self.quantityLine.text()
dateinCell = self.dateinLine.text()
applyCell = self.applyLine.text()
noticeCell = self.noticeLine.text()
list_tab = [(numCell,
thikCell,
matCell,
sizeCell,
quantityCell,
dateinCell,
applyCell,
noticeCell)]
if "".__eq__(numCell) and "".__eq__(thikCell) and "".__eq__(matCell) and "".__eq__(
sizeCell) and "".__eq__(quantityCell) and "".__eq__(dateinCell) and "".__eq__(
applyCell) and "".__eq__(noticeCell):
emptyError = EmptyErrorDialoge()
emptyError.exec()
elif Main().**MainTabIndex** == 0 and Main().**ListTabIndex** == 0:
. . . .
</code></pre> | <p>I found a solution.
It was necessary to make the following changes in the super method of the "Dialoge_list" classWas:</p>
<pre><code>class Dialoge_list(QDialog, Ui_dialog_List):
def __init__(self):
super(Dialoge_list, self).__init__()
</code></pre>
<p>Became:</p>
<pre><code>class Dialoge_list(QDialog, Ui_dialog_List):
def __init__(self, parent):
super(Dialoge_list, self).__init__(parent)
</code></pre>
<p>Also made changes to the addListToBase function.Was:</p>
<pre><code>def addLineDialoge(self):
self.MainTabIndex = self.MainTab.currentIndex()
self.ListTabIndex = self.ListTab.currentIndex()
print(self.ListTabIndex)
addList = Dialoge_list()
. . .
</code></pre>
<p>Became</p>
<pre><code>def addLineDialoge(self):
self.MainTabIndex = self.MainTab.currentIndex()
self.ListTabIndex = self.ListTab.currentIndex()
print(self.ListTabIndex)
addList = Dialoge_list(self)
. . .
</code></pre>
<p>After that, in the child class, you can call the MainTabIndex and ListTabIndex functions, waiting for this you just need to add the method parent(). Was:</p>
<pre><code>class Dialoge_list(QDialog, Ui_dialog_List):
def __init__(self):
super(Dialoge_list, self).__init__()
self.setupUi(self)
self.addItemButt.clicked.connect(self.addListToBase)
</code></pre>
<p>Became:</p>
<pre><code>class Dialoge_list(QDialog, Ui_dialog_List):
def __init__(self):
super(Dialoge_list, self).__init__()
self.setupUi(self)
self.addItemButt.clicked.connect(self.addListToBase)
self.MainTabIndex = str(self.parent().MainTab.currentIndex())
self.ListTabIndex = str(self.parent().ListTab.currentIndex())
</code></pre>
<p>And only after that, the values of these functions can be used anywhere in the child class.</p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Numpy masked array - find segment nearest to specific index<p>I have a series of small images, stored as 2d numpy arrays. After applying a threshold, I turn the input image into a masked array (mask out values below threshold). Based on this, as shown in the plot below I end up with a number of different objects (2 sometimes more). How can I identify the object that is nearest to center of this masked image, and return an array containing only that object?</p>
<p><a href="https://i.stack.imgur.com/8PUvu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8PUvu.png" alt="enter image description here" /></a></p>
<pre><code>img = masked_array(
data=[[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, 1.0, 1.0, --, --, --, --,
--, --, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, 1.0, 1.0, 1.0, --, --, --, --,
--, --, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, 1.0, 1.0, 1.0, --, --, --, --,
--, --, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, 1.0, 1.0, --, --, --, --,
--, --, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, 1.0, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, 1.0, 1.0, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, 1.0, 1.0, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, 1.0, 1.0, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --],
[--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --, --, --, --, --, --, --, --, --,
--, --, --, --, --, --, --, --]],
mask=[[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, False, False,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, False, False, False,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, False, False, False,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, False, False,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, False, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, False, False, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, False, False, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, False, False, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True],
[ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True]],
fill_value=1e+20)
</code></pre> | <p>Final result:<br />
<a href="https://i.stack.imgur.com/sKXyR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sKXyR.png" alt="enter image description here" /></a></p>
<h2>4 steps involved here:</h2>
<ol>
<li>get index of the center and indices of non-masked points</li>
<li>get the closest point to the center</li>
<li>get the "object" in which the point closest to the center belongs. You can get this using <a href="https://stackoverflow.com/questions/46441893/connected-component-labeling-in-python">opencv connected components</a> (or <a href="https://stackoverflow.com/questions/64345584/how-to-properly-use-cv2-findcontours-on-opencv-version-4-4-0">findContour</a>)</li>
<li>Modify the image to keep only the object you are interested in</li>
</ol>
<h1>Step 1</h1>
<p>Getting indices of non masked point to get the one closest to the center</p>
<pre class="lang-py prettyprint-override"><code>>>> center = [[img.shape[1] // 2, img.shape[0] // 2]]
>>> center
[[20, 20]]
>>> indices = np.array(list(zip(*img.nonzero())))
>>> indices
array([[18, 25],
[18, 26],
[19, 24],
[19, 25],
[19, 26],
[20, 24],
[20, 25],
[20, 26],
[21, 25],
[21, 26],
[22, 19],
[23, 19],
[23, 20],
[24, 19],
[24, 20],
[25, 19],
[25, 20]], dtype=int64)
</code></pre>
<h1>Step 2</h1>
<p>Compute the distance. I'll use scipy for this</p>
<pre class="lang-py prettyprint-override"><code>>>> from scipy.spatial.distance import cdist
>>> distance = cdist(indices, center)
>>> distance
array([[5.38516481],
[6.32455532],
[4.12310563],
[5.09901951],
[6.08276253],
[4. ],
[5. ],
[6. ],
[5.09901951],
[6.08276253],
[2.23606798],
[3.16227766],
[3. ],
[4.12310563],
[4. ],
[5.09901951],
[5. ]])
>>> np.argmin(distance)
10
>>> distance[10]
array([2.23606798])
>>> closest_point = indices[10]
>>> closest_point
array([22, 19], dtype=int64)
</code></pre>
<h1>Step 3</h1>
<p>Find the "object" ( = the connected component) closest to the center.<br />
I'll use OpenCV for this</p>
<pre class="lang-py prettyprint-override"><code>>>> import cv2
>>> N_cc, cc = cv2.connectedComponents(img.data.astype(np.uint8))
>>> N_cc
3 # 3 objects on your image: the 2 'black' and the white one
>>> obj = np.array(
list(zip(
*np.where(cc == cc[closest_point[0], closest_point[1]]) # getting all the points from the connected component having the same label as the point closest to the center
))
)
>>> obj
array([[22, 19], # the closest point to the center
[23, 19], # and all its neighbours in the same object
[23, 20],
[24, 19],
[24, 20],
[25, 19],
[25, 20]], dtype=int64)
</code></pre>
<h1>Step 4</h1>
<p>Keep only the main object in the original image</p>
<pre class="lang-py prettyprint-override"><code>>>> img.mask.fill(True)
>>> img.mask[obj[:, 0], obj[:, 1]] = False # numpy version of: for i in obj: img.mask[i[0], i[1]] = False
>>> img.nonzero()
(array([22, 23, 23, 24, 24, 25, 25], dtype=int64),
array([19, 19, 20, 19, 20, 19, 20], dtype=int64))
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Sort a dictionary depending of some value<pre><code>"users": {
"673336994218377285": {"votes": 5},
"541388453708038165": {"votes": 1},
"845444326065700865": {"votes": 9}
}
</code></pre>
<p>How can I sort a dictionary depending on the "votes" key of the nested dictionary? The dictionary should look like this:</p>
<pre><code>"users": {
"845444326065700865": {"votes": 9},
"673336994218377285": {"votes": 5},
"541388453708038165": {"votes": 1}
}
</code></pre> | <p>Dictionaries in Python (since 3.6) are sorted by their insertion order, so you have to create a new dictionary with the elements inserted in their sorted order:</p>
<pre><code>users = {
"673336994218377285": {"votes": 5},
"541388453708038165": {"votes": 1},
"845444326065700865": {"votes": 9}
}
dict(sorted(users.items(), key=lambda x: x[1]['votes'], reverse=True))
</code></pre>
<p>The <code>key=lambda x: x[1]['votes']</code> makes it sort each element according to the 'votes' field of the value of each item.</p>
<p>If you're using an older version of Python then dictionaries will not be sorted, so you'll have to use this same approach with <code>collections.OrderedDict</code> instead of <code>dict</code>.</p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
How to set a new index<p>My df has the columns 'Country' and 'Country Code' as the current index. How can I remove this index and create a new one that just counts the rows? I´ll leave the picture of how it´s looking. All I want to do is add a new index next to Country. Thanks a lot!</p>
<p><a href="https://i.stack.imgur.com/WfYNd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WfYNd.png" alt="enter image description here" /></a></p> | <p>If you are using a pandas DataFrame and your DataFrame is called df:</p>
<pre><code>df = df.reset_index(drop=False)
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
how to list a name n-times?<p>I have a pandas data frame named <code>df</code> and an integer variable named <code>n</code>.</p>
<p>how can I create a list of <code>n</code>-times my dataframe's name <code>df</code>?</p>
<p>Example:</p>
<pre><code>n=3
l = [df,df,df]
</code></pre>
<p>Note: <code>n</code> changes almost randomly for every execution.</p> | <p>You can use a list comprehension to replicate the list <code>n</code> times:</p>
<pre><code>l = [df for _ in range(n)]
</code></pre>
<p>Though note that, as mentioned in the comments, this creates <code>n</code> references to the same object, so a change in any of them will be reflected across all dataframes. If that is a problem (which most likely is) take a new <code>copy</code> on each iteration:</p>
<pre><code>l = [df.copy() for _ in range(n)]
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
HTML Img Src Variable<p>I am trying to pass an array of image urls (in String format) from a python application to an HTML web page. In this HTML web page, I run a Jinja for loop in which I try to display a series of images whose sources are in the array I passed to the HTML webpage. However, the images are not appearing. Below is my code for this attempt. imgLinks is the array that contains all the urls of my image sources, and the variable length represents the length of this array.</p>
<pre><code>{% for arrayPos in range(length) %}
<div class="card">
<div class="container">
<img src=imgLinks[arrayPos] width=30% height=20%> </img>
</div>
</div>
<br>
{% endfor %}
</code></pre>
<p>Per the request of someone, here is my python code. I am basically calling from an API to get my information.</p>
<pre><code>@app.route('/explorelaunches')
def explorelaunches():
response = requests.get("https://ll.thespacedevs.com/2.0.0/launch/upcoming/")
jsonResponse = response.json()
launches = jsonResponse["results"]
names = []
startTimes = []
padNames = []
descriptions = []
imgLinks = []
for launch in launches:
if (launch['name'] is None):
names.append("N/A")
else:
names.append(launch['name'])
if (launch['net'] is None):
startTimes.append("N/A")
else:
dateString = launch['net']
finalDate = parse(dateString).strftime('%B %d, %Y')
startTimes.append(finalDate)
if (launch['pad'] is None or launch['pad']['name'] is None):
padNames.append("N/A")
else:
padNames.append(launch['pad']['name'])
if (launch['mission'] is None or launch['mission']['description'] is None):
descriptions.append("N/A")
else:
descriptions.append(launch['mission']['description'])
if (launch['image'] is None):
imgLinks.append("N/A")
else:
imgLinks.append(launch['image'])
return render_template("explorelaunches.html", username=session.get(names=names, startTimes=startTimes, padNames=padNames, descriptions=descriptions, length=len(names), imgLinks=imgLinks)
</code></pre>
<p>Is there any way I can accomplish this task? Thanks in advance.</p> | <p>Given an list of URLs, you can directly iterate over the list in jinja template. I have just made bit of correction according to the information you have provide.</p>
<pre><code>{% for image_link in imgLinks%}
<div class="card">
<div class="container">
<img src={{ image_link }} width=30% height=20%> </img> <!--you forgot to put url inside {{...}}-->
</div>
</div>
<br>
{% endfor %}
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
CreateProcessW failed error:2 ssh_askpass: posix_spawn: No such file or directory Host key verification failed, jupyter notebook on remote server<p>So I was following a <a href="https://towardsdatascience.com/running-jupyter-notebooks-on-remote-servers-603fbcc256b3" rel="nofollow noreferrer">tutorial</a> to connect to my jupyter notebook which is running on my remote server so that I can access it on my local windows machine.</p>
<p>These were the steps that I followed.</p>
<p>On my remote server :</p>
<pre><code>jupyter notebook --no-browser --port=8889
</code></pre>
<p>Then on my local machine</p>
<pre><code>ssh -N -f -L localhost:8888:localhost:8889 *******@**********.de.gyan.com
</code></pre>
<p>But I am getting an error</p>
<pre><code>CreateProcessW failed error:2
ssh_askpass: posix_spawn: No such file or directory
Host key verification failed.
</code></pre>
<p>How do I resolve this? Or is there is any other way to achieve the same?</p> | <p>If you need the DISPLAY variable set because you want to use VcXsrc or another X-Server in Windows 10 the workaround is to add the host you want to connect to your known_hosts file.
This can be done by calling</p>
<pre><code>ssh-keyscan -t rsa host.example.com | Out-File ~/.ssh/known_hosts -Append -Encoding ASCII;
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
How to create a matrix of lists?<p>I need to create a matrix MxN where every element of the matrix is a list of integers. I need a list so that I can append new elements as I go, therefore a 3D matrix would not work here.
I'm not sure if what I need here would actually be a list of lists.</p> | <p>The following function creates a 2D matrix of empty lists:</p>
<pre><code>>>> def create(row,col):
... return [[[] for _ in range(col)] for _ in range(row)]
...
>>> L = create(2,3)
>>> L[1][2].extend([1,2,3]) # add multiple integers at a location
>>> for row in L:
... print(row)
...
[[], [], []]
[[], [], [1, 2, 3]]
>>> L[0][1].append(1) # add one more integer at a location
>>> for row in L:
... print(row)
...
[[], [1], []]
[[], [], [1, 2, 3]]
</code></pre>
<p>How it works:</p>
<ul>
<li><code>[]</code> is a new instance of an empty list.</li>
<li><code>[[] for _ in range(col)]</code> uses a list comprehension to create a list of "col" empty lists.</li>
<li><code>[[] for _ in range(col)] for _ in range(row)</code> create "row" new lists of "col" empty lists.</li>
</ul> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Can I use the column name as condition?<p>I have a pandas dataframe which contains around a hundred columns.
Most of these columns are dates and I want to iterate through all these.</p>
<p>Here is an example :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">date</th>
<th style="text-align: center;">nbDays</th>
<th style="text-align: right;">2020-12-20</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">2020-12-30</td>
<td style="text-align: center;">4</td>
<td style="text-align: right;"></td>
</tr>
</tbody>
</table>
</div>
<p>IF date + nbdays <= 2020-12-20, set the value of this column to TRUE, FALSE if No.
The only thing I can't do is taking the column name as an argument in my condition, and do it for all these date columns.</p>
<p>Here's my expected output :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">date</th>
<th style="text-align: center;">nbDays</th>
<th style="text-align: center;">2020-12-20</th>
<th style="text-align: right;">2020-12-21</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">2020-12-30</td>
<td style="text-align: center;">4</td>
<td style="text-align: center;">FALSE</td>
<td style="text-align: right;">FALSE</td>
</tr>
<tr>
<td style="text-align: left;">2020-12-18</td>
<td style="text-align: center;">2</td>
<td style="text-align: center;">TRUE</td>
<td style="text-align: right;">FALSE</td>
</tr>
</tbody>
</table>
</div>
<p>Maybe in a loop but it'll be long to run?</p> | <p><em>Ensure your date columns are converted to datetime for this to work</em></p>
<p>The basic steps I've used are:</p>
<ol>
<li>get pandas to identify the date columns</li>
<li>shift the "date" column by nbDays</li>
<li>compare the shifted date column to the dates in the columns</li>
</ol>
<pre><code>from dateutil.relativedelta import relativedelta
shifted_date = [
t + relativedelta(days=nb_days)
for t, nb_days in zip(df[date], df[nbDays])
]
date_columns = df.select_dtypes(include=[np.datetime64]).columns
for date_column in date_columns:
date_to_check = pd.to_datetime(date_column)
df[date_column] = np.where(
shifted_date <= date_to_check, True, False
)
</code></pre>
<p>Don't be afraid to use a <code>for</code> loop here because the tough work is vectorised in the <code>np.where</code> function.</p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
How to add 91 to all the values in a column of a pandas data frame?<p>Consider my data frame as like this</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>S.no</th>
<th>Phone Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>9955290232</td>
</tr>
<tr>
<td>2</td>
<td>8752837492</td>
</tr>
<tr>
<td>3</td>
<td>9342832245</td>
</tr>
<tr>
<td>4</td>
<td>919485928837</td>
</tr>
<tr>
<td>5</td>
<td>917482482938</td>
</tr>
<tr>
<td>6</td>
<td>98273642733</td>
</tr>
</tbody>
</table>
</div>
<p>I want the values in "Phone number" column to prefixed with 91
If the value has 91 already then, proceed to the next value.</p>
<p>My output</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>S.no</th>
<th>Phone Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>919955290232</td>
</tr>
<tr>
<td>2</td>
<td>918752837492</td>
</tr>
<tr>
<td>3</td>
<td>919342832245</td>
</tr>
<tr>
<td>4</td>
<td>919485928837</td>
</tr>
<tr>
<td>5</td>
<td>917482482938</td>
</tr>
<tr>
<td>6</td>
<td>919827364273</td>
</tr>
</tbody>
</table>
</div>
<p>How could this be done?</p> | <p>Simplest would be comvert to string, add <code>91</code> to the beginning and slice to last 12 digits:</p>
<pre><code>df['New Phone Number'] = df['Phone Number'].astype(str).radd("91").str[-12:]
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
How to create an alphanumeric grid in a certain sequence allowing double digit numbers?<p>I have a grid feature class that varies in size and shape. My test shapefile is a 3x4 grid. I need to create an alphanumeric sequence that goes in a specific order but can be scaled for a different size grid. Below is the order the grid is in:</p>
<pre><code>A4 | B4 | C4
A3 | B3 | C3
A2 | B2 | C2
A1 | B1 | C1
</code></pre>
<p>and to use this alphanumeric sequence, the list will need to be printed in a specific order (starting from the bottom left of the table, moving to the right, and then returning to the left value on the next row up:
A1, B1, C1, A2, B2, C2, A3, B3, C3, A4, B4, C4</p>
<p>I had this:</p>
<pre><code>from itertools import product
from string import ascii_uppercase, digits
for x, y in product(ascii_uppercase, digits):
print('{}{}'.format(x, y))
</code></pre>
<p>It generates a sequence like: A0 through A9, then B0 through B9, and so forth.
However I also need larger grids so the script would have to compensate and allow the sequence to use double digits after 9 if the grid is larger than 9 high.
ie. A10, B10, C10</p>
<p>I then tried to make 2 lists and then combine them together, but I ran into the problem of joining these in the sequence I need.</p>
<pre><code>w = 3
h = 4
alpha = []
numeric = []
for letter in ascii_uppercase[:w]:
alpha.append(letter)
for num in range(1, h+1):
numeric.append(num)
</code></pre>
<p>I assume I might not need to make a numeric list, but don't know how to do it. I know slightly more than just the basics of python and have created so more complex scripts, but this is really puzzling for me! I feel like I am so close but missing something really simple from both of my samples above. Thank you for any help you can give me!</p>
<p>Solved, here is what I have for others who might need to use my question:</p>
<pre><code>w = 9
h = 20
alpha = []
numeric = []
for letter in ascii_uppercase[:w]:
alpha.append(letter)
for num in range(1, h+1):
numeric.append(num)
longest_num = len(str(max(numeric)))
for y in numeric:
for x in alpha:
print '{}{:0{}}'.format(x, y, longest_num)
</code></pre>
<p>I didn't need the code formatted as a table since I was going to perform a field calculation in ArcMap.</p> | <p>After you compute <code>numeric</code>, also do:</p>
<pre><code>longest_num = len(str(max(numeric)))
</code></pre>
<p>and change your format statement to:</p>
<pre><code>'{}{:0{}}'.format(x, y, longest_num)
</code></pre>
<p>This ensures that when you get to double digits you get the following result:</p>
<pre><code>A12 | B12 | C12
A11 | B11 | C11
...
A02 | B02 | C02
A01 | B01 | C01
</code></pre>
<p>To actually print the grid however you need to change your code:</p>
<pre><code>longest_num = len(str(max(numeric)))
for y in reversed(numeric):
print(" | ".join('{}{:0{}}'.format(x, y, longest_num)
for x in alpha))
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
python requests and bs4 how to navigate through the children of an element<p>so this is my code</p>
<pre><code>from bs4 import BeautifulSoup
import requests
import time
URL = 'http://www.vn-meido.com/k1/index.php?board=17.0'
# loads page
r = requests.get(URL)
soup = BeautifulSoup(r.content, "html.parser")
# gets the newest book
book = soup.select_one('td[class^="subject windowbg2"]').text
while True:
# reloads the page
r = requests.get(URL)
soup = BeautifulSoup(r.content, "html.parser")
# gets the newest book
new_book = soup.select_one('td[class^="subject windowbg2"]').text
# checks if a new book has been uploaded
if book == new_book:
print("no new book found")
elif book != new_book:
print(new_book)
book = soup.select_one('td[class^="subject windowbg2"]').text
# repeats after 30 seconds
time.sleep(30)
</code></pre>
<p>but if you go to the website and have a look I get the text of the newest book uploaded but I want to be able to separate the title and the author and the title and author are in different elements but they don't have a way to identify them (like a class or an ID) so if you can help please do, thanks</p> | <p>Assuming html remains consistent across entries (I only checked a few) then when next text is found under the pinned listings at the top (I assume this to be a new book) then you need to extract the book url, visit that url, then you can use ``:-soup-contains<code>to target author and book title by specific text and</code>next_sibling` to get the required return values.</p>
<p>N.B. I have removed the while loop for the purposes of this answer. The additions to the <code>elif</code> are the important ones.</p>
<pre><code>from bs4 import BeautifulSoup
import requests
URL = 'http://www.vn-meido.com/k1/index.php?board=17.0'
# loads page
r = requests.get(URL)
soup = BeautifulSoup(r.content, "html.parser")
# gets the newest book
book = '' # for testing altered this line
r = requests.get(URL)
soup = BeautifulSoup(r.content, "html.parser")
# gets the newest book
new_book = soup.select_one('td[class^="subject windowbg2"]').text
# checks if a new book has been uploaded
if book == new_book:
print("no new book found")
elif book != new_book:
print(new_book)
new_book_url = soup.select_one('tr:not([class]) td:not([class*=stickybg]) ~ .subject a')['href']
r = requests.get(new_book_url)
soup = BeautifulSoup(r.content, "html.parser")
for member in ['TITLE ', 'AUTHOR']:
print(soup.select_one(f'strong:-soup-contains("{member}")').next_sibling.next_sibling)
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Pandas group by values in list (in series)<p>I am trying to group by items in a list in DataFrame Series. The dataset being used is the <a href="https://insights.stackoverflow.com/survey" rel="nofollow noreferrer">Stack Overflow 2020 Survey</a>.</p>
<p>The layout is roughly as follows:</p>
<pre><code> ... LanguageWorkedWith ... ConvertedComp ...
Respondent
1 Python;C 50000
2 C++;C 70000
</code></pre>
<p>I want to essentially want to use <code>groupby</code> on the unique values in the list of languages worked with, and apply the a mean aggregator function to the ConvertedComp like so...</p>
<pre><code>LanguageWorkedWith
C++ 70000
C 60000
Python 50000
</code></pre>
<p>I have actually managed to achieve the desired output but my solution seems somewhat janky and being new to Pandas, I believe that there is probably a better way.</p>
<p>My solution is as follows:</p>
<pre><code># read csv
sos = pd.read_csv("developer_survey_2020/survey_results_public.csv", index_col='Respondent')
# seperate string into list of strings, disregarding unanswered responses
temp = sos["LanguageWorkedWith"].dropna().str.split(';')
# create new DataFrame with respondent index and rows populated withknown languages
langs_known = pd.DataFrame(temp.tolist(), index=temp.index)
# stack columns as rows, dropping old column names
stacked_responses = langs_known.stack().reset_index(level=1, drop=True)
# Re-indexing sos DataFrame to match stacked_responses dimension
# Concatenate reindex series to ConvertedComp series columnwise
reindexed_pays = sos["ConvertedComp"].reindex(stacked_responses.index)
stacked_with_pay = pd.concat([stacked_responses, reindexed_pays], axis='columns')
# Remove rows with no salary data
# Renaming columns
stacked_with_pay.dropna(how='any', inplace=True)
stacked_with_pay.columns = ["LWW", "Salary"]
# Group by LLW and apply median
lang_ave_pay = stacked_with_pay.groupby("LWW")["Salary"].median().sort_values(ascending=False).head()
</code></pre>
<p>Output:</p>
<pre><code>LWW
Perl 76131.5
Scala 75669.0
Go 74034.0
Rust 74000.0
Ruby 71093.0
Name: Salary, dtype: float64
</code></pre>
<p>which matches the value calculated when choosing specific language: <code>sos.loc[sos["LanguageWorkedWith"].str.contains('Perl').fillna(False), "ConvertedComp"].median()</code></p>
<p>Any tips on how to improve/functions that provide this functionality/etc would be appreciated!</p> | <p>In the target column only data frame, decompose the language name and combine it with the salary. The next step is to convert the data from horizontal format to vertical format using melt. Then we group the language names together to get the median. <a href="https://pandas.pydata.org/docs/reference/api/pandas.melt.html" rel="nofollow noreferrer">melt docs</a></p>
<pre><code>lww = sos[["LanguageWorkedWith","ConvertedComp"]]
lwws = pd.concat([lww['ConvertedComp'], lww['LanguageWorkedWith'].str.split(';', expand=True)], axis=1)
lwws.reset_index(drop=True, inplace=True)
df_long = pd.melt(lwws, id_vars='ConvertedComp', value_vars=lwws.columns[1:], var_name='lang', value_name='lang_name')
df_long.groupby('lang_name')['ConvertedComp'].median().sort_values(ascending=False).head()
lang_name
Perl 76131.5
Scala 75669.0
Go 74034.0
Rust 74000.0
Ruby 71093.0
Name: ConvertedComp, dtype: float64
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Get first Tuesday of month every year<p>I want to use sql or python to get the first Tuesday in June for the current year. </p>
<p>For example:</p>
<ul>
<li>The year is 2020, so I need to return 06/02/2020</li>
<li>The year is 2021, so I need to return 06/01/2021</li>
</ul> | <p>Here's the python way.</p>
<pre class="lang-py prettyprint-override"><code>import datetime
def get_day(year):
d = datetime.datetime(year, 6, 1)
offset = 1-d.weekday() #weekday = 1 means tuesday
if offset < 0:
offset+=7
return d+datetime.timedelta(offset)
</code></pre>
<p>Pass in the year to the function, it returns the first tuesday as a <code>datetime</code> object.</p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
How to declare a global variable of pySerial with Python<p>Using Python I need to call the 'configSerialPort' function several times and for that I have declared serialPort as global and it is my code:</p>
<pre><code>import serial
comPort = 'COM5'
serialPort = None
def configSerialPort(timeout):
serialPort = serial.Serial(port = comPort, baudrate = 9600, timeout = timeout)
def ping():
#serialPort = serial.Serial(port = comPort, baudrate = 9600, timeout = 1)
command = "AT\n"
serialPort.write(command.encode('ASCII'))
bufferRxSerial = serialPort.readline().decode('ASCII')
if( bufferRxSerial.strip() == "OK" ):
return True
else:
return False
def main():
global serialPort
configSerialPort(3)
flagConexion = ping()
if flagConexion == True:
print('The Modem is connected!')
else:
print('ERROR, no connection to modem!')
main()
</code></pre>
<p>but I have this error:</p>
<pre><code>File "C:/Users/WSR/AppData/Local/Programs/Python/Python39/TestSerialPort.py", line 12, in ping
serialPort.write(command.encode('ASCII'))
AttributeError: 'NoneType' object has no attribute 'write'
</code></pre>
<p>how can I correct it</p> | <p>Whenever you want to access a global variable in a function, you should declare it as global</p>
<pre><code>def configSerialPort(timeout):
global serialPort
...
def ping():
global serialPort
...
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
How do I stop the code running the remember() function every time I use speakRemember() function?<p>I have this code for a remembering system:</p>
<pre><code>def remember():
speak('What do you want me to remember sir?')
toRemember = input('What should I remember? ')
speak('ok, i will remember: ' + toRemember)
return toRemember
def speakRemember():
toRemember = remember()
speak('this is what you told mke to remember: '+toRemember)
</code></pre>
<p>whenever I trigger the speakRemember() function and it gets the data from the remember() it ends up running the remember() function. I think the error is here: <code>toRemember = remember()</code>
but I don't see why it would run the other function. If anyone knows if this is a bug or just human error please tell me!</p>
<p>(there are no errors)</p> | <p>To elaborate on my comment:</p>
<pre class="lang-py prettyprint-override"><code>class Remember:
def __init__(self, to_remember=None):
self.to_remember = to_remember
def __call__(self):
self.to_remember = input('What Should I remember? ')
def __str__(self):
return f"this is what you told me to remember: {toRemember}"
def __repr__(self):
retrun self.__str__
# If you want to print response while setting a value:
def remember_this(self):
print('What do you want me to remember sir?')
self()
print(f"ok, I will remember: {self.to_remember}")
remember = Remember()
remember()
>> What Should I remember? This
print(remember.to_remember)
>>> 'This'
print(remember)
>>> this is what you told me to remember: This
remember.remember_this()
>>> What do you want me to remember sir?
>>> What Should I remember? That
>>> ok, I will remember: That
print(remember)
>>> this is what you told me to remember: That
</code></pre>
<p>If you call the instance of your class (in this case <code>remember</code>) the <code>__call__</code> function is used. You can also create different function to change class attributes.</p>
<p>The <code>__str__</code> and <code>__repr__</code> functions are use to make it easy to print the values in a string.</p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Reading a (Wireshark) LiveCapture of USB keystrokes into python on Ubuntu 20.04?<h2>Context</h2>
<p>The bluetooth of my keyboard is unstable, it's a known problem of the device. The manufacturer says the micro-USB does not transmit keypresses and that it is for charging only. However, I inspected the USB data with Wireshark and detected it does transmit the keystrokes over its micro-USB connection. So I am trying to give the keyboard a second life through the micro-USB connection (and hopefully help people with the same issue).</p>
<h2>System</h2>
<p>Ubuntu 20.04</p>
<h2>Approach</h2>
<p>I've identified the USB port of my keyboard device in Wireshark, and recorded the stream of data across that port. That data is saved into a file called <code>abcd.pcapng</code> (I pressed the buttons <code>abcd</code> during the recording). Next, I wrote a basic python script that uses <code>tshark</code> to convert <code>abcd.pcapng</code> file into its original keypresses <code>abcd</code>.</p>
<h2>Code</h2>
<p>This is the Python code that converts the <code>abcd.pcapng</code> file into the letters <code>abcd</code>:</p>
<pre><code># This script extracts the keypresses from a pcapng file.
import os
pcapng_filename = "abcd.pcapng"
keypress_ids_filename = "keypress_ids.txt"
# create the output for
command_pcapng_to_keypress_ids = (
f"tshark -r '{pcapng_filename}' -T fields -e usb.capdata > {keypress_ids_filename}"
)
print(
f"Running the following bash command to convert the pcapng file to 00xx00000 nrs:\n{command_pcapng_to_keypress_ids}"
)
os.system(command_pcapng_to_keypress_ids)
# read keypress id file
switcher = {
"04": "a", # or A
"05": "b", # or B
"06": "c", # or C
"07": "d", # or D
"08": "e", # or E
"09": "f", # or F
"0A": "g", # or G
"0B": "h", # or H
"0C": "i", # or I
"0D": "j", # or J
"0E": "k", # or K
"0F": "l", # or L
"10": "m", # or M
"11": "n", # or N
"12": "o", # or O
"13": "p", # or P
"14": "q", # or Q
"15": "r", # or R
"16": "s", # or S
"17": "t", # or T
"18": "u", # or U
"19": "v", # or V
"1A": "w", # or W
"1B": "x", # or X
"1C": "y", # or Y
"1D": "x", # or Z
"1E": "1", # or !
"1F": "2", # or @
"20": "3", # or #
"21": "4", # or $
"22": "5", # or %
"23": "6", # or ^
"24": "7", # or &
"25": "8", # or *
"26": "9", # or (
"27": "0", # or )
"2D": "-", # or _
"2E": "+", # or =
"2F": "[", # or {
"30": "]", # or }
"31": '"', # or |
"33": ";", # or :
"34": "'", # or "
"35": "`", # or ~
"36": ",", # or <
"37": ".", # or >
"38": "/", # or ?
}
def readFile(filename):
fileOpen = open(filename)
return fileOpen
file = readFile(keypress_ids_filename)
print(f"file={file}")
# parse the 0000050000000000 etc codes and convert them into keystrokes
for line in file:
if len(line) == 17:
two_chars = line[4:6]
try:
print(
f"line={line[0:16]}, relevant characters indicating keypress ID: {two_chars} convert keypres ID to letter: {switcher[two_chars]}"
)
except:
pass
</code></pre>
<h2>Output</h2>
<p>The output of that script for the specified file is:</p>
<pre><code>Running the following bash command to convert the pcapng file to 00xx00000 nrs:
tshark -r 'abcd.pcapng' -T fields -e usb.capdata > keypress_ids.txt
file=<_io.TextIOWrapper name='keypress_ids.txt' mode='r' encoding='UTF-8'>
line=0000040000000000, relevant characters indicating keypress ID: 04 convert keypres ID to letter: a
line=0000050000000000, relevant characters indicating keypress ID: 05 convert keypres ID to letter: b
line=0000060000000000, relevant characters indicating keypress ID: 06 convert keypres ID to letter: c
line=0000070000000000, relevant characters indicating keypress ID: 07 convert keypres ID to letter: d
</code></pre>
<h2>Question</h2>
<p>How can I adjust the code to get the USB data directly as a continuous stream, instead of first having to start- and stop recording the USB data followed by having to create the output <code>abcd.pcapng</code> file?</p>
<p>For example, is there a Wireshark-api or tshark function that starts listening until the/some script is stopped?</p> | <h2>Solution</h2>
<p>The following script called <code>live_capture_keystrokes.py</code> captures the <code>Leftover Capture Data</code> which contains the signals of the keystrokes, they are parsed live and continuously by the Python code.</p>
<p>I think it is important to activate usb monitoring each time you reboot the computer (if you want to run this script successfully). To do that, you can run:</p>
<pre><code>sudo modprobe usbmon
</code></pre>
<p>Ideally you would run that without sudo, that would also prevent one to run the python file with sudo, but I did not yet figure out how to run <code>modprobe usbmon</code> without sudo.</p>
<h2>Code</h2>
<p>This <code>live_capture_keystrokes.py</code> script needs to be ran with sudo if <code>modprobe usbmon</code> is ran with sudo. To run the python script in sudo, one can type:</p>
<pre><code>sudo su
# sudo apt install python3
# pip install pyshark
# python3 live_capture_keystrokes.py
</code></pre>
<p>And the content of <code>live_capture_keystrokes.py</code> is:</p>
<pre><code>import pyshark
# Get keystrokes data
print("\n----- Capturing keystrokes from usbmon0 --------------------")
capture = pyshark.LiveCapture(interface='usbmon0', output_file='output.pcap')
# Source: https://www.programcreek.com/python/example/92561/pyshark.LiveCapture
for i, packet in enumerate(capture.sniff_continuously()):
try:
data= packet[1].usb_capdata.split(":")
print(data)
except:
pass
capture.clear()
capture.close()
print(f'DONE')
</code></pre>
<h2>Output</h2>
<p>The output is not yet parsed back to keystrokes, I will add that later. However, this is the output, each time you press a key on your usb keyboard, it prints the accompanying list directly to screen.</p>
<pre><code>a['00', '00', '04', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
b['00', '00', '05', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
c['00', '00', '06', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
d['00', '00', '07', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
e['00', '00', '08', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
f['00', '00', '09', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
g['00', '00', '0a', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
h['00', '00', '0b', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
i['00', '00', '0c', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
j['00', '00', '0d', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
k['00', '00', '0e', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
l['00', '00', '0f', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
m['00', '00', '10', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
n['00', '00', '11', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
o['00', '00', '12', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
p['00', '00', '13', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
q['00', '00', '14', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
r['00', '00', '15', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
s['00', '00', '16', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
t['00', '00', '17', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
u['00', '00', '18', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
v['00', '00', '19', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
w['00', '00', '1a', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
x['00', '00', '1b', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
y['00', '00', '1c', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
z['00', '00', '1d', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
0['00', '00', '62', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
1['00', '00', '59', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
2['00', '00', '5a', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
3['00', '00', '5b', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
4['00', '00', '5c', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
5['00', '00', '5d', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
6['00', '00', '5e', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
7['00', '00', '5f', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
8['00', '00', '60', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
9['00', '00', '61', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
1['00', '00', '1e', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
2['00', '00', '1f', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
3['00', '00', '20', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
4['00', '00', '21', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
5['00', '00', '22', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
6['00', '00', '23', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
7['00', '00', '24', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
8['00', '00', '25', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
9['00', '00', '26', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
0['00', '00', '27', '00', '00', '00', '00', '00']
['00', '00', '00', '00', '00', '00', '00', '00']
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Updating column-entries when using groupby+apply iteratively<p>I use the groupby+apply methods on a dataframe and store the return-Values of the applied function in a new column.</p>
<p>The initial dataframe df is:</p>
<pre><code>In[1]: df
Out[1]:
tag a b
0 tag1 15 1
1 tag1 26 2
2 tag2 20 2
3 tag3 11 3
4 tag3 15 3
5 tag3 24 4
</code></pre>
<p>The groupby+apply procedure is the following:</p>
<pre><code>In[2]: grouped = df.groupby('tag')
In[3]: df['a+b'] = grouped.get_group('tag1').apply(function,axis=1)
In[4]: df
Out[4]:
tag a b a+b
0 tag1 15 1 16
1 tag1 26 2 28
2 tag2 20 2 nan
3 tag3 11 3 nan
4 tag3 15 3 nan
5 tag3 24 4 nan
In[5]: df['a+b'] = grouped.get_group('tag2').apply(function,axis=1)
In[6]: df
Out[6]:
tag a b a+b
0 tag1 15 1 nan
1 tag1 26 2 nan
2 tag2 20 2 22
3 tag3 11 3 14
4 tag3 15 3 nan
5 tag3 24 4 nan
</code></pre>
<p>First I chose to apply the function only to entries with 'tag1'. In the original case this is, because the used dataframe is huge and I am only interested in a small number of specific groups to apply the function to.</p>
<p>The problem which you can see from <em>In[5]</em> onwards, is that when repeating code from <em>In[3]</em> in <em>In[5]</em> for a different group, the entries in column 'a+b' for the group 'tag1' will get lost in this procedure.</p>
<p>How can I find a way to simply update column-entries of 'a+b' and not overwriting? Is there a best-practice example for this kind of problem?</p> | <p>This is what I found works best. I use pandas.Series.update() which updates a single column of the Dataframe:</p>
<pre><code>for key, item in grouped:
series = grouped.get_group(key).apply(function,axis=1)
if 'a+b' in df.columns :
df['a+b'].update(series)
else:
df['a+b'] = series
</code></pre>
<p>This code works best, because I need the function to be applied iteratively to each group (or a specified set or groups) and not all groups at once. This is needed due to limited memory capacities and also because I need the information of the applied function only for a small number of groups.</p>
<p>Any comments on this code are very much appreciated!</p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Calling a certain function based on a variable<p>I am trying to call certain functions based on a certain variable. If I have lots of functions based on this variable it quickly gets very ugly with all if statements. My questions is if there is a more elegant and "pythonic" solution than doing something like the code below?</p>
<pre><code>if variable == 0:
function_0()
elif variable == 1:
function_1()
elif variable == 2:
function_2()
</code></pre> | <p>Create an array of the functions, index with the variable and call the function.</p>
<pre><code>[function_0, function_1, function_2][variable]()
</code></pre>
<p>Or do it via a dictionary</p>
<pre><code>dd = {0 : function_0, 1 : function_1, 2 : function_2}
dd[variable]()
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
What method do you use a lot when controlling p4 command with Python?<p>What method do you use a lot when controlling p4 command with Python?</p>
<ol>
<li>Use p4 module</li>
<li>Control p4 command using subprocess ("p4 change")</li>
</ol>
<p>I'm currently creating tool the second method</p> | <p>I find the simplest way to translate from command line to P4Python is the <code>p4.run()</code> command. You just pass in the command you want to run as the first argument and then add each P4 argument after that.</p>
<p>For example, in the terminal:</p>
<p><code>p4 changes</code></p>
<p>In Python would be:</p>
<p><code>p4.run("changes")</code></p>
<p>Terminal:</p>
<p><code>p4 describe 153</code></p>
<p>Python:</p>
<p><code>p4.run("describe", 153)</code></p>
<p>So a super simple example of just printing the results of p4 changes would be something like this:</p>
<pre><code>from P4 import P4
p4 = P4()
p4.connect()
changelists = p4.run("changes")
print(changelists)
p4.disconnect()
</code></pre>
<p>There are other ways to run certain commands and some extra steps for things like submitting changelists so be sure to check the documentation: <a href="https://www.perforce.com/manuals/p4python/Content/P4Python/python.p4.html#Instance_Methods_..39" rel="nofollow noreferrer">https://www.perforce.com/manuals/p4python/Content/P4Python/python.p4.html#Instance_Methods_..39</a></p>
<p>Hopefully this helps you get started!</p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Need download voice message from Telegram on Python<p>I started developing a pet project related to telegram bot. One of the points was the question, <strong>how to download a voice message from the bot?</strong></p>
<p>Task: Need to download a audiofile from telegram bot and save in project folder.</p>
<p><strong>GetUpdates</strong>
<a href="https://api.telegram.org/bot" rel="nofollow noreferrer">https://api.telegram.org/bot</a>/getUpdates:</p>
<pre><code>{"duration":2,"mime_type":"audio/ogg","file_id":"<file_id>","file_unique_id":"<file_unique_id>","file_size":8858}}}]}
</code></pre>
<p><br/>
I checked <strong><a href="https://github.com/eternnoir/pyTelegramBotAPI" rel="nofollow noreferrer">pyTelegramBotAPI</a> documentation</strong>, but I didn't find an explanation for exactly how to download the file.</p>
<p>I created the code based on the documentation:</p>
<pre><code>@bot.message_handler(content_types=['voice'])
def voice_processing(message):
file_info = bot.get_file(message.voice.file_id)
file = requests.get('https://api.telegram.org/file/bot{0}/{1}'.format(cfg.TOKEN, file_info.file_path))
</code></pre>
<pre><code>print(type(file), file)
------------------------------------------------------------
Output: <class 'requests.models.Response'>, <Response [200]>
</code></pre>
<p><br/>
I also found one <strong>example</strong> where the author downloaded audio in <strong>chunks</strong>. How exactly I did not understand, but it used a <strong>similar function</strong>:</p>
<pre><code>def read_chunks(chunk_size, bytes):
while True:
chunk = bytes[:chunk_size]
bytes = bytes[chunk_size:]
yield chunk
if not bytes:
break
</code></pre> | <p>In the github of the project there is an <a href="https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/download_file_example.py" rel="nofollow noreferrer">example</a> for that:</p>
<pre><code>@bot.message_handler(content_types=['voice'])
def voice_processing(message):
file_info = bot.get_file(message.voice.file_id)
downloaded_file = bot.download_file(file_info.file_path)
with open('new_file.ogg', 'wb') as new_file:
new_file.write(downloaded_file)
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Broadcasting a M*D matrix to N*D matrix in python (D is greater than 1, M>N)<p>I would like to subtract the rows of a MXD matrix from a NXD matrix (D is greater than 1, M > N) without using any for loops in Python. e.g. suppose I want to subtract the rows of a 100*25 matrix from the rows of a 20*25 matrix. How to write the code without for loops (I know I can do it using broadcasting but can't seem to code).</p> | <p>Method 1:</p>
<pre><code>def subtract(A, B):
m = A.shape[0]
n = B.shape[0]
C = np.empty_like(A)
for i in range(m // n):
C[i*n : (i+1)*n] = A[i*n : (i+1)*n] - B
return C
</code></pre>
<p>Method 2:</p>
<pre><code>def subtract(A, B):
m = A.shape[0]
n = B.shape[0]
return A - np.tile(B, (m // n, 1))
</code></pre>
<p>Method 3:</p>
<pre><code>def subtract(A, B):
B_ = np.repeat(B, 5).reshape(B.size, -1).T.reshape(-1, B.shape[1])
return A - B_
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
shutil.copy2 gives "SameFileError" altho files are not at all the same - why?<pre><code> File "C:\WPy64-3810\python-3.8.1.amd64\lib\shutil.py", line 239, in copyfile
raise SameFileError("{!r} and {!r} are the same file".format(src, dst))
SameFileError: 'G:\\My Drive\\xxxxxxxxxxxx\\Customers (CR, Kit, & Consulting)\\xxxxx\\reports\\old drafts\\Rxxxxxxxx-1E0 (canceled pilot).doc' and
'G:\\Shared drives\\Studies sorted by model\\Executed - updated 2020-03-22 15h05m55s\\EAE in C57BL_6 mice, therapeutic\\MOG35-55\\Rxxxxxxxx-1E0 (canceled pilot) xxxxx__Therapeutic EAE studies in C57BL_6 mice.doc' are the same file
</code></pre>
<p>What the heck is happening here? </p>
<p>Python 3.8, x64, Windows - the two files it prints are clearly not at all the same, yet it says "SameFileError".</p>
<p>I've redacted the path with "xxxxx" in a few places (these are customer files). And inserted a newline to make the source/dest filenames line up (easier to compare).</p>
<p>FWIW, both the source and destination filepaths are on Google Drive File Stream (G:); that may have something to do with it.</p> | <p>It's a bug related to how shutil reads a Google Drive File Stream file system.</p>
<p>See here:
<a href="https://bugs.python.org/issue33935" rel="nofollow noreferrer">https://bugs.python.org/issue33935</a></p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
How to get xml elements which have childs with a certain tag and attribute<p>I want to find xml elements which have certain child elements. The child elements need to have a given tag and an attribute set to a specific value.</p>
<p>To give a concrete example (based on the <a href="https://docs.python.org/3/library/xml.etree.elementtree.html#parsing-xml" rel="nofollow noreferrer">official documentation</a>). I want to find all <code>country</code> elements which have a child element <code>neighbor</code> with attribute <code>name="Austria"</code>:</p>
<pre><code>import xml.etree.ElementTree as ET
data = """<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<neighbor name="Malaysia" direction="N"/>
<partner name="Austria"/>
</country>
<country name="Panama">
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
"""
root = ET.fromstring(data)
</code></pre>
<p>What I've tried without success:</p>
<pre><code>countries1 = root.findall('.//country[neighbor@name="Austria"]')
countries2 = root.findall('.//country[neighbor][@name="Austria"]')
countries3 = root.findall('.//country[neighbor[@name="Austria"]]')
</code></pre>
<p>which all give:</p>
<blockquote>
<p>SyntaxError: invalid predicate</p>
</blockquote>
<hr />
<p>Following solutions are obviously wrong, as too much elements are found:</p>
<pre><code>countries4 = root.findall('.//country/*[@name="Austria"]')
countries5 = root.findall('.//country/[neighbor]')
</code></pre>
<p>where <code>countries4</code> contains all elements having an attribute <code>name="Austria"</code>, but including the <code>partner</code> element. <code>countries5</code> contains all elements which have <em>any</em> neighbor element as a child.</p> | <blockquote>
<p>I want to find all country elements which have a child element neighbor with attribute name="Austria"</p>
</blockquote>
<p>see below</p>
<pre><code>import xml.etree.ElementTree as ET
data = """<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<neighbor name="Malaysia" direction="N"/>
<partner name="Austria"/>
</country>
<country name="Panama">
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
"""
root = ET.fromstring(data)
countries_with_austria_as_neighbor = [c.attrib['name'] for c in root.findall('.//country') if
'Austria' in [n.attrib['name'] for n in c.findall('neighbor')]]
print(countries_with_austria_as_neighbor)
</code></pre>
<p>output</p>
<pre><code>['Liechtenstein']
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Append inner 0 & 1st index to all elements in 2nd index two-dimensional List of Lists - python<p>Hello new to python here... wondering what the best way is to solve a problem like this. </p>
<p>I have a 2d array that look something like this:</p>
<pre><code>a = [['October 17', 'Manhattan', '10024, 10025, 10026'],
['October 17', 'Queen', '11360, 11362, 11365, 11368']]
</code></pre>
<p>Would like to iterate over this to create a new list or data frame that looks like the following:</p>
<pre><code>10024, October 17, Manhattan
10025, October 17, Manhattan
10026, October 17, Manhattan
11360, October 17, Queens
11362, October 17, Queens
11365, October 17, Queens
11368, October 17, Queens
</code></pre>
<p>Any insight would be greatly appreciated. </p>
<p>Thank you. </p> | <p>You may need to iterate over the values, and for each iterate over the several indices you have</p>
<pre><code>values = [['October 17', 'Manhattan', '10024, 10025, 10026'],
['October 17', 'Queens', '11360, 11362, 11365, 11368']]
result = [[int(idx), row[0], row[1]]
for row in values
for idx in row[2].split(',')]
df = DataFrame(result, columns=['idx', 'date', 'place'])
</code></pre>
<p>To obtain</p>
<pre><code>[[10024, 'October 17', 'Manhattan'], [10025, 'October 17', 'Manhattan'],
[10026, 'October 17', 'Manhattan'], [11360, 'October 17', 'Queens'],
[11362, 'October 17', 'Queens'], [11365, 'October 17', 'Queens'],
[11368, 'October 17', 'Queens']]
idx date place
0 10024 October 17 Manhattan
1 10025 October 17 Manhattan
2 10026 October 17 Manhattan
3 11360 October 17 Queens
4 11362 October 17 Queens
5 11365 October 17 Queens
6 11368 October 17 Queens
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Pandas - calculate monthly average from data with mixed frequencies<p>Suppose I have a dataset consisting of monthly, quarterly and annual average occurrences of an event:</p>
<pre><code>multi_index = pd.MultiIndex.from_tuples([("2022-01-01", "2022-12-31"),
("2022-01-01", "2022-03-30"),
("2022-03-01", "2022-03-30"),
("2022-04-01", "2022-04-30")])
multi_index.names = ['period_begin', 'period_end']
df = pd.DataFrame(np.random.randint(10, size=4), index=multi_index)
df
0
period_begin period_end
2022-01-01 2022-12-31 4
2022-03-30 3
2022-03-01 2022-03-30 5
2022-04-01 2022-04-30 8
</code></pre>
<p>I want to calculate the monthly averages as a (simple) sum of these overlapping data. For instance, the mean in March 2022 should be equal to the sum of the observations March-2022, Q1-2022 and Y-2022. For April 2022, it's the sum of April-2022 and Y-2022 (Q2-2022 does not show up and has no observation). In the end, what I would like to have is:</p>
<pre><code>month_begin Monthly_Avg
2022-01-01 7
2022-02-01 7
2022-03-01 12
2022-04-01 15
...
2022-12-01 4
</code></pre>
<p>I tried <code>pd.Grouper()</code> but it didn't work. Does anybody have an idea? I would be grateful!</p> | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html" rel="nofollow noreferrer"><code>date_range</code></a> in list comprehension for months values, create DataFrame and aggregate <code>sum</code>:</p>
<pre><code>L = [(x, v) for (s, e), v in df[0].items() for x in pd.`(s, e, freq='MS')]
df = (pd.DataFrame(L, columns=['month_begin','Data'])
.groupby('month_begin', as_index=False)['Data']
.sum())
print (df)
month_begin Data
0 2022-01-01 7
1 2022-02-01 7
2 2022-03-01 12
3 2022-04-01 12
4 2022-05-01 4
5 2022-06-01 4
6 2022-07-01 4
7 2022-08-01 4
8 2022-09-01 4
9 2022-10-01 4
10 2022-11-01 4
11 2022-12-01 4
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
In R, Error for No Boto3 to connect Athena even though Boto3 Installed<p>I am trying to connect to Athena from R. After setup 'RAthena' and connection, I got this error:</p>
<pre><code>Error: Boto3 is not detected please install boto3 using either: `pip install boto3` in terminal or `install_boto()`.
Alternatively `reticulate::use_python` or `reticulate::use_condaenv` will have to be used if boto3 is in another environment.
</code></pre>
<p>So by using <code>pip install</code>, I installed <code>boto3</code> in both Python 2 and Python 3.</p>
<pre><code>Requirement already up-to-date: boto3 in ./Library/Python/2.7/lib/python/site-packages (1.12.39)
</code></pre>
<pre><code>Requirement already satisfied: boto3 in ./Library/Python/3.7/lib/python/site-packages (1.12.39)
</code></pre>
<p>But in <code>R</code>, I am still having the same error. Then I tried using <code>install_boto()</code> in <code>R</code>.
It tells me to do as follow:</p>
<pre><code>Installation complete. Please restart R.
</code></pre>
<p>Then I would stay in this <code>Restarting R session...</code> output forever and never see any note for successful restart.
And at the end, <code>R</code> still can't detect <code>boto3</code>.</p> | <p>really sorry to hear you are having issue with the <code>RAthena</code> package. Can you let me know what version of the package you are running. </p>
<p>Have you tried setting which python you are using through <code>reticulate</code>? For example:</p>
<pre><code>library(DBI)
# specifying python conda environment
reticulate::use_condaenv("RAthena")
# Or specifying python virtual enviroment
reticulate::use_virtualenv("RAthena")
con <- dbConnect(RAthena::athena())
</code></pre>
<p>Can you also check if <code>numpy</code> is installed, I remember <code>reticulate</code> can bind to python environments better if <code>numpy</code> is apart of it. </p>
<p>Alternatively you can use <a href="https://github.com/DyfanJones/noctua" rel="nofollow noreferrer"><code>noctua</code></a>. <code>noctua</code> works exactly the same as <code>RAthena</code> but instead of using python's <code>boto3</code> it uses R's <code>paws</code> package.</p>
<p>If you are still struggling I can raise this as an issue on Github. I thought I had resolved this issue by adding <code>numpy</code> to the installation function <code>install_boto</code>, however I am happy to re-open this issue.</p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
How to append value to list in a row based on another column python?<p>I have a dataframe that looks like:</p>
<pre><code> body label
the sky is blue [noun]
the apple is red. [noun]
Let's take a walk [verb]
</code></pre>
<p>I want to add an item to the list in label depending on if there is a color in the body column.</p>
<p>Desired Output:</p>
<pre><code> body label
the sky is blue [noun, color]
the apple is red. [noun, color]
Let's take a walk [verb]
</code></pre>
<p>I have tried:</p>
<pre><code>data.loc[data.body.str.contains("red|blue"), 'label'] = data.label.str.append('color')
</code></pre> | <p>One option is to use <code>apply</code> on the Series and then directly append to list:</p>
<pre><code>data.loc[data.body.str.contains('red|blue'), 'label'].apply(lambda lst: lst.append('color'))
data
body label
0 the sky is blue [noun, color]
1 the apple is red. [noun, color]
2 Let's take a walk [verb]
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Pandas: Splitting datetime into weekday, month, hour columns<p>I have a dataset with date-time values like this,</p>
<pre><code> datetime
0 2012-04-01 07:00:00
. .
. .
</code></pre>
<p>I would like to create separate columns of <strong>weekday, hour, month</strong> like,</p>
<pre><code> datetime weekday_1 ... weekday_7 hour_1 ... hour_7 ... hour_24 month_1 ... month_4 ... month_12
0 2012-04-01 07:00:00 0 1 0 1 0 0 1 0
</code></pre>
<p><em>(taking monday as weekday_1, the example date is sunday: weekday_7)</em></p>
<p>The only way I know how to extract from datetime is this,</p>
<pre><code>df['month'] = df['datetime'].dt.month
</code></pre>
<p>But I cannot seem to apply this to fit my problem.</p>
<p>Sorry if this sounds repetitive, i am fairly new to this. But similar question answers were not helpful enough.
Thanks in advance.</p> | <p>Create a custom function:</p>
<pre><code># Use {i:02} to get a number on two digits
cols = [f'weeday_{i}' for i in range(1, 8)] \
+ [f'hour_{i}' for i in range(1, 25)] \
+ [f'month_{i}' for i in range(1, 13)]
def get_dummy(dt):
l = [0] * (7+24+12)
l[dt.weekday()] = 1
l[dt.hour + 6] = 1
l[dt.month + 30] = 1
return pd.Series(dict(zip(cols, l)))
df = df.join(df['datetime'].apply(get_dummy))
</code></pre>
<p>Output:</p>
<pre><code>>>> df.iloc[0]
datetime 2012-04-01 07:00:00
weeday_1 0
weeday_2 0
weeday_3 0
weeday_4 0
weeday_5 0
weeday_6 0
weeday_7 1 # <- Sunday
hour_1 0
hour_2 0
hour_3 0
hour_4 0
hour_5 0
hour_6 0
hour_7 1 # <- 07:00
hour_8 0
hour_9 0
hour_10 0
hour_11 0
hour_12 0
hour_13 0
hour_14 0
hour_15 0
hour_16 0
hour_17 0
hour_18 0
hour_19 0
hour_20 0
hour_21 0
hour_22 0
hour_23 0
hour_24 0
month_1 0
month_2 0
month_3 0
month_4 1 # <- April
month_5 0
month_6 0
month_7 0
month_8 0
month_9 0
month_10 0
month_11 0
month_12 0
Name: 0, dtype: object
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Resuming debug from the middle in pycharm<p>This should be a common issue and I believe it should have been asked somewhere! But I couldn't find a wording that leads my search to an answer!</p>
<p>Suppose you have a python program that runs for 1 hour! The issue that you want to debug and ultimately rerun (possibly in several rounds) happens after 45 mins! Is there a way to kinda Cache or save your variables in debugger space, and rerun the program from that point onwards? (Especially for Python/Pycharm). I already thought of Pickling my variables but first, there are too many variables and second, not all objects can be pickled in python!</p> | <p><strong>Proper way</strong>:
You can accomplish this with the <a href="https://docs.python.org/3/library/pdb.html" rel="nofollow noreferrer">post-mortem functionality from pdb</a>. <a href="https://paris-swc.github.io/python-testing-debugging-profiling/07-debugging-post-mortem.html" rel="nofollow noreferrer">[more info]</a>. This lets you use the debugger after an exception is raised.</p>
<p><strong>Quick and dirty way</strong>: This isn't the best way to do it, but a quick way to post-mortem debug is to place the part of the code where you want to check the variables in a try-except block with a breakpoint set in the except block. If you do this with the built-in <code>breakpoint()</code> function, you can play with the variables and then continue execution by entering <code>c</code> at the debugger prompt.</p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Split a dictionary to explictly call out 'Key' : dict.keys() and "Value' : dict.values() for JSON data going into an API<p>I'm currently working with the CampaignMonitor API to support with email subscription management and email marketing. I need to send JSON data through the API to make any changes to the subscription list. My current code looks like the following,</p>
<pre><code>df = test_json.groupby(['EmailAddress', 'Name']).apply(lambda x : x[['Location', 'location_id', 'customer_id', 'status','last_visit'].astype(str).to_dict(orient = 'records'))
df = df.reset_index().rename(columns = {0 : 'CustomFields'})
#df['CustomFields'].apply(lambda x : print(x[0].items()))
</code></pre>
<p>Which returns the following</p>
<pre><code>{‘EmailAddress’ : ‘[email protected]’, ‘Name’ : ‘John Smith’, ‘CustomFields’ : [{'Location': 'H6GO', location_id': 'D8047', 'customer_id': '2963', 'status': 'Active', 'last_visit': '2020-06-23'}]}
</code></pre>
<p>However, the Campaign Monitor API specifically wants for the CustomFields to contain an explicit call out for the key and value of each dictionary pairing. Is there a simple way to expand an existing dictionary and create a sub dictionary within a dictionary calling out the the key and value? Right now, I'm thinking of using apply to do it row by row but am struggling for how to break these down so the key and value callouts remain in one dictionary,</p>
<pre><code>{‘EmailAddress’ : ‘[email protected]’, ‘Name’ : ‘John Smith’, ‘CustomFields’ : [{‘Key’ : 'Location', ‘Value’ : 'H6GO'},
{‘Key’ : ‘location_id' , ‘Value’ : 'D8047'},
{‘Key’ : 'customer_id', ‘Value’ : '2963'},
{‘Key’ : 'status', ‘Value’ : 'Active'},
{‘Key’ : 'last_visit', ‘Value’ : '2020-06-23'}
]}
</code></pre> | <p>Try this:</p>
<pre><code>d["CustomFields"] = [{"key": k, "value": v} for k,v in d["CustomFields"][0].items()]
</code></pre>
<p>output:</p>
<pre><code>{'EmailAddress': '[email protected]',
'Name': 'John Smith',
'CustomFields': [{'key': 'Location', 'value': 'H6GO'},
{'key': 'location_id', 'value': 'D8047'},
{'key': 'customer_id', 'value': '2963'},
{'key': 'status', 'value': 'Active'},
{'key': 'last_visit', 'value': '2020-06-23'}]}
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
What is the most efficient way to edit the values in a list of dictionaries?<p>I have multiple dictionaries inside the list, what is an efficient and possible way to update and limit all the float values to only two decimal points?
For example: Make the value of <code>'AmazonEC2': 22.740000000000002</code> to <code>'AmazonEC2': 22.74</code></p>
<pre><code>[{
'AmazonEC2': 22.740000000000002,
'awskms': 0.09,
'AmazonDynamoDB': 6.740000000000002,
'AmazonElastiCache': 0.01,
'AmazonS3': 5.54,
'AmazonCloudWatch': 1.08,
'AWSAmplify': 0.55,
'AmazonRDS': 0.01
}, {
'awskms': 0.740000000000003,
'AmazonS3': 5.740000000000004,
'AmazonCloudWatch': 1.740000000000003,
'AmazonDynamoDB': 6.740000000000006,
'AmazonEC2': 22.740000000000002,
'AWSAmplify': 0.49,
'AmazonRDS': 0.01,
'AmazonElastiCache': 0.01
}]
</code></pre> | <pre><code>for item in your_list:
for key in item.keys():
item[key] = round(item[key], 2)
</code></pre>
<p>The main iteration is list, dict lookup is <code>O(1)</code>.</p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
How to get a column name to display even when there is no data for that column?<p><strong>I want to get the names of the columns of a pandas dataframe even when I don't have data according to certain search criteria</strong></p>
<p><strong>that's how it is now:</strong></p>
<pre><code>Empty DataFrame
Columns: []
Index: []
</code></pre>
<hr />
<p><strong>as I want it to be:</strong></p>
<pre><code>Empty DataFrame
Columns: [column_name]
Index: []
</code></pre>
<p><em><strong>I select the data directly from the MYSQL DB, I do not save it in memory !</strong></em></p> | <p>I am not sure of your need, but if you want to have a dataframe with column names, you can initialize it with the column names :</p>
<pre class="lang-py prettyprint-override"><code> df = pd.DataFrame(columns=['A', 'B', 'C'])
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
How to add hex bytes in a string?<p>I have this string of hex bytes, separated by spaces:</p>
<pre><code>byteString = "7E 00 0A 01 01 50 01 00 48 65 6C 6C 6F"
</code></pre>
<p>How to add bytes in this way:</p>
<pre><code>01 + 01 + 50 + 01 + 00 + 48 + 65 + 6C + 6C + 6F = 247
</code></pre> | <p>Considering that you have the <em>hex</em> sequence as a <em>str</em> (<em>bytes</em>), what you need to do is:</p>
<ul>
<li>Split the sequence in smaller strings each representing a byte (2 <em>hex</em> digits): "<em>7E</em>", "<em>00</em>", ...</li>
<li>Convert each such string to the integer value corresponding to the <em>hex</em> representation (the result will be a list of integers)</li>
<li>Add the desired values (ignoring the 1<sup>st</sup> 3)</li>
</ul>
<blockquote>
<pre class="lang-py prettyprint-override"><code>>>> byte_string = "7E 00 0A 01 01 50 01 00 48 65 6C 6C 6F"
>>>
>>> l = [int(i, 16) for i in byte_string.split(" ")] # Split and conversion to int done in one step
>>> l
[126, 0, 10, 1, 1, 80, 1, 0, 72, 101, 108, 108, 111]
>>>
>>> [hex(i) for i in l] # The hex representation of each element (for checking only)
['0x7e', '0x0', '0xa', '0x1', '0x1', '0x50', '0x1', '0x0', '0x48', '0x65', '0x6c', '0x6c', '0x6f']
>>>
>>> s = sum(l[3:])
>>>
>>> s
583
>>> hex(s)
'0x247'
</code></pre>
</blockquote> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
ValueError building a neural network with 2 outputs in Keras<p>I tried to build a network having a single input X (a 2-dimensions matrix of size Xa*Xb) and 2 outputs Y1 and Y2 (both in 1 dimension). Even though it isn't the case in the code I posted below, Y1 is supposed to be a classifier that outputs a one-hot vector and Y2 is supposed to be for regression (the original code raised the same error).</p>
<p>When training the network I get the following error:</p>
<p><code>ValueError: Shapes (None, None) and (None, 17, 29) are incompatible</code></p>
<p>Obviously, <code>(None, 17, 29)</code> translates to <code>(None, size_Xa, size_Y1)</code>, and I don't understand why Xa and Y1 should be related (independantly from Xb) in the first place.</p>
<p>Here is my code. I tried to reduce it to the minimum in order to make it easier to understand.</p>
<pre><code>import numpy as np
from keras.layers import Dense, LSTM, Input
from keras.models import Model
def dataGenerator():
while True:
yield makeBatch()
def makeBatch():
"""generates a batch of artificial training data"""
x_batch, y_batch = [], {}
x_batch = np.random.rand(batch_size, size_Xa, size_Xb)
#x_batch = np.random.rand(batch_size, size_Xa)
y_batch['output1'] = np.random.rand(batch_size, size_Y1)
y_batch['output2'] = np.random.rand(batch_size, size_Y2)
return x_batch, y_batch
def generate_model():
input_layer = Input(shape=(size_Xa, size_Xb))
#input_layer = Input(shape=(size_Xa))
common_branch = Dense(128, activation='relu')(input_layer)
branch_1 = Dense(size_Y1, activation='softmax', name='output1')(common_branch)
branch_2 = Dense(size_Y2, activation='relu', name='output2')(common_branch)
model = Model(inputs=input_layer,outputs=[branch_1,branch_2])
losses = {"output1":"categorical_crossentropy", "output2":"mean_absolute_error"}
model.compile(optimizer="adam",
loss=losses,
metrics=['accuracy'])
return model
batch_size=5
size_Xa = 17
size_Xb = 13
size_Y2 = 100
size_Y1 = 29
model = generate_model()
model.fit( x=dataGenerator(),
steps_per_epoch=50,
epochs=15,
validation_data=dataGenerator(), validation_steps=50, verbose=1)
</code></pre>
<p>If I uncomment the 2 commented lines in makeBatch and generate_model, the error disappears. So if the input X is in 1 dimension it runs, but when I change it to 2 dimensions (keeping everything else the same) the error appears.</p>
<p>Is this related to the architecture with 2 outputs? I think there is something I'm missing here, any help is welcome.</p>
<p>I add the full error log for reference:</p>
<pre><code>Epoch 1/15
Traceback (most recent call last):
File "neuralnet_minimal.py", line 41, in <module>
model.fit( x=dataGenerator(),
File "/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py", line 66, in _method_wrapper
return method(self, *args, **kwargs)
File "/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py", line 848, in fit
tmp_logs = train_function(iterator)
File "/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py", line 580, in __call__
result = self._call(*args, **kwds)
File "/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py", line 627, in _call
self._initialize(args, kwds, add_initializers_to=initializers)
File "/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py", line 505, in _initialize
self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access
File "/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/eager/function.py", line 2446, in _get_concrete_function_internal_garbage_collected
graph_function, _, _ = self._maybe_define_function(args, kwargs)
File "/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/eager/function.py", line 2777, in _maybe_define_function
graph_function = self._create_graph_function(args, kwargs)
File "/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/eager/function.py", line 2657, in _create_graph_function
func_graph_module.func_graph_from_py_func(
File "/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py", line 981, in func_graph_from_py_func
func_outputs = python_func(*func_args, **func_kwargs)
File "/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py", line 441, in wrapped_fn
return weak_wrapped_fn().__wrapped__(*args, **kwds)
File "/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/framework/func_graph.py", line 968, in wrapper
raise e.ag_error_metadata.to_exception(e)
ValueError: in user code:
/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py:571 train_function *
outputs = self.distribute_strategy.run(
/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/distribute/distribute_lib.py:951 run **
return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/distribute/distribute_lib.py:2290 call_for_each_replica
return self._call_for_each_replica(fn, args, kwargs)
/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/distribute/distribute_lib.py:2649 _call_for_each_replica
return fn(*args, **kwargs)
/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py:532 train_step **
loss = self.compiled_loss(
/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/keras/engine/compile_utils.py:205 __call__
loss_value = loss_obj(y_t, y_p, sample_weight=sw)
/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/keras/losses.py:143 __call__
losses = self.call(y_true, y_pred)
/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/keras/losses.py:246 call
return self.fn(y_true, y_pred, **self._fn_kwargs)
/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/keras/losses.py:1527 categorical_crossentropy
return K.categorical_crossentropy(y_true, y_pred, from_logits=from_logits)
/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/keras/backend.py:4561 categorical_crossentropy
target.shape.assert_is_compatible_with(output.shape)
/path/of/my/project/venv/lib/python3.8/site-packages/tensorflow/python/framework/tensor_shape.py:1117 assert_is_compatible_with
raise ValueError("Shapes %s and %s are incompatible" % (self, other))
ValueError: Shapes (None, None) and (None, 17, 29) are incompatible
</code></pre> | <p>Strangely enough, the error disappears when I add a <code>Flatten()</code> layer before the network splits... It has to do with the shape of the network but I still don't get the real reason behind all of this.</p>
<p>I will mark this as correct answer as it solves the problem, unless someone else posts something. Please tell me if this is not the right way to do it.</p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
how do I pass the √ untouched<p>is it possible to pass the <code>√</code> through this untouched or am i asking too much</p>
<pre><code>import urllib.request
path = 'html'
links = 'links'
with open(links, 'r', encoding='UTF-8') as links:
for link in links: #for each link in the file
print(link)
with urllib.request.urlopen(link) as linker: #get the html
print(linker)
with open(path, 'ab') as f: #append the html to html
f.write(linker.read())
</code></pre>
<p>links</p>
<pre><code>https://myanimelist.net/anime/27899/Tokyo_Ghoul_√A
</code></pre>
<p>output</p>
<pre><code>File "PYdown.py", line 7, in <module>
with urllib.request.urlopen(link) as linker:
File "/usr/lib64/python3.6/urllib/request.py", line 223, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib64/python3.6/urllib/request.py", line 526, in open
response = self._open(req, data)
File "/usr/lib64/python3.6/urllib/request.py", line 544, in _open
'_open', req)
File "/usr/lib64/python3.6/urllib/request.py", line 504, in _call_chain
result = func(*args)
File "/usr/lib64/python3.6/urllib/request.py", line 1392, in https_open
context=self._context, check_hostname=self._check_hostname)
File "/usr/lib64/python3.6/urllib/request.py", line 1349, in do_open
encode_chunked=req.has_header('Transfer-encoding'))
File "/usr/lib64/python3.6/http/client.py", line 1254, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/usr/lib64/python3.6/http/client.py", line 1265, in _send_request
self.putrequest(method, url, **skips)
File "/usr/lib64/python3.6/http/client.py", line 1132, in putrequest
self._output(request.encode('ascii'))
UnicodeEncodeError: 'ascii' codec can't encode character '\u221a' in position 29: ordinal not in range(128)
</code></pre> | <p>You need to quote Unicode chars in URL. You have file which contains list of urls you need to open, so you need to split each url <em>(using <a href="https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlsplit" rel="nofollow noreferrer"><code>urllib.parse.urlsplit()</code></a>)</em>, quote <em>(with <a href="https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote" rel="nofollow noreferrer"><code>urllib.parse.quote()</code></a>)</em> host and every part of path <em>(to split paths you can use <a href="https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.parts" rel="nofollow noreferrer"><code>pathlib.PurePosixPath.parts</code></a>)</em> and then form URL back <em>(using <a href="https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlunsplit" rel="nofollow noreferrer"><code>urllib.parse.urlunsplit()</code></a>)</em>.</p>
<pre class="lang-py prettyprint-override"><code>from pathlib import PurePosixPath
from urllib.parse import urlsplit, urlunsplit, quote, urlencode, parse_qsl
def normalize_url(url):
splitted = urlsplit(url) # split link
path = PurePosixPath(splitted.path) # initialize path
parts = iter(path.parts) # first element always "/"
quoted_path = PurePosixPath(next(parts)) # "/"
for part in parts:
quoted_path /= quote(part) # quote each part
return urlunsplit((
splitted.scheme,
splitted.netloc.encode("idna").decode(), # idna
str(quoted_path),
urlencode(parse_qsl(splitted.query)), # force encode query
splitted.fragment
))
</code></pre>
<p>Usage:</p>
<pre class="lang-py prettyprint-override"><code>links = (
"https://myanimelist.net/anime/27899/Tokyo_Ghoul_√A",
"https://stackoverflow.com/",
"https://www.google.com/search?q=√2&client=firefox-b-d",
"http://pfarmerü.com/"
)
print(*(normalize_url(link) for link in links), sep="\n")
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>https://myanimelist.net/anime/27899/Tokyo_Ghoul_%E2%88%9AA
https://stackoverflow.com/
https://www.google.com/search?q=%E2%88%9A2&client=firefox-b-d,
http://xn--pfarmer-t2a.com/
</code></pre>
<hr />
<p><em>You can help my country, check <a href="https://stackoverflow.com/users/10824407/olvin-roght?tab=profile">my profile info</a>.</em></p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Start index (under FIeld) from 1 with pandas DataFrame<p>I would like to start the index from 1 undes the "Field" column</p>
<pre><code>df = pd.DataFrame(list(zip(total_points, passing_percentage)),
columns =['Pts Measured', '% pass'])
df = df.rename_axis('Field').reset_index()
df["Comments"] = ""
df
</code></pre>
<p>Output:</p>
<pre><code> Field Pts Measured % pass Comments
0 0 92909 90.66
1 1 92830 91.85
2 2 130714 99.99
</code></pre> | <p>I found a similar question here: <a href="https://stackoverflow.com/questions/32249960/in-python-pandas-start-row-index-from-1-instead-of-zero-without-creating-additi">In Python pandas, start row index from 1 instead of zero without creating additional column</a></p>
<p>For your question, it would be as simple as adding the following line:</p>
<pre><code>df["Field"] = np.arange(1, len(df) + 1)
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
SQLite3 in python update where multiple possible matches<p>Perhaps you can help me. I am selecting the oldest # rows in a database, then want to update the date column for each item I selected.</p>
<pre><code>from datetime import datetime
import sqlite3
conn = sqlite3.connect('testing.db')
cursor = conn.cursor()
# Create the table
cursor.execute('CREATE TABLE IF NOT EXISTS players (player_tag TEXT, update_date TEXT, UNIQUE(player_tag));')
max_player_tags = 2
# Insert some data with old dates
arr = [['tag1','20200123T05:06:07'], ['tag2','20200123T05:06:07'], ['tag3','20200123T05:06:07'], ['tag4', datetime.now().isoformat()]]
cursor.executemany('INSERT OR IGNORE INTO PLAYERS values (?, ?)', arr)
conn.commit()
#Select the oldest 2 items
old_tags = [i[0] for i in cursor.execute('SELECT player_tag FROM players ORDER BY update_date DESC LIMIT 2')]
print(old_tags)
#Now update the dates to now
cursor.execute('UPDATE players SET update_date = datetime("now") WHERE player_tag in %s' % old_tags)
print([i for i in 'SELECT * FROM players'])
cursor.close()
conn.close()
</code></pre>
<p>The error I get is</p>
<pre><code> cursor.execute('UPDATE players SET update_date = datetime("now") WHERE player_tag in %s' % old_tags)
sqlite3.OperationalError: no such table: 'tag1', 'tag2'
['tag1', 'tag2']
</code></pre>
<p>I have also tried:</p>
<pre><code>cursor.executemany('INSERT OR IGNORE INTO PLAYERS values (?, ?) ON DUPLICATE KEY UPDATE', upd_arr)
</code></pre>
<p>Any ideas?</p> | <p>I would just use a single query here:</p>
<pre><code>sql = """UPDATE players
SET update_date = datetime("now")
WHERE player_tag IN (SELECT player_tag FROM players
ORDER BY update_date DESC LIMIT 2)"""
cursor.execute(sql)
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
if an item in a list doesn't match a column name in a data frame, produce exception statement<p>I have the following code which creates a list, takes inputs of column names the user wants, then a for loop applies each list attribute individually to check in the if statement if the user input matches the columns in the data frame.</p>
<p>Currently this produces an exception handling statement if all inputs to the list are unmatching, but if item in the list matches the column in the dataframe but others do not, then jupyter will produce its own error message "KeyError: "['testcolumnname'] not in index", because it is trying to move onto the else part of my statement and create the new dataframe with this but it cant (because those columns do not exist)</p>
<p>I want it to be able to produce this error message 'Attribute does not exist in Dataframe. Make sure you have entered arguments correctly.' if even 1 inputted list attribute does not match the dataframe and all other do. But Ive been struggling to get it to do that, and it produces this KeyError instead.</p>
<p>My code:</p>
<pre><code> lst = []
lst = [item for item in str(input("Enter your attributes here: ")).lower().split()]
for i in lst:
if i not in df.columns:
print('Attribute does not exist in Dataframe. Make sure you have entered arguments correctly.')
break
else:
df_new = df[lst]
# do other stuff
</code></pre>
<p>for example if i have a dataframe:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</thead>
<tbody>
<tr>
<td>NA</td>
<td>yes</td>
<td>yes</td>
</tr>
<tr>
<td>yes</td>
<td>no</td>
<td>yes</td>
</tr>
</tbody>
</table>
</div>
<p>and my list contains:</p>
<pre><code>['A','B','C']
</code></pre>
<p>It works correctly, and follows the else statement, because all list items match the dataframes columns so it has no problem.</p>
<p>Or if it has this:</p>
<pre><code>['x','y','z']
</code></pre>
<p>It will give the error message I have, correctly. Because no items match the data frames items so it doesn't continue.</p>
<p>But if it is like this, where one attribute is matching the dataframe, and others not...</p>
<pre><code>['A','D','EE']
</code></pre>
<p>it gives the jupyter KeyError message but I want it to bring back the print message i created ('Attribute does not exist in Dataframe. Make sure you have entered arguments correctly.').</p>
<p>The KeyError appears on the line of my else statement: 'df_new = df[lst]'</p>
<p>Can anyone spot an issue i have here that will stop it from going this? Thank you all</p> | <p>Try not to print, but to raise exception
And you need to fix your indentation</p>
<pre class="lang-py prettyprint-override"><code>lst = []
lst = [item for item in str(input("Enter your attributes here: ")).lower().split()]
for i in lst:
if i not in df.columns:
raise ValueError('Attribute does not exist in Dataframe. Make sure you have entered arguments correctly.')
df_new = df[lst]
# do other stuff
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Pandas - merge dataframe to keep all values on left and 'insert' values from right if 'no key on left' else 'update' existing 'key' in left<p>I have two dataframes df1 and df2.</p>
<pre><code>np.random.seed(0)
df1= pd.DataFrame({'key': ['A', 'B', 'C', 'D'],'id': ['2', '23', '234', '2345'], '2021': np.random.randn(4)})
df2= pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'id': ['23', '2345', '67', '45'],'2022': np.random.randn(4)})
key id 2021
0 A 2 1.764052
1 B 23 0.400157
2 C 234 0.978738
3 D 2345 2.240893
key id 2022
0 B 23 1.867558
1 D 2345 -0.977278
2 E 67 0.950088
3 F 45 -0.151357
</code></pre>
<p>I want to have unique keys. If key found already just update the key else insert new row.
I am not sure if I have to use merge/concat/join. Can anyone give insight on this please?</p>
<p>Note:I have used full outer join, it returns duplicate columns. Have edited the input dataframes after posting the question.</p>
<p>Thanks!</p> | <p>You can do it using merge function:</p>
<pre><code>df = df1.merge(df2, on='key', how='outer')
df
key 2021 2022
0 A 1.764052 NaN
1 B 0.400157 1.867558
2 C 0.978738 NaN
3 D 2.240893 -0.977278
4 E NaN 0.950088
5 F NaN -0.151357
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Tweepy, a bytes-like object is required, not str. How do i fix this error?<p>error: Traceback (most recent call last):
File "C:\Users\zakar\PycharmProjects\Tweepy-bots\main.py", line 29, in
c=c.replace("im ","")
TypeError: a bytes-like object is required, not 'str'</p>
<p>error <a href="https://i.stack.imgur.com/qOQH4.png" rel="nofollow noreferrer">Error picture</a></p>
<p>this is how the code looks like:</p>
<pre><code>`import tweepy
import tweepy as tt
import time
import sys
import importlib
importlib.reload(sys)
#login credentials twitter account
consumer_key = '-NOT GOING TO PUT THE ACTUAL KEY IN-'
consumer_secret = '-NOT GOING TO PUT THE ACTUAL KEY IN-'
access_token = '-NOT GOING TO PUT THE ACTUAL KEY IN-'
access_secret = '-NOT GOING TO PUT THE ACTUAL KEY IN-'
#login
auth = tt.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tt.API(auth)
search_query = "barca"
user = api.me()
print(user.name)
max_tweets = 100
for tweet in tweepy.Cursor(api.search, q=search_query).items(max_tweets):
c=tweet.text.encode('utf8')
c=c.replace("im ","")
answer="@"+tweet.user.screen_name+" Hi " + c + ", I'm a bot!"
print ("Reply:",answer)
api.update_status(status=answer,in_reply_to_status_id=tweet.id)
time.sleep(300) #every 5 minutes`
</code></pre> | <p>The problem is because you are encoding the text , and then replacing.</p>
<p>here</p>
<pre><code>c=tweet.text.encode('utf8')
c=c.replace("im ","")
</code></pre>
<p>encode() will return bytes not a string. So in replace also you need to use the bytes. Like</p>
<pre><code>c=tweet.text.encode('utf8')
c=c.replace(b"im ",b"")
</code></pre>
<p>Or you replace the content first and then encode.</p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Remove python, can I still use the the virtual Environment<p>I created a virtual environment, for example on my computer, python3.9 -m venv myenv
if I uninstall python3.9 can I still launch my python script once myenv is activated ?</p> | <p>no you wont be able to run python applications anymore.</p>
<p>refer <a href="https://docs.python.org/3/library/venv.html" rel="nofollow noreferrer">https://docs.python.org/3/library/venv.html</a>
venv — Creation of virtual environments¶
New in version 3.3.</p>
<p>Source code: Lib/venv/</p>
<p>The venv module provides support for creating lightweight “virtual environments” with their own site directories, optionally isolated from system site directories. Each virtual environment has its own Python binary (which matches the version of the binary that was used to create this environment) and can have its own independent set of installed Python packages in its site directories.</p>
<p>See PEP 405 for more information about Python virtual environments.</p> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
How to make python read input as a float?<p>I need to take an input in the following form "score/max" (Example 93/100) and store it as a float variable. The problem I run into is that python does the division indicated by backslash and since the two numbers are integers, the result is 0. Even if I convert my input into a float the result is 0.0.
Here is my code for reference:</p>
<pre><code>#!/usr/bin/env python
exam1=float(input("Input the first test score in the form score/max:"))
</code></pre>
<p>If 93/100 is entered, exam1 variable will be equal to 0.0 instead of the intended 0.93. </p> | <p><strong>Note:</strong></p>
<h2><code>input()</code></h2>
<blockquote>
<p>reads a line from input, converts it to a string
(stripping a trailing newline), and returns that.</p>
</blockquote>
<p>You may want to try the following code,</p>
<pre><code>string = input("Input the first test score in the form score/max: ")
scores = string.strip().split("/")
exam1 = float(scores[0]) / float(scores[1])
print(exam1)
</code></pre>
<p>Input:</p>
<pre><code>Input the first test score in the form score/max: 93/100
</code></pre>
<p>Output:</p>
<pre><code>0.93
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Using one column values as index to list type values in another in pandas<p>We have data representing temperature forecast for every 3 hours period from the moment. We also know number of 3 hour periods after which the weather is needed. So, we have dataframe:</p>
<pre><code>import pandas as pd
d = {'T_forecast': [[11.98, 10.84, 8.74, 6.31, 4.52],[11.29, 7.87, 3.94, 5.02, 7.97],[16.22, 14.87, 11.31, 10.54, 10.72]
,[9.77, 7.54, 5.96, 2.75, 4.99],[18.61, 16.52, 13.52, 11.62, 16.44]], 'delta_hours_divided_by_3': [3, 1,2,3,1]}
df = pd.DataFrame(data=d)
print(df)
T_forecast delta_hours_divided_by_3
0 [11.98, 10.84, 8.74, 6.31, 4.52] 3
1 [11.29, 7.87, 3.94, 5.02, 7.97] 1
2 [16.22, 14.87, 11.31, 10.54, 10.72] 2
3 [9.77, 7.54, 5.96, 2.75, 4.99] 3
4 [18.61, 16.52, 13.52, 11.62, 16.44] 1
</code></pre>
<p>We need to create column with particular element from the list in 'T_forecast' columns.The result should be:</p>
<pre><code> T_forecast delta_hours_divided_by_3 T_by_the_shift_start
0 [11.98, 10.84, 8.74, 6.31, 4.52] 3 8.74
1 [11.29, 7.87, 3.94, 5.02, 7.97] 1 11.29
2 [16.22, 14.87, 11.31, 10.54, 10.72] 2 14.87
3 [9.77, 7.54, 5.96, 2.75, 4.99] 3 5.96
4 [18.61, 16.52, 13.52, 11.62, 16.44] 1 18.61
</code></pre>
<p>I can get it for particular value, with code:</p>
<pre><code>print(df['T_forecast'][0][df['delta_hours_divided_by_3'][0]-1])
8.74
</code></pre>
<p>But I struggle creating column out:</p>
<pre><code>df['T_by_the_shift_start']=df['T_forecast'][df['delta_hours_divided_by_3']-1]
ValueError: cannot reindex on an axis with duplicate labels
</code></pre>
<p>Using the for loop is not an option since the original dataframe is very large and the server will choke. What can lead to solving the issue?</p> | <h3>Loop solution</h3>
<pre><code>df['T_by_the_shift_start'] = [a[b - 1] for a, b in df.to_numpy()]
</code></pre>
<h3>Non-loop solution</h3>
<p>** lists should have same length across all rows</p>
<p>** This solution will perform around 2x better only on large data sets >= 500K</p>
<pre><code>df['T_by_the_shift_start'] = np.array([*df['T_forecast']])[range(len(df)), df['delta_hours_divided_by_3'] - 1]
</code></pre>
<hr />
<pre><code> T_forecast delta_hours_divided_by_3 T_by_the_shift_start
0 [11.98, 10.84, 8.74, 6.31, 4.52] 3 8.74
1 [11.29, 7.87, 3.94, 5.02, 7.97] 1 11.29
2 [16.22, 14.87, 11.31, 10.54, 10.72] 2 14.87
3 [9.77, 7.54, 5.96, 2.75, 4.99] 3 5.96
4 [18.61, 16.52, 13.52, 11.62, 16.44] 1 18.61
</code></pre> |
Please answer the following Stackoverflow question on Python. Answer it like you are a developer answering Stackoverflow questions.
Stackoverflow question:
Image is not updating in Django<p>Please help me. I am trying to update the profile in which username and email are updated but the image dose not. My code is....</p>
<p><strong>profile.html</strong></p>
<pre><code> <form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Profile Info</legend>
{{ u_form|crispy }}
{{ p_form|crispy }}
</fieldset>
<br>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Update</button>
</div>
</form>
</code></pre>
<p><strong>views.py</strong></p>
<pre><code>@login_required
def profile(request):
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.FILES, instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, f'Account Successfully Updated!')
return redirect('profile')
else:
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST, instance=request.user.profile)
context = {
'u_form' : u_form,
'p_form' : p_form
}
return render(request, 'users/profile.html', context)
</code></pre>
<p><strong>forms.py</strong></p>
<pre><code>class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
</code></pre> | <p>I believe your issue lies in views.py.</p>
<p>Firstly, you are checking to see if the method for retrieving the view is POST. If it is not, you are initializing a form with the POST data that is not present. I have simplified that for you below.</p>
<p>Secondly, you are not passing the POST information to the second form, only the files portion. Have you tried changing the p_form to take both parameters like below?</p>
<pre><code>@login_required
def profile(request):
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, f'Account Successfully Updated!')
return redirect('profile')
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'u_form' : u_form,
'p_form' : p_form
}
return render(request, 'users/profile.html', context)
</code></pre> |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 31