QuestionId
int64 74.8M
79.8M
| UserId
int64 56
29.4M
| QuestionTitle
stringlengths 15
150
| QuestionBody
stringlengths 40
40.3k
| Tags
stringlengths 8
101
| CreationDate
stringdate 2022-12-10 09:42:47
2025-11-01 19:08:18
| AnswerCount
int64 0
44
| UserExpertiseLevel
int64 301
888k
| UserDisplayName
stringlengths 3
30
β |
|---|---|---|---|---|---|---|---|---|
75,951,065
| 13,677,363
|
How to import a class/function in google Colab from a .py file on google drive
|
<p>I am trying to import a class from a .py file which is stored in my google drive.</p>
<p>Initially, I have mounted google drive as follows:</p>
<pre><code>from google.colab import drive
drive.mount('/content/drive')
</code></pre>
<p>Then navigate into the destination folder using:</p>
<pre><code>%cd "/content/drive/MyDrive/Autonomous_Driving/GRTP/clstm_lifelong/us1011/sgan-nsl"
!ls
</code></pre>
<p>It shows output like:</p>
<pre><code>/content/drive/MyDrive/Autonomous_Driving/GRTP/clstm_lifelong/us1011/sgan-nsl
checkpoint.pkl __pycache__ utils_wcgan_decompose.py
loss.mat trained_models
model_wcgan_decompose.py train_wcgan_decompose.py
</code></pre>
<p>Now in that <code>model_wcgan_decompose.py</code> file of the drive there was some class named <code>highwayNet_d</code>, <code>highwayNet_g_compose</code>, <code>highwayNet</code>. Now I am trying to import the class for my purpose using:</p>
<pre><code>from model_wcgan_decompose import highwayNet_d
</code></pre>
<p>but it shows error like:</p>
<pre><code>ImportError Traceback (most recent call last)
<ipython-input-26-256c2191a0a5> in <cell line: 9>()
7 #import model_wcgan_decompose
8
----> 9 from model_wcgan_decompose import highwayNet_d
10
11
ImportError: cannot import name 'highwayNet_d' from 'model_wcgan_decompose' (/content/drive/MyDrive/Autonomous_Driving/GRTP/clstm_lifelong/us1011/sgan-nsl/model_wcgan_decompose.py)
</code></pre>
<p>Please suggest how can I fix it?</p>
|
<python><google-drive-api><google-colaboratory>
|
2023-04-06 15:09:12
| 1
| 949
|
Kanchon Gharami
|
75,951,051
| 11,922,765
|
Python Dataframe sort the dataframe using pd.cut range column
|
<p>I have a big dataframe and I created a temperature range column by using <code>pd.cut</code>. This is fine. Now I want to know the minimum range in that min-max range column. So, I can use this column to sort the dataframe</p>
<p>My code:</p>
<pre><code># Goal: sort below dataframe by the 'temp_range' columns
# The column should be sorted as '-60-50','-10-0','0-10','20-30'
xdf = pd.DataFrame(data={'temp_range':['-10-0','20-30','-60-50','0-10']})
xdf['Min. temp range']= xdf['temp_range'].apply(lambda x:x[:3])
xdf
</code></pre>
<p>Present solution:</p>
<pre><code> temp_range Min. temp range
0 -10-0 -10
1 20-30 20-
2 -60-50 -60
3 0-10 0-1
</code></pre>
<p>Expected solution:</p>
<pre><code> temp_range Min. temp range
0 -10-0 -10
1 20-30 20
2 -60-50 -60
3 0-10 0
</code></pre>
<p>Sort this expected solution by the Min. temp range column</p>
<pre><code>xdf.sort_values('Min. temp range')
temp_range Min. temp range
0 -60-50 -60
1 -10-0 -10
2 0-10 0
3 20-30 20
</code></pre>
|
<python><pandas><dataframe><numpy>
|
2023-04-06 15:07:56
| 1
| 4,702
|
Mainland
|
75,951,004
| 705,676
|
Partition numpy array in-place by condition
|
<p>I have a 1d array of u64 ints. I need to partition it based on given bit inplace.</p>
<p>In pure python it's easy two pointer problem (similar to partitioning in quicksort), but I wonder if it possible to do it efficiently using numpy.</p>
<p>Lets say I have:</p>
<pre class="lang-py prettyprint-override"><code>arr = np.arange(720, dtype=np.uint64) # a lot of 64bit unsigned ints
np.random.shuffle(arr) # in unknown order
left = arr[arr & 32 == 0] # all elements having 5th bit 0 in any order
right = arr[arr & 32 == 32] # all elements having 5th bit 1 in any order
arr[:] = np.concatenate([left, right])
</code></pre>
<p>I would also need to know the index of the partition (aka. <code>len(left)</code> above).</p>
|
<python><numpy><bit-manipulation><partitioning><in-place>
|
2023-04-06 15:02:31
| 3
| 31,420
|
MichaΕ Ε rajer
|
75,950,914
| 10,409,952
|
Cast doesn't work as expected when concatenating strings
|
<p>I am trying to achieve the simplest task - creating the FISCAL_YEAR column as shown below (column YEAR is given):</p>
<pre><code>+------+-------------+
| YEAR | FISCAL_YEAR |
+------+-------------+
| 2022 | 2022-2023 |
+------+-------------+
| 2022 | 2022-2023 |
+------+-------------+
| 2022 | 2022-2023 |
+------+-------------+
| 2022 | 2022-2023 |
+------+-------------+
</code></pre>
<p>I keep getting the error: <code>can only concatenate str (not "int") to str </code></p>
<p>These are the steps I've tried so far, without success:</p>
<ol>
<li><p><code>df['fiscal_year'] = str(df['year']) + "-" + str(df['year']+1)</code></p>
</li>
<li><p><code>df['fiscal_year'] = df['year'].astype(str) + "-" + (df['year']+1).astype(str)</code></p>
</li>
<li></li>
</ol>
<p><code>df['year_str'] = pd.Series(df['year'], dtype=pd.StringDtype())</code></p>
<p>And also:</p>
<p><code>df['year_str'] = df['year'].astype(str)</code></p>
<p>And then:</p>
<p><code>df['year_str'].str.cat(df['year_str'].astype(int) + 1, sep='-')</code></p>
<p>None of these options work. Is there is anything else I'm missing?</p>
<p>** I am on Windows 10 and Python version 3.9.7</p>
|
<python><pandas>
|
2023-04-06 14:54:04
| 1
| 310
|
SAR
|
75,950,748
| 4,007,564
|
Product and sum without addtional memory allocation
|
<p>Is there away to multiply two arrays and sum along an axis (or multiple axes) without allocating extra memory?</p>
<p>In this example:</p>
<pre><code>import numpy as np
A = np.random.random((10, 10, 10))
B = np.random.random((10, 10, 10))
C = np.sum(A[:, None, :, :, None] * B[None, :, None, :, :], axis=(-1,-2))
</code></pre>
<p>When computing C, an intermediate matrix of size 10x10x10x10x10 is created only to be collapsed immediately. Is there a way to avoid this in numpy?</p>
|
<python><numpy><broadcasting>
|
2023-04-06 14:33:14
| 1
| 2,002
|
Tohiko
|
75,950,697
| 5,510,713
|
Trigger a Python script remotely and run it on the host machine
|
<p>I have a python script which uses Tkinter library to do screen grab of the image displayed on my secondary screen. The script works perfectly fine. When i try to run the script remotely using ssh (command below)</p>
<pre><code>ssh pi@testing.com "python /home/display_capture.py"
</code></pre>
<p>I get the following error message:</p>
<blockquote>
<p>_tkinter.TclError: no display name and no $DISPLAY environment variable</p>
</blockquote>
<p>which is understandable because i'm running the script from a remote machine. What's the best way to trigger the script remote but execute on the machine?</p>
|
<python><tkinter><ssh>
|
2023-04-06 14:28:22
| 1
| 776
|
DhiwaTdG
|
75,950,681
| 887,074
|
Alias Python package with a different root name when the old one uses lazy imports
|
<p>I'm currently in the middle of renaming a project. In the meantime I need to not break existing users, so I'd like to provide an alias that lets users use it exactly the same as they previously would. This is turning out to be tricker than I initially thought.</p>
<p>Say I have a repo with a package:</p>
<pre><code>βββ setup.py
βββ pyproject.toml
βββ oldpkg
βββ __init__.py
βββ __main__.py
βββ submod.py
βββ subpkg
βββ __init__.py
βββ nested.py
</code></pre>
<p>My first thought was to introduce:</p>
<pre><code>βββ newpkg.py
</code></pre>
<p>and fill its contents with <code>from oldpkg import *</code></p>
<p>Then in setup.py add:</p>
<pre><code> packages=find_packages(include=[
'oldpkg', 'oldpkg.*',
# Alias the module while we transition to a new name.
'newpkg', 'newpkg.*',
]),
</code></pre>
<p>so both packages are installed.</p>
<p>Works at a the top level for <code>import newpkg</code> but fails if you <code>from newpkg import subpkg</code>.</p>
<p>My next thought was that I could write a script that for every python file in the old package I autogenerate a dumy python file in the new package with <code>from <oldpkg>.<subname> import *</code>.</p>
<p>Now this functionally works, but it introduces two namespaces and it has the problem that it actually accesses the attributes in the old package. The old package uses <a href="https://scientific-python.org/specs/spec-0001/" rel="nofollow noreferrer">lazy imports</a>, which means it uses the module level <code>__getattr__</code> to expose submodules dynamically without doing the time consuming work of importing them all at startup.</p>
<p>I'm not sure if there is any way around this problem. Really all I want is the user to be able to use <code>oldpkg</code> and <code>newpkg</code> interchangably. In fact it would be really great if <code>import oldpkg, newpkg; oldpkg is newpkg</code> was True.</p>
<p>Is there any way that I can write a <code>newpkg</code> that is a strict alias of <code>oldpkg</code>? If possible I'd like the following statements to be functionally equivalent:</p>
<pre class="lang-bash prettyprint-override"><code># In bash I'd like the CLI to be the same. The `__main__.py` should be mirrored
python -m oldpkg
python -m newpkg
</code></pre>
<pre class="lang-py prettyprint-override"><code># In Python
import oldpkg
import newpkg
assert oldpkg is newpkg
from oldpkg.subpkg import nested as n1
from newpkg.subpkg import nested as n2
assert n1 is n2
</code></pre>
<p>Perhaps the above is not possible, but I'm wondering what the best way to go about this would be. I want to go through the following transition phases:</p>
<ol>
<li>newpkg is just a pointer to oldpkg.</li>
<li>contents move from oldpkg to newpkg and now oldpkg is a pointer to newpkg.</li>
<li>oldpkg now includes a deprecation warning.</li>
<li>oldpkg now errors when it is imported and tells the user to use newpkg.</li>
<li>oldpkg is removed.</li>
</ol>
<p>Is there any prior art on acomplishing this transition plan?</p>
|
<python><setuptools><python-packaging>
|
2023-04-06 14:26:57
| 1
| 5,318
|
Erotemic
|
75,950,671
| 17,491,224
|
Exception: Reindexing only valid with uniquely valued Index objects - indexes are unique
|
<p>I am attempting to concat two dataframes. When I tried doing so, I was hit with the error that the <code>Reindexing only valid with uniquely valued Index objects</code> while trying to run this code:
<code>df_3=pd.concat([df_1,df_2])</code>.</p>
<p>I have added the following checks and updates to try and identify the issue:</p>
<pre><code>df_1= df_1.reset_index(drop=True)
df_2= df_2.reset_index(drop=True)
try:
df_3=pd.concat([df_1,df_2], ignore_index=True)
except Exception as e:
print(df_1.index.is_unique)
print(df_1.index.to_list())
print(df_2.index.is_unique)
print(df_2.index.to_list())
df_1.to_csv("../../df_1.csv")
df_2.to_csv("../../df_2.csv")
raise Exception(e)
</code></pre>
<p>This results in the following output:</p>
<pre><code>True
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 8
7, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123,
124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140]
True
[0, 1]
Reindexing only valid with uniquely valued Index objects
</code></pre>
<p>I do not know why this is occurring - I do not get the same issue when I am testing in a console. Please advise!</p>
|
<python><pandas>
|
2023-04-06 14:26:11
| 1
| 518
|
Christina Stebbins
|
75,950,655
| 8,510,149
|
Groupby, Window and rolling average in Spark
|
<p>I want to do a groupby and do a rolling average on huge dataset using pyspark. Not used to pyspark I struggle to see my mistake here. Why doesn't this work?</p>
<pre><code>data = pd.DataFrame({'group':['A']*5+['B']*5,
'order':[1,2,3,4,5, 1,2,3,4,5],
'value':[23, 54, 65, 64, 78, 98, 78, 76, 77, 57]})
spark_df = spark.createDataFrame(data)
window_spec = Window.partitionBy("group").orderBy("order").rowsBetween(-1, 0)
# Calculate the rolling average of col_value
rolling_avg = avg(col("value")).over(window_spec).alias("value_rolling_avg")
# Group by col_group and col_date and calculate the rolling average of col_value
spark_df.groupby("group").agg(rolling_avg).show()
</code></pre>
<pre><code>AnalysisException: [COLUMN_NOT_IN_GROUP_BY_CLAUSE] The expression "order" is neither present in the group by, nor is it an aggregate function. Add to group by or wrap in `first()` (or `first_value()`) if you don't care which value you get.;
</code></pre>
|
<python><pyspark>
|
2023-04-06 14:24:44
| 1
| 1,255
|
Henri
|
75,950,370
| 3,595,907
|
MQTT: Client publishing but subscribers not getting data with QoS 2
|
<p>Raspberry Pi 3B+, W10 x64, Paho, Mosquitto MQTT</p>
<p>I have data being sent in 358.4 Kb payloads once a second via MQTT from a Raspberry Pi to a W10 x64 machine. I'm getting the following with different QoS values,</p>
<p>QoS 0: most of the data but some payloads missing, different sent & recieved counts.</p>
<p>QoS 1: most of the data but some payloads missing, different sent & recieved counts.</p>
<p>QoS 2: publisher claims to have sent everything even though the subscriber is recieving nothing. I have a running message at both ends showing the number of sent & recieved in real time.</p>
<p>Anyone know why this is happening?</p>
<p>The publisher side is in C & relevent code snippets below,</p>
<pre><code>#include "../daqhats/examples/c/daqhats_utils.h"
// Whole load of includes here
#include "MQTTClient.h"
#define MQTT_ADDRSS "tcp://localhost:1883"
#define CLIENTID "ExampleClientPub"
#define TOPIC "mqtt_test"
#define QOS 2
#define TIMEOUT 1000L
int pub_count = 0;
int publish(MQTTClient client,
MQTTClient_deliveryToken token,
MQTTClient_connectOptions conn_opts,
char* payload,
int device)
{
int rc = 0;
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to connect, return code %d\n", rc);
exit(-1);
}
int payload_len = 25600 * sizeof(double);
MQTTClient_publish(client, TOPIC, payload_len, &payload, QOS, 0, &token);
printf("Published: %d\n", device);
pub_count++;
return rc;
}
int main(void)
{
// MQTT initialzers
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_deliveryToken token;
MQTTClient_create(&client, MQTT_ADDRSS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
union DAQ_Data{
double f[2 * 25600];
char s[2 * 25600 * sizeof(double)];
};
// A whole load of DAQ hardware set up here
union DAQ_Data payload;
do //while (is_running)
{
for (device = 0; device < DEVICE_COUNT; device++)
{
// Read data
result = mcc172_a_in_scan_read(address[device], &scan_status[device], samples_to_read,
timeout, payload.f, buffer_size,
&samples_read[device]);
publish(client, token, conn_opts, payload.s, device);
// More DAQ stuff
}
fflush(stdout);
usleep(100000);
if (enter_press())
{
printf("Aborted - enter pressed\n\n");
break;
}
}
while (!enter_press());
printf("Pub count: %d\n", pub_count);
sleep(2);
// DAQ hardware clean up
return 0;
}
</code></pre>
<p>The PC subscriber side in Python, taken fromm the Eclipse MQTT Client example,</p>
<pre><code>import argparse
import os
import ssl
import sys
import paho.mqtt.client as mqtt
parser = argparse.ArgumentParser()
parser.add_argument('-H', '--host', required=False, default="192.168.30.212")#"mqtt.eclipseprojects.io")
parser.add_argument('-t', '--topic', required=False, default="mqtt_test") #"$SYS/#")
parser.add_argument('-q', '--qos', required=False, type=int, default=2)
parser.add_argument('-c', '--clientid', required=False, default=None)
parser.add_argument('-u', '--username', required=False, default=None)
parser.add_argument('-d', '--disable-clean-session', action='store_true', help="disable 'clean session' (sub + msgs not cleared when client disconnects)")
parser.add_argument('-p', '--password', required=False, default=None)
parser.add_argument('-P', '--port', required=False, type=int, default=None, help='Defaults to 8883 for TLS or 1883 for non-TLS')
parser.add_argument('-k', '--keepalive', required=False, type=int, default=60)
parser.add_argument('-s', '--use-tls', action='store_true')
parser.add_argument('--insecure', action='store_true')
parser.add_argument('-F', '--cacerts', required=False, default=None)
parser.add_argument('--tls-version', required=False, default=None, help='TLS protocol version, can be one of tlsv1.2 tlsv1.1 or tlsv1\n')
parser.add_argument('-D', '--debug', action='store_true')
args, unknown = parser.parse_known_args()
mq = open("mq_test.bin", "wb")
rec_count = 0
def on_connect(mqttc, obj, flags, rc):
print("rc: " + str(rc))
def on_message(mqttc, obj, msg):
global rec_count
rec_count = rec_count + 1
# message = msg.payload.decode("utf-8") + '\n'
mq.write(msg.payload)
print("recieved: ", rec_count)
def on_publish(mqttc, obj, mid):
print("mid: " + str(mid))
def on_subscribe(mqttc, obj, mid, granted_qos):
print("Subscribed: " + str(mid) + " " + str(granted_qos))
def on_log(mqttc, obj, level, string):
print(string)
usetls = args.use_tls
if args.cacerts:
usetls = True
port = args.port
if port is None:
if usetls:
port = 8883
else:
port = 1883
mqttc = mqtt.Client(args.clientid,clean_session = not args.disable_clean_session)
if usetls:
if args.tls_version == "tlsv1.2":
tlsVersion = ssl.PROTOCOL_TLSv1_2
elif args.tls_version == "tlsv1.1":
tlsVersion = ssl.PROTOCOL_TLSv1_1
elif args.tls_version == "tlsv1":
tlsVersion = ssl.PROTOCOL_TLSv1
elif args.tls_version is None:
tlsVersion = None
else:
print ("Unknown TLS version - ignoring")
tlsVersion = None
if not args.insecure:
cert_required = ssl.CERT_REQUIRED
else:
cert_required = ssl.CERT_NONE
mqttc.tls_set(ca_certs=args.cacerts, certfile=None, keyfile=None, cert_reqs=cert_required, tls_version=tlsVersion)
if args.insecure:
mqttc.tls_insecure_set(True)
if args.username or args.password:
mqttc.username_pw_set(args.username, args.password)
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
if args.debug:
mqttc.on_log = on_log
print("Connecting to "+args.host+" port: "+str(port))
mqttc.connect(args.host, port, args.keepalive)
mqttc.subscribe(args.topic, args.qos)
mqttc.loop_forever()
</code></pre>
|
<python><c><mqtt><paho><qos>
|
2023-04-06 13:57:28
| 1
| 3,687
|
DrBwts
|
75,950,366
| 1,485,926
|
Common mocks defined with @patch to several test case functions in Python
|
<p>I have this testing code in Python using mocks (simplified):</p>
<pre><code>from unittest import TestCase
from mock import patch
class TestClass(TestCase):
@patch("mymodule.function1")
@patch("mymodule.function2")
@patch("mymodule.function3")
def test_case_1(self, function3_mock, function2_mock, function1_mock):
# code for test_case_1
...
@patch("mymodule.function1")
@patch("mymodule.function2")
@patch("mymodule.function3")
def test_case_2(self, function3_mock, function2_mock, function1_mock):
# code for test_case_2
...
@patch("mymodule.function1")
@patch("mymodule.function2")
@patch("mymodule.function3")
def test_case_3(self, function3_mock, function2_mock, function1_mock):
# code for test_case_3
...
...
</code></pre>
<p>I wonder if there is some way of simplifying this, so:</p>
<ul>
<li>I don't repeat all the time the three <code>@patch(...)</code> statements in each test case function</li>
<li>I don't need to pass the mock function to the test case function, so I can call write just <code>def test_case_1(self)</code> for instance</li>
</ul>
<p>Is that possible? Could you provide some hints/advice?</p>
<p>Thanks in advance!</p>
|
<python><python-unittest><python-mock>
|
2023-04-06 13:57:02
| 1
| 12,442
|
fgalan
|
75,950,294
| 2,263,683
|
How to handle exceptions for all the sub apps in FastAPI
|
<p>I have a FastAPI project containing multiple sub apps (The sample includes just one sub app).</p>
<pre><code>main_app = FastAPI()
class CustomException(Exception):
def __init__(self, message: str, status_code: int, name: str = "Exception"):
Exception.__init__(self)
self.name = name
self.status_code = status_code
self.message = message
@main_app.exception_handler(CustomException)
async def custom_exception_handler(exception: CustomException) -> JSONResponse:
return JSONResponse(
status_code=exception.status_code, content={"error": exception.message}
)
main_app.mount("/subapp", subapp1)
</code></pre>
<p>I've handled the exceptions in main app, but not in <code>subapp1</code>. Now if I use the <code>CustomException</code> in <code>subapp1</code>:</p>
<pre><code>raise CustomException(
status_code=status.HTTP_404_NOT_FOUND,
message=f"{self.model.__name__} not found",
)
</code></pre>
<p>I get this error:</p>
<blockquote>
<p>RuntimeError: Caught handled exception, but response already started.</p>
</blockquote>
<p>It seems like when raising <code>CustomException</code> in a sub app, it won't be handled by the main app exception handler. So how can I handle the exceptions from all the sub app using the main app exception handler?</p>
|
<python><exception><fastapi>
|
2023-04-06 13:49:01
| 1
| 15,775
|
Ghasem
|
75,950,275
| 5,295,802
|
pytest does not work as expected combined with @cache
|
<p><em>Question updated after the reply from larsks</em></p>
<p>I'm having trouble writing a unit test in Pytest for a cached class. I'm trying to patch <code>slowfunc</code> in the code below with <code>mockfunc</code>. However, the patch only appears to succeed when I'm not using <code>@cache</code>.</p>
<pre><code>import pytest
from functools import cache
from unittest.mock import patch
@cache
class A:
def __init__(self):
print("calling init")
def slowfunc(self, text):
print("calling slowfunc:", text)
return False
def call(self):
return self.slowfunc("blah")
class B:
def call(self):
a = A()
return a.call()
class Test_B:
def mockfunc(self, text):
print("calling mockfunc:", text)
return True
@patch.object(A, 'slowfunc', mockfunc)
def test_B(self):
b = B()
result = b.call()
assert result == True
if __name__ == "__main__":
retcode = pytest.main(["-xs", __file__])
</code></pre>
<p>Running the code with <code>@cache</code> commented out gives the expected result:</p>
<pre><code>example.py calling init
calling mockfunc: blah
.
=== 1 passed in 0.07s ===
</code></pre>
<p>With <code>@cache</code> enabled it fails:</p>
<pre><code>example.py calling init
calling slowfunc: blah
F
=== FAILURES ===
___ Test_B.test_B ___
self = <example.Test_B object at 0x7f305eaaa1f0>
@patch.object(A, 'slowfunc', mockfunc)
def test_B(self):
b = B()
result = b.call()
> assert result == True
E assert False == True
example.py:27: AssertionError
=== short test summary info ===
FAILED example.py::Test_B::test_B - assert False == True
!!!! stopping after 1 failures !!!
=== 1 failed in 0.23s ===
</code></pre>
<p><code>slowfunc</code> is called in this case, and the test fails. What's going on? Using <code>A.cache_clear()</code> at the start of the test does not resolve the situation either.</p>
|
<python><pytest>
|
2023-04-06 13:46:10
| 1
| 881
|
Sander
|
75,950,196
| 15,178,267
|
Django: How to filter django objects based on month?
|
<p>I am trying to get/count how many orders that were made in a month, i have written some logic to do this, but the issue is this: It does not count how many total orders were made in a month, it spreads different orders on the same month.</p>
<p>To be more explicit, look at the reponse below:</p>
<p><strong>This is how to the queryset looks now</strong></p>
<pre><code><QuerySet [{'month': 4, 'count': 1}, {'month': 6, 'count': 1}, {'month': 6, 'count': 1}]>
</code></pre>
<p><strong>This is how to the expected queryset should look</strong></p>
<pre><code><QuerySet [{'month': 4, 'count': 1}, {'month': 6, 'count': 2}]>
</code></pre>
<p>The <code>'month':4</code> is <code>'month':April</code> and <code>'month':6</code> is <code>'month':June</code></p>
<hr />
<p>This is the code i have written to do this, but does not work</p>
<p><strong>models.py</strong></p>
<pre><code>
class CartOrder(models.Model):
vendor = models.ManyToManyField(Vendor)
...
date = models.DateTimeField(auto_now_add=False)
</code></pre>
<p><strong>views.py</strong></p>
<pre><code>import calendar
from django.db.models.functions import ExtractMonth
orders = CartOrder.objects.annotate(month=ExtractMonth('date')).values('month').annotate(count=Count('id')).values('month','count')
print(orders)
</code></pre>
<p>terminal</p>
<pre><code><QuerySet [{'month': 4, 'count': 1}, {'month': 6, 'count': 1}, {'month': 6, 'count': 1}]>
</code></pre>
|
<python><django><django-models><django-rest-framework><django-views>
|
2023-04-06 13:38:05
| 1
| 851
|
Destiny Franks
|
75,949,991
| 20,920,790
|
How to ignore IndexError in while/for loops?
|
<p>I need to find index of value "1.2 Information" in table.</p>
<p>Where's only one value like this, and it could be at any column.
I need to get index of row with this value.
I got this code to find it, but I get IndexError in first column.
How to ignore error and continue loop?</p>
<p>I know that I can do this with 'continue', can't understand how.</p>
<pre><code>ind = ""
cols = list(df.columns)
while type(ind) != int:
for col in cols:
ind = int(df[df[col].str.contains('^1.2 Information') == True].index[0])
</code></pre>
<p><a href="https://docs.google.com/spreadsheets/d/1YfbBDom1ISKPRIvkBa6oqnsc426ghzk3/edit?usp=sharing&ouid=113752785996722037226&rtpof=true&sd=true" rel="nofollow noreferrer">Table</a></p>
<pre><code>01.01.* - 31.12.*
1.1
No. No. Date 1 Time
1231 46546 21:15:27
No. No. Date 1 Time
789798 45648 15:20:38
1.2 Information
</code></pre>
<p>Thanks.</p>
|
<python><pandas>
|
2023-04-06 13:17:31
| 1
| 402
|
John Doe
|
75,949,975
| 10,437,727
|
Struggling with batch processing in Azure Table Storage locally
|
<p>I have these batches that contain more than 100 entities that I'm trying to split to send in my local Azure storage account (Azurite):</p>
<pre class="lang-py prettyprint-override"><code>def save_results_in_database(self, operations, table_name):
table = self.table_service_client.get_table_client(table_name)
if table_name is None:
raise Exception(f"Table {table_name} does not exist !")
try:
table.submit_transaction(operations)
except Exception as e:
logging.exception(
f"Error while saving results in database for table {table_name}"
)
if 0 < len(results) < 100:
helpers.save_results_in_database(results, action)
else:
# if the number of results is greater than 100, we need to split them in batches of 50
# and save them in batches
batch_size = 50
for i in range(0, len(results), batch_size):
batch = results[i : i + batch_size]
helpers.save_results_in_database(batch, action)
sleep(10)
</code></pre>
<p>And for some reason somes batches pass and some don't. For example if I have 107 entities to push, the first 50 pass, the second 50 doesn't and the remaining 7 pass.</p>
<p>I tried putting some sleep but I'm not sure it actually helps.
Here's the error message:</p>
<pre><code>Error while saving results in database for table <table name>
File "/usr/local/lib/python3.10/site-packages/azure/data/tables/_table_client.py", line 734, in submit_transaction
return self._batch_send(self.table_name, *batched_requests.requests, **kwargs) # type: ignore
File "/usr/local/lib/python3.10/site-packages/azure/data/tables/_base_client.py", line 334, in _batch_send
raise decoded
azure.data.tables._error.TableTransactionError: 2:An error occurred while processing this request.
ErrorCode:InvalidInput
Content: {"odata.error":{"code":"InvalidInput","message":{"lang":"en-US","value":"2:An error occurred while processing this request.\nRequestId:994b1eca-1109-4ff9-aa56-0dc73ae97a18\nTime:2023-04-06T13:08:29.278Z"}}}
</code></pre>
<p>Am I missing something? Because I'm fairly certain that the input is valid schema-wise.
TIA</p>
|
<python><azure><azure-table-storage>
|
2023-04-06 13:15:44
| 1
| 1,760
|
Fares
|
75,949,951
| 11,169,692
|
How to convert dict into array of objects in python
|
<p>I have a dict list <code>dict(streams_list)</code> which gives values example- <code>{'Generic': ['_96_fkGECEeyqHrLeykGtFQ'], 'SF1B': ['_9lG7AJ8PEey0L88pC_veNw']}</code></p>
<p>How can I convert this to array of objects ? example -</p>
<p><code>[{'Generic': '_96_fkGECEeyqHrLeykGtFQ'}, {'SF1B': '_9lG7AJ8PEey0L88pC_veNw'},....]</code></p>
|
<python>
|
2023-04-06 13:14:03
| 5
| 503
|
NoobCoder
|
75,949,872
| 12,436,050
|
Group by and concatenate the columns in pandas dataframe
|
<p>I have following dataframe.</p>
<pre><code> id1 id2 id3 lan term
0 100000000006 100000023268 10000 en Abnormal pain
1 100000000006 100000023268 10000 zh jhkghdgh
2 100000000006 100000023268 10000 cs ghjdgfhgd
3 100000000006 100000023268 10000 nl jgfhgjhgfh
4 100000000006 100000023268 10000 fr hgdhfghjgeh
5 100000000006 100000023269 10000 en pain
6 100000000006 100000023269 10000 fr hgdhfghjgehd
7 100000000006 100000023269 10000 nl hgdhfghjgehdff
</code></pre>
<p>I would like to group by column id1, id2, id3 and concatenate the 'term' column values where lan is not 'en' and create a new column for this. The expected dataframe is:</p>
<pre><code> id1 id2 id3 term synonyms
0 100000000006 100000023268 10000 Abnormal pain jhkghdgh |ghjdgfhgd|jgfhgjhgfh|hgdhfghjgeh
3 100000000006 100000023269 10000 pain hgdhfghjgehd|hgdhfghjgehdff
</code></pre>
<p>How can I achive this. I am using below code but without any filter on 'lan' column.</p>
<pre><code>join_unique = lambda x: '|'.join(x.unique())
df_meddra_qtt = df_meddra.groupby(['id1', 'id2', 'id3'], as_index=False).agg(join_unique)
</code></pre>
|
<python><pandas><concatenation>
|
2023-04-06 13:05:38
| 2
| 1,495
|
rshar
|
75,949,728
| 21,521,861
|
PyAutoGUI - error caused by mouse on second monitor?
|
<p>I have a program that uses PyAutoGUI to auto-sign me into work by opening programs, clicking things in timed order, etc. I set up a logging error text file and this morning it said the following: <code>ERROR:root:2023-04-06 08:00:03.184901 - PyAutoGUI fail-safe triggered from mouse moving to a corner of the screen. To disable this fail-safe, set pyautogui.FAILSAFE to False. DISABLING FAIL-SAFE IS NOT RECOMMENDED.</code></p>
<p>I went ahead and disabled this issue using <code>pyautogui.FAILSAFE = False</code>. Question is, could this error be caused by my mouse being dormant on my second monitor when the program is triggered to run? The mouse doesn't slide, but instead uses moveTo to "teleport" to the coordinate I need it at.</p>
<p>I know the error gets raised when the mouse reaches the upper left corner (0,0), so is it possible the mouse teleporting from one screen to the other temporarily sets the mouse value as (0,0) thus causing the error?</p>
<p>Thanks,</p>
|
<python><python-3.x><pyautogui>
|
2023-04-06 12:49:39
| 0
| 473
|
Caleb Carson
|
75,948,875
| 180,231
|
How can I use the ZBar libraries in a python Azure function?
|
<p>I am attempting to write a simple Azure Function app in Python.</p>
<p>My function app work fine in the local simulator but when I attempt to publish it to Azure, it fails with this error:</p>
<pre><code>Exception while executing function: Functions.ProcessPDF Result: Failure
Exception: ImportError: Unable to find zbar shared library. Please check the requirements.txt file for the missing module.
</code></pre>
<p>My understanding is that the ZBar libraries cannot be found by the runtime environment (Lunix x64 for Azure Functions).</p>
<p>My "requirements.txt" file does not contain <code>zbar</code> but it does contain <code>pyzbar</code> which is the wrapper I am using.</p>
<p>My question is: how can I deploy the necessary libraries in the host in Azure functions?</p>
|
<python><azure><azure-functions>
|
2023-04-06 11:14:27
| 1
| 3,442
|
Stephane
|
75,948,844
| 11,321,089
|
How to convert an 8bpp bitmap to 1bpp bitmap in Python
|
<p>I have some code which is fine for creating greyscale (8bpp) images but I need to create 1bpp (binary) also for a printer. I have seen 2 posts here but cannot understand how they fix the issue.
<a href="https://stackoverflow.com/questions/21067028/cant-format-bmp-image-data-to-1-bit-per-pixel-in-pil">Can't format BMP image data to 1 bit per pixel in PIL</a>
I have pillow installed but call it using PIL as all the tutorials I have read seem to say to import Image from PIL.</p>
<p>I have a method called conv_to_1bpp which sets anything at 255 equal to 1, this is still making 8bpp images though.</p>
<p><strong>Code</strong></p>
<pre><code>from PIL import Image
import numpy as np
import os
import sys
import struct
class BmpMaker:
def __init__(self):
self.ffp = None
self.img_width = None
self.img_height = None
self.ws_activation = None
self.bpp = None
def make_image(self, img_width, img_height, ws_activation):
"""Creates a bitmap."""
self.ffp = None
self.img_width = img_width
self.img_height = img_height
self.ws_activation = ws_activation
# Create new black image - L mode for b/w
img = Image.new('L', (img_width, img_height))
# Convert to Numpy array for easy processing
na = np.array(img)
# set the amount of white space activation
white_rows = ws_activation
# make white lines
na[0:white_rows, 0:999] = 255
# Revert to PIL Image from Numpy array and save
self.ffp = self.make_img_title(img_width, img_height, ws_activation)
Image.fromarray(na).save(self.ffp)
self.bpp = self.get_bitdepth()
return self.ffp
def make_img_title(self, img_width, img_height, ws_activation):
if ws_activation == 0:
mystr = f"{img_height}x{img_width}"
elif ws_activation is not None:
mystr = f"{ws_activation}_{img_height}x{img_width}"
self.ffp = os.path.join(os.getcwd(), mystr + ".bmp")
print("img_ffp : ", self.ffp)
return self.ffp
def get_bitdepth(self):
# Read first 100 bytes
with open(self.ffp, 'rb') as f:
BMP = f.read(100)
if BMP[0:2] != b'BM':
sys.exit('ERROR: Incorrect BMP signature')
# Get BITMAPINFOHEADER size - https://en.wikipedia.org/wiki/BMP_file_format
BITMAPINFOHEADERSIZE = struct.unpack('<i', BMP[14:18])[0]
okSizes = [40, 52, 56, 108, 124]
if BITMAPINFOHEADERSIZE not in okSizes:
sys.exit(f'ERROR: BITMAPINFOHEADER size was {BITMAPINFOHEADERSIZE},'
f' expected one of {okSizes}')
# Get bits per pixel
self.bpp = struct.unpack('<H', BMP[28:30])[0]
print(f'bbp: {self.bpp}')
return self.bpp
def get_img_bitdepth(self, img):
# Read first 100 bytes
with open(img, 'rb') as f:
BMP = f.read(100)
if BMP[0:2] != b'BM':
sys.exit('ERROR: Incorrect BMP signature')
# Get BITMAPINFOHEADER size - https://en.wikipedia.org/wiki/BMP_file_format
BITMAPINFOHEADERSIZE = struct.unpack('<i', BMP[14:18])[0]
okSizes = [40, 52, 56, 108, 124]
if BITMAPINFOHEADERSIZE not in okSizes:
sys.exit(f'ERROR: BITMAPINFOHEADER size was {BITMAPINFOHEADERSIZE},'
f' expected one of {okSizes}')
# Get bits per pixel
img_bpp = struct.unpack('<H', BMP[28:30])[0]
print(f'bbp: {img_bpp}')
return img_bpp
def conv_to_1bpp(self):
img = Image.open(self.ffp)
arr = np.array(img)
#print(arr)
# Set all values at indices where the array equals 255 to 1.
arr[arr==255] = 1
print('\n'*3, arr)
Image.fromarray(arr).save("my_img.bmp")
print(self.get_img_bitdepth("my_img.bmp"))
if __name__ == "__main__":
import PIL
print('Pillow Version:', PIL.__version__)
bm = BmpMaker()
base_image = bm.make_image(1000, 8, 5)
print("bitmap ffp: ", bm.ffp)
print("bitmap bitdepth : ", bm.bpp)
bm.conv_to_1bpp()
</code></pre>
|
<python><bitmap><python-imaging-library><bit><bit-depth>
|
2023-04-06 11:10:34
| 1
| 909
|
Windy71
|
75,948,838
| 7,421,447
|
Could you create a website font-end using Python Tkinter?
|
<p>I have a question. Would it be possible to create web apps using Python Tkinter for front end? The reason, that to create a website you need to know a lot of things. Such as HTML/CSS/JS. Would it be possible create browser based apps using python only?</p>
|
<python><python-3.x><tkinter><browser>
|
2023-04-06 11:10:12
| 2
| 713
|
Alain Michael Janith Schroter
|
75,948,087
| 3,116,231
|
Pass class method name as a parameter
|
<p>I want to change the last line of following code</p>
<pre><code>import io
import pandas as pd
writer = io.BytesIO()
data = [{"createdAt": 2021, "price": 10}, {"createdAt": 2022, "price": 20} ]
pd.DataFrame(data).to_csv(self.writer, header="true", index=False)
</code></pre>
<p>so that I can pass the name of the class method <code>to_csv</code> as an argument.</p>
<p>Like</p>
<pre><code>f = lambda x: pd.DataFrame(data).x(self.writer, header="true", index=False)
f('to_csv') # should do exactly the same as pd.DataFrame(data).x(.....
</code></pre>
<p>I tried <code>to_csv</code>, <code>to_csv()</code> as an argument as well. May I ask for help for fixing this?</p>
|
<python><pandas>
|
2023-04-06 09:46:23
| 1
| 1,704
|
Zin Yosrim
|
75,948,040
| 1,511,274
|
Identify the timestamps of the merged audio signal
|
<p>I have an audio file which was created by substituting multiple speech segments into an original (speech) utterance. The two speakers sound quite similar to each other.
I want to find the timestamps where such substitutions happened, so I guess that one thing I can do is looking for the abrupt changes in the audio waveform.</p>
<p>By visualizing the waveform, I have something like below. There was a sudden shift in the middle of the figure, which implies the fusion of the two speech segments.</p>
<pre class="lang-python prettyprint-override"><code>fig, (ax, ax2) = plt.subplots(nrows=2, sharex=True)
ax.set(xlim=[1.5, 1.6], title='Sample view', ylim=[-1, 1])
y, sr = librosa.load("example.wav", sr=None,duration=10)
y_harm, y_perc = librosa.effects.hpss(y)
librosa.display.waveshow(y, sr=sr, ax=ax, marker='.', label='Full signal')
librosa.display.waveshow(y_harm, sr=sr, alpha=0.5, ax=ax2, label='Harmonic')
librosa.display.waveshow(y_perc, sr=sr, color='r', alpha=0.5, ax=ax2, label='Percussive')
</code></pre>
<p><a href="https://i.sstatic.net/WdQSb.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/WdQSb.png" alt="waveform visualization" /></a></p>
<p>I found some answer <a href="https://dsp.stackexchange.com/questions/83813/how-to-identify-sudden-changes-in-signals">here</a> and <a href="https://dsp.stackexchange.com/questions/66380/detect-abrupt-changes-in-signal">here</a> which suggested</p>
<blockquote>
<p>differentiate the signal numerically and threshold the magnitude of
differentiate to identify the abrupt changes</p>
</blockquote>
<p>I have tried using the sliding window and threshold to find such changes but the result was not as expected with too many false positives.</p>
<p><strong>My question is:</strong> how to find such abrupt changes and <strong>their timestamps</strong> programmatically by using any (maybe, python-based) open-source tools? Machine learning-based approaches are welcome too.</p>
<p>Note that the segment merged done by waveform overlapping and the amplitude is <a href="https://www.itu.int/rec/T-REC-G.191/en" rel="nofollow noreferrer">normalized</a>. I think it will make it harder to locate such fusion points. I am not sure I used to right terms for this. Please suggest the right ones if you I think there are proper terms to denote what I have described so far.</p>
|
<python><machine-learning><deep-learning><signal-processing><speech>
|
2023-04-06 09:40:29
| 0
| 1,845
|
Long
|
75,947,977
| 567,059
|
Compare objects in a list to identify those with certain identical key/value pairs and those without
|
<p>Using Python, how can I find objects in a list that share certain key/value pairs, then create two separate lists - one for objects that share those certain key/value pairs, and one for objects that don't?</p>
<p>For example, take the following simple list -</p>
<pre class="lang-json prettyprint-override"><code>[
{
"id": "111",
"host": "aaa",
"path": "/b/c/d"
},
{
"id": "222",
"host": "bbb",
"path": "/x/y/z"
},
{
"id": "333",
"host": "aaa",
"path": "/b/c/d"
},
{
"id": "444",
"host": "aaa",
"path": "/b/c/d"
}
]
</code></pre>
<p>I'd like to end up with two lists -</p>
<ul>
<li><p>Objects with duplicate <code>host</code> and <code>path</code>.</p>
<pre class="lang-json prettyprint-override"><code>[
{
"host": "aaa",
"path": "/b/c/d"
"ids": [
"111",
"333",
"444",
}
]
</code></pre>
</li>
<li><p>Objects without duplicate <code>host</code> and <code>path</code>.</p>
<pre class="lang-json prettyprint-override"><code>[
{
"id": "222",
"host": "bbb",
"path": "/x/y/z"
}
]
</code></pre>
</li>
</ul>
<p>My best attempt so far has yielded two lists, but all of the objects in the original list are added to <code>dups_list</code>, regardless of whether or not they are actually duplicates.</p>
<p>Please note that I have tried taking a <code>deepcopy</code> of <code>main_list</code> to use in the second <code>for</code> statement, but that yielded the exact same results.</p>
<pre class="lang-py prettyprint-override"><code>>>> import jsonpickle
>>> main_list = list((dict(Id="111",host="aaa",path="/b/c/d"),dict(Id="222",host="bbb",path="/x/y/z"),dict(Id="333",host="aaa",path="/b/c/d"),dict(Id="444",host="aaa",path="/b/c/d")))
>>> dups_list = list()
>>> non_dups_list = list()
>>> for o in main_list:
... is_duplicate = False
... for o2 in main_list:
... if o2['host'] == o['host'] and o2['path'] == o['path']:
... is_duplicate = True
... break
... if is_duplicate:
... dups_list.append(o)
... else:
... non_dups_list.append(o)
...
>>> print(jsonpickle.encode(non_dups_list, indent=4))
[]
>>> print(jsonpickle.encode(dups_list, indent=4))
[
{
"Id": "111",
"host": "aaa",
"path": "/b/c/d"
},
{
"Id": "222",
"host": "bbb",
"path": "/x/y/z"
},
{
"Id": "333",
"host": "aaa",
"path": "/b/c/d"
},
{
"Id": "444",
"host": "aaa",
"path": "/b/c/d"
}
]
</code></pre>
|
<python><list><object><comparison>
|
2023-04-06 09:34:14
| 2
| 12,277
|
David Gard
|
75,947,847
| 12,870,750
|
Two sync QGrapchisView layers miss aligned scene rect after zoom event, but aligned after pan events
|
<p>I have two classes of edited <code>QGrapchicsView</code>, one (<code>GraphicsView</code>) shows lines and it enables zoom and pan. The second class (<code>PolygonGrapchisView</code>) only updates the scene rect to match that of the first class <code>GraphicsView</code> from a signal receive from the first class. The pan events is triggered by the middle button</p>
<p><strong>The Issue</strong></p>
<p>The <code>PolygonGrapchisView</code> class receives the signal from the <code>GraphicsView</code> class and updates the scene rect to match the extent on both classes.</p>
<p>Regardless of the position or zoom level, the signal from the <code>mousePressEvent</code>, <code>mouseReleaseEvent</code> and <code>mouseMoveEvent</code> functions (pan events) from the <code>GraphicsView</code> class set the scene rect on both classes correctly. What I mean by correctly, is that it sets the rect scene in the two classes so that the polygons and the lines stay in the same position relative to each other, after the events.</p>
<p>When I try to do the same with <code>wheelEvent</code> (zoom event) it has two behaviors. The first one is when the zoom event is done when the scroll bar is full (occupies the whole horizontal and vertical bars, there is no room to move the scrollbar) or we are doing a zoom out, here it works 'correctly'.</p>
<p>The second, is when we began to zoom in until the scroll bars activates
and start to have room to move, the signal to match the scene rect fails. It miss aligns the two graphicsview classes, meaning that the polygon and the line do not stay in the same position relative to each other but start to overlap or partway from each other. You can fix this miss alignment issue if you stop moving the wheel and just press the middle bottom and pan the scene.</p>
<p>This is the initial status of the plot, this is how it should stay after all the mouse events.</p>
<p><a href="https://i.sstatic.net/EpslU.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/EpslU.png" alt="enter image description here" /></a></p>
<p>This is the one where the failure occurs when you do a zoom in until you activate the scroll bars.</p>
<p><a href="https://i.sstatic.net/pJeWN.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/pJeWN.png" alt="enter image description here" /></a>
<strong>Expected behavior</strong></p>
<p>The scene from the <code>PolygonGrapchisView</code> class is updated 'correctly' when we do a pan or zoom event in the <code>GraphicsView</code> class, regardless from the zoom level or the position of the scrollbars. It keeps the relative distance between polygon and lines during and after the mouse events.</p>
<p>Code</p>
<pre><code>from PyQt5 import QtWidgets, QtGui, QtCore
import sys
class PolygonGraphicsView(QtWidgets.QGraphicsView):
def __init__(self, scene, parent=None):
super(PolygonGraphicsView, self).__init__(scene, parent)
# Set the anchor point for zooming and resizing
self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
self.setResizeAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
# Disable the scrollbars
self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
@QtCore.pyqtSlot(QtCore.QRectF, QtGui.QTransform)
def setBounds(self, rect_scene, transform_matrix):
#set scene rect
self.setSceneRect(rect_scene)
# Update the transformation matrix to match GraphicsView
self.setTransform(transform_matrix)
class GraphicsView(QtWidgets.QGraphicsView):
#seΓ±al para cambiar el viewport del qgrapichsview de los poligonos
scene_rect_changed = QtCore.pyqtSignal(QtCore.QRectF, QtGui.QTransform)
def __init__(self, scene, parent=None):
super(GraphicsView, self).__init__(scene, parent)
# "variables iniciales"
self.pos_init_class = None
self.scale_factor = 1.5
# # Set the anchor point for zooming and resizing
self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
self.setResizeAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
def send_polygon_graphicsView_update(self):
# Emit the scene_rect_changed signal with the transformation matrix
new_rect = self.sceneRect()
self.scene_rect_changed.emit(new_rect, self.transform())
def mousePressEvent(self, event):
pos = self.mapToScene(event.pos())
# "pan mouse"
if event.button() == QtCore.Qt.MiddleButton:
self.pos_init_class = pos
#update position
self.send_polygon_graphicsView_update()
else:
super(GraphicsView, self).mousePressEvent(event)
def mouseReleaseEvent(self, event):
# pan
if self.pos_init_class and event.button() == QtCore.Qt.MiddleButton:
self.pos_init_class = None
# update position
self.send_polygon_graphicsView_update()
else:
super(GraphicsView, self).mouseReleaseEvent(event)
def mouseMoveEvent(self, event):
if self.pos_init_class:
# "pan"
delta = self.pos_init_class - self.mapToScene(event.pos())
r = self.mapToScene(self.viewport().rect()).boundingRect()
self.setSceneRect(r.translated(delta))
# update position
self.send_polygon_graphicsView_update()
super(GraphicsView, self).mouseMoveEvent(event)
def wheelEvent(self, event):
old_pos = self.mapToScene(event.pos())
# Determine the zoom factor
if event.angleDelta().y() > 0:
zoom_factor = self.scale_factor
else:
zoom_factor = 1 / self.scale_factor
# Apply the transformation to the view
transform = QtGui.QTransform()
transform.translate(old_pos.x(), old_pos.y())
transform.scale(zoom_factor, zoom_factor)
transform.translate(-old_pos.x(), -old_pos.y())
# Get the current transformation matrix and apply the new transformation to it
current_transform = self.transform()
self.setTransform(transform * current_transform)
# update position
self.send_polygon_graphicsView_update()
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
# apply transparent style sheet
self.this_style_sheet = """
background-color: transparent;
selection-background-color:transparent;
"""
self.transparent_viewport_style_sheet = """
background-color: transparent;
"""
# Geometry of the window
self.geometry = QtCore.QRect(0, 0, 800, 500)
self.scene_rect_value = QtCore.QRectF(721200.96, -9679800.97, 500, -500)
self.setGeometry(self.geometry)
# Create central widget and layout
central_widget = QtWidgets.QWidget()
layout = QtWidgets.QGridLayout()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
# Polygon graphics view widget (bottom layer)
self.polygon_scene = QtWidgets.QGraphicsScene()
self.polygon_graphicsView = PolygonGraphicsView(scene=self.polygon_scene, parent=self)
self.polygon_graphicsView.setSceneRect(self.scene_rect_value)
layout.addWidget(self.polygon_graphicsView, 0, 0)
# Graphics view widget (top layer)
self.scene = QtWidgets.QGraphicsScene()
self.graphicsView = GraphicsView(scene=self.scene, parent=self)
self.graphicsView.setSceneRect(self.scene_rect_value)
self.graphicsView.setStyleSheet(self.this_style_sheet)
self.graphicsView.viewport().setStyleSheet(self.transparent_viewport_style_sheet)
layout.addWidget(self.graphicsView, 0, 0)
#seΓ±al para el qgrapichsview de poligonos
self.graphicsView.scene_rect_changed.connect(self.polygon_graphicsView.setBounds)
# Dummy line and polygon generator
self.dummy_lines_polygons()
def dummy_lines_polygons(self):
polygon_list = [[[721278.105, 9679978.402], [721378.918, 9679958.288], [721395.355, 9680058.781], [721294.491, 9680079.538]],
[[721398.840, 9679959.473], [721486.867, 9679930.441], [721502.381, 9680029.483], [721416.757, 9680055.152]]]
for pol in polygon_list:
polygon = QtGui.QPolygonF()
for item in pol:
x = item[0]
y = -item[1]
polygon.append(QtCore.QPointF(x, y))
polygon_item = QtWidgets.QGraphicsPolygonItem(polygon)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 255))
polygon_item.setBrush(brush)
self.polygon_scene.addItem(polygon_item)
# add some lines to the line view
line_list = [[[721385.198, 9679948.971], [721404.402, 9680064.235] ], [[721404.402, 9680064.235], [721512.651, 9680035.611]]]
pen = QtGui.QPen(QtGui.QColor(255, 0, 0))
for line in line_list:
x1 = line[0][0]
y1 = -line[0][1]
x2 = line[1][0]
y2 = -line[1][1]
line = QtWidgets.QGraphicsLineItem(x1, y1, x2, y2)
line.setPen(pen)
self.scene.addItem(line)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
</code></pre>
|
<python><pyqt5><qt5><qgraphicsview>
|
2023-04-06 09:20:46
| 1
| 640
|
MBV
|
75,947,797
| 2,560,292
|
Modify response to get a list of IDs and not a list of dict when referencing ForeignKeys
|
<p>I have a simple app that creates and stores tickets. Those tickets can cross-references themselves, so I use a specific table to keep this kind of information. A greatly simplified table structure is like this:</p>
<pre class="lang-py prettyprint-override"><code>class Ticket(Base):
"""Ticket."""
__tablename__ = "tickets"
id = Column(Integer, primary_key=True, autoincrement="auto")
title = Column(String(50), nullable=False)
children_tickets = relationship(
"TicketReferences",
primaryjoin="Ticket.id == TicketReferences.parent_id",
cascade="all, delete-orphan"
)
parents_tickets = relationship(
"TicketReferences",
primaryjoin="Ticket.id == TicketReferences.child_id",
cascade="all, delete-orphan"
)
class TicketReferences(Base):
"""Tickets can be cross-referenced"""
__tablename__ = "tickets_references"
id = Column(Integer, primary_key=True, autoincrement="auto")
parent_id = Column(Integer, ForeignKey("tickets.id"), nullable=False)
child_id = Column(Integer, ForeignKey("tickets.id"), nullable=False)
</code></pre>
<p>Then I declare the corresponding schemas for Pydantic:</p>
<pre class="lang-py prettyprint-override"><code>class TicketsReferences(BaseModel):
parent_id: int
child_id: int
class Config:
orm_mode = True
class TicketCreate(TicketBase):
title: str
parents_tickets: Optional[List[int]] = []
children_tickets: Optional[List[int]] = []
class Ticket(TicketBase):
id: int
title: str
parents_tickets: List[TicketsReferences]
children_tickets: List[TicketsReferences]
class Config:
orm_mode = True
</code></pre>
<p>So then I can create tickets with those POST bodies:</p>
<pre class="lang-json prettyprint-override"><code># Creates a first ticket which id will be 1
{
"title": "Foo",
"parents_tickets": [],
"children_tickets": [],
}
# Creates a second ticket referencing ticket 1 as a parent
{
"title": "Bar",
"parents_tickets": [1],
"children_tickets": [],
}
</code></pre>
<p>The issue is when I request one of those ticket I get an overly complex structure for either <code>parents_tickets</code> or <code>children_tickets</code>:</p>
<pre class="lang-json prettyprint-override"><code># Fetch ticket #2
{
"id": 2,
"title": "bar",
"parents_tickets": [
{
"parent_id": 1,
"child_id": 2
}
],
"children_tickets": []
}
</code></pre>
<p>I'd like to get a list of id like this: <code>"parents_tickets": [1]</code> and that's it. How do I do that?</p>
|
<python><fastapi><pydantic>
|
2023-04-06 09:14:41
| 1
| 1,196
|
Shan-x
|
75,947,699
| 15,524,481
|
Django: apply constraint on 'choices'-based property on model
|
<p>I want to apply a constraint in the following way:
<br>
Imagine that you have a Charfield property with some choices.</p>
<pre class="lang-py prettyprint-override"><code>class ExampleChoices(models.TextChoices):
A = "A", "a"
B = "B", "b"
C = "C", "c"
D = "D", "c"
class ExampleModel(models.Model, PublishModelMixin):
property = models.CharField(choices=ExampleChoices.choices, default=ExampleChoices.A)
</code></pre>
<p>I now want to put constraints on two of those choices, rules:</p>
<ol>
<li>If choice C is used I want it to be unique and cannot be used anywhere else, with that D cannot be used at all</li>
<li>The same rule applies for when D is used, D must be unique and C cannot be used anywhere else.</li>
<li>In the previous occasions all other choices can just be used like normally.</li>
</ol>
<p>How would I achieve this?</p>
|
<python><django>
|
2023-04-06 09:03:55
| 2
| 458
|
Xander
|
75,947,688
| 5,909,136
|
Install python package on a specific folder instead of user level
|
<p>So I am currently working on a DevOps task for a Python repository.
I am tasked with making the repository work properly with our Docker environment.</p>
<p>My current issue is that when running <code>pip3 install</code>, it installs everything in various folders that have nothing to do with the current repository path.
This is not ideal when working with <code>docker-compose</code> for a local development environment.</p>
<p>What we want to achieve is to install <code>pip</code> dependencies once on the host machine and then mount them as a dynamic volume inside the docker container. The reason is simple, we want to be able to destroy the container as many times as we want without having to download everything again. Because this is an AI repository, you can imagine that the <code>pip</code> dependencies are heavy and take a lot of time to download. We currently have about 5 to 10GB of dependencies to download depending on the branch and current code progress.</p>
<p>Ideally, I'd like <code>pip</code> to behave like Node.JS tools such as <code>yarn</code> or <code>npm</code> where it builds a local folder (like <code>node_modules</code>) that I can easily mount inside the container.</p>
<p>I have looked through the <code>pip</code> documentation but I simply can't find a way to do this at all.</p>
<p><strong>Is there a way to constrain <code>pip</code> and <code>python</code> to install dependencies inside a specific folder and to only use those dependencies?</strong></p>
|
<python><docker><docker-compose><pip>
|
2023-04-06 09:02:53
| 2
| 411
|
SmashingQuasar
|
75,947,479
| 56,711
|
Using Pytest, can I find out which tests execute a single line of code?
|
<p>I am using pytest to run my Python tests. Is there a way I can run I'd like to know which tests cover a specific line of code. I want to be able to run just the tests that execute a specific line. I know the <code>coverage</code> tool collects related data, but I feel this use case is not covered.</p>
|
<python><pytest><code-coverage>
|
2023-04-06 08:42:45
| 1
| 6,081
|
Simon Walker
|
75,947,478
| 12,234,535
|
How to compute one mean dataset of 4 datasets [Python, xarray]
|
<p>I'm having 4 [GFS] temperature datasets: they are all the same in spatial resolution, the only difference is timestamp - they are for 00 UTC, 06 UTC, 12 UTC, 18 UTC within one day.</p>
<p>I need to <strong>compute the mean daily temperature dataset</strong>. Is there a way to do <em>instrumentally</em>, but not, like, manually pop values from corresponding nodes, compute mean and insert into a dataset?</p>
<pre><code>import xarray as xr
dst00 = xr.open_dataset('gfs.t00z.pgrb2.1p00.f000', engine='cfgrib')
dst06 = xr.open_dataset('gfs.t06z.pgrb2.1p00.f000', engine='cfgrib')
dst12 = xr.open_dataset('gfs.t12z.pgrb2.1p00.f000', engine='cfgrib')
dst18 = xr.open_dataset('gfs.t18z.pgrb2.1p00.f000', engine='cfgrib')
</code></pre>
<p>Direct links to download sample datasets:</p>
<p><a href="https://nomads.ncep.noaa.gov/cgi-bin/filter_gfs_1p00.pl?dir=%2Fgfs.20230405%2F00%2Fatmos&file=gfs.t00z.pgrb2.1p00.f000&var_TMP=on&lev_2_m_above_ground=on&subregion=&toplat=90&leftlon=0&rightlon=100&bottomlat=60" rel="nofollow noreferrer">00UTC</a>
<a href="https://nomads.ncep.noaa.gov/cgi-bin/filter_gfs_1p00.pl?dir=%2Fgfs.20230405%2F06%2Fatmos&file=gfs.t06z.pgrb2.1p00.f000&var_TMP=on&lev_2_m_above_ground=on&subregion=&toplat=90&leftlon=0&rightlon=100&bottomlat=60" rel="nofollow noreferrer">06UTC</a> <a href="https://nomads.ncep.noaa.gov/cgi-bin/filter_gfs_1p00.pl?dir=%2Fgfs.20230405%2F12%2Fatmos&file=gfs.t12z.pgrb2.1p00.f000&var_TMP=on&lev_2_m_above_ground=on&subregion=&toplat=90&leftlon=0&rightlon=100&bottomlat=60" rel="nofollow noreferrer">12UTC</a> <a href="https://nomads.ncep.noaa.gov/cgi-bin/filter_gfs_1p00.pl?dir=%2Fgfs.20230405%2F18%2Fatmos&file=gfs.t18z.pgrb2.1p00.f000&var_TMP=on&lev_2_m_above_ground=on&subregion=&toplat=90&leftlon=0&rightlon=100&bottomlat=60" rel="nofollow noreferrer">18UTC</a></p>
|
<python><arrays><dataset><mean><python-xarray>
|
2023-04-06 08:42:37
| 1
| 379
|
Outlaw
|
75,946,823
| 12,877,988
|
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1131)
|
<p>I have ubuntu server that sends request to a website. When I send request it gives</p>
<blockquote>
<p>ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED]
certificate verify failed: unable to get local issuer certificate
(_ssl.c:1131)</p>
</blockquote>
<p>error.</p>
<p>I added that website's CA certificate to my trusted certs lists. Now, I can send request with curl but not with python.</p>
<p>In python, I tried <code>verify='location/cert.pem' </code> and <code>cert='location/cert.crt' </code>, but I still get error above.</p>
<p>How to fix this issue?</p>
|
<python><python-3.x><cacerts>
|
2023-04-06 07:21:31
| 0
| 1,497
|
Elvin Jafarov
|
75,946,772
| 9,108,781
|
'pseudocorpus' no longer available from 'gensim.models.phrases'?
|
<p>Several months ago, I used "pseudocorpus" to create a fake corpus as part of phrase training using Gensim with the following code:</p>
<pre><code>from gensim.models.phrases import pseudocorpus
corpus = pseudocorpus(bigram_model.vocab, bigram_model.delimiter, bigram_model.common_terms)
bigrams = []
for bigram, score in bigram_model.export_phrases(corpus, bigram_model.delimiter, as_tuples=False):
if score >= bigram_model.threshold:
bigrams.append(bigram.decode('utf-8'))
</code></pre>
<p>Now when I run the code, I got the following error message:</p>
<pre><code>ImportError: cannot import name 'pseudocorpus' from 'gensim.models.phrases'
</code></pre>
<p>I'm using Gensim 4.2.0. Is pseudocorpus() no longer available with Gensim 4.2.0?</p>
<p>Thanks a lot!</p>
|
<python><python-3.x><gensim>
|
2023-04-06 07:12:56
| 1
| 943
|
Victor Wang
|
75,946,683
| 5,186,167
|
Is there a Python module to handle csv files with sections?
|
<p>I'm seeing more and more csv files containing multiple sections, each containing their own table. For instance this file from <a href="https://support.10xgenomics.com/single-cell-gene-expression/software/pipelines/latest/using/multi#examples" rel="nofollow noreferrer">10XGenomics</a>:</p>
<pre><code>[gene-expression]
reference,/path/to/transcriptome
[libraries]
fastq_id,fastqs,feature_types
gex1,/path/to/fastqs,Gene Expression
mux1,/path/to/fastqs,Multiplexing Capture
[samples]
sample_id,cmo_ids
sample1,CMO301
sample2,CMO303
</code></pre>
<p>Sometimes the section headers are even embedded in their own row, e.g.</p>
<pre><code>[gene-expression],,
reference,/path/to/transcriptome,
[libraries],,
fastq_id,fastqs,feature_types
gex1,/path/to/fastqs,Gene Expression
mux1,/path/to/fastqs,Multiplexing Capture
[samples],,
sample_id,cmo_ids,
sample1,CMO301,
sample2,CMO303,
</code></pre>
<p>Is there a Python module to handle this kind of sectioning directly? I couldn't find how to do it with Pandas or the <code>csv</code> module. E.g. from both examples above I would expect to get a dictionary with one item per section, and then a list of lists for each section.</p>
<p>Some sections have headers, it would be nice if this could be handled too, e.g. similarly to <code>csv.DictReader</code>.</p>
<p>Although it's not particularly hard to write a solution that can parse this particular example, producing something that works in the general case is much harder, e.g. parsing a simple csv file is easily done with <code>split</code> and yet the <code>csv</code> module is 400+ lines of Python, and many more lines of C, so what I'm really looking for here is a module to handle this problem in general.</p>
<p>PS: <a href="https://stackoverflow.com/questions/3701696/is-there-a-python-package-to-parse-readable-data-files-with-sections">this question</a> is related but the answers do not address the point about the csv parser unfortunately</p>
|
<python><pandas><csv>
|
2023-04-06 07:01:18
| 3
| 440
|
Aratz
|
75,946,672
| 3,337,089
|
PyTorch grid_sample for 2D tensors
|
<p>I have a 3D tensor <code>data</code> of shape <code>(N, W, D)</code> and another 1D tensor <code>index</code> of shape <code>(B,)</code>. I need to sample <code>data</code> using <code>index</code> such that my output should be of shape <code>(B,N,D)</code>. That is, for every element of <code>index</code>, I need to linearly interpolate <code>data</code> along dimension 1 and stack the resulting 2D tensors.</p>
<p>Is it possible to do this using PyTorch <code>grid_sample</code>? If yes, how?
The problems I'm facing are the following.</p>
<ol>
<li><code>grid_sample</code> interpolates in 2D or 3D, but not in 1D.</li>
<li>PyTorch requires batch size of <code>data</code> and <code>index</code> to be the same. But in my case, <code>data</code> does not have a batch dimension i.e., <code>data</code> is common for every element in <code>index</code>. I don't want to repeat <code>data</code>, <code>B</code> times unless there is no other way.</li>
</ol>
<p>I could write a <a href="https://github.com/NagabhushanSN95/Pose-Warping/blob/main/src/WarperPytorch.py#L212--293" rel="noreferrer">bilinear interpolation code myself</a>, but I don't want to handle all the boundary cases myself. <code>grid_sample</code> supports zero padding, which I want to use directly.</p>
|
<python><pytorch><linear-interpolation>
|
2023-04-06 06:59:43
| 0
| 7,307
|
Nagabhushan S N
|
75,946,655
| 1,384,464
|
Detecting all rectangles and contours from a jpg of a scanned structured paper form using OpenCV
|
<p>As a newbie to OCR, I am attempting to detect all the rectangles/boxes in a scanned document illustrated here <a href="https://i.sstatic.net/xp4gz.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/xp4gz.jpg" alt="JPG of structured form" /></a></p>
<p>However the output of the code snippet provided below is unable to identify a considerable number of rectangles from the image.</p>
<pre><code>import cv2
import imutils
import warnings
import numpy as np
warnings.filterwarnings('ignore')
import matplotlib.pyplot as plt
img = cv2.imread("example.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
threshold = cv2.adaptiveThreshold(
gray.copy(),
255, # maximum value assigned to pixel values exceeding the threshold
cv2.ADAPTIVE_THRESH_GAUSSIAN_C, # gaussian weighted sum of neighborhood
cv2.THRESH_BINARY_INV, # thresholding type
301, # block size (5x5 window)
21) # constant
font = cv2.FONT_HERSHEY_COMPLEX
keypoints = cv2.findContours(threshold.copy(),
cv2.RETR_CCOMP,
cv2.CHAIN_APPROX_SIMPLE)
contours = imutils.grab_contours(keypoints)
working_image = None
idx = 1
cropped_field_images = []
contour_list = list(contours)
contour_list.reverse()
rev_contours = tuple(contour_list)
for contour in rev_contours:
x,y,w,h = cv2.boundingRect(contour)
area = cv2.contourArea(contour)
approx = cv2.approxPolyDP(contour, 10, True)
location = None
if len(approx) == 4 and area > 1500 : #if the shape size is rectangular
working_image = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
cv2.putText(img, str(idx), (x, y), font, 1, (0,0,255))
location = approx
mask = np.zeros(gray.shape, np.uint8) #Create a blank mask
rect_img = cv2.drawContours(mask, [location], 0, 255, -1)
rect_img = cv2.bitwise_and(img, img, mask = mask)
(x, y) = np.where(mask==255)
(x1, y1) = (np.min(x), np.min(y))
(x2, y2) = (np.max(x), np.max(y))
cropped_rect = gray[x1:x2+1, y1:y2+1]
cropped_field_images.append(cropped_rect)
idx += 1
plt.figure(figsize = (11.69*2,8.27*2))
plt.axis('off')
plt.imshow(cv2.cvtColor(working_image, cv2.COLOR_BGR2RGB));
</code></pre>
<p>The result of the code above is the image below. Any rectangle without a number on its top left corner and a green boundary was not recognised by the code above and has been marked by a red star. I tried varying opencv2 adaptive thresholds' type, block size and constant in the code snippet above, but these red-starred rectangles keep getting ommited from the output results.</p>
<p><a href="https://i.sstatic.net/Tn30X.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Tn30X.jpg" alt="Detection result" /></a></p>
<p>What I'm I missing? What could I consider to make sure these boxes/regions are not omitted in the results? Any help in optimising adaptive thresholds to make sure all the red-starred rectangle sections are included in the output results would be greatly appreciated.</p>
|
<python><opencv><image-processing><computer-vision><ocr>
|
2023-04-06 06:57:45
| 2
| 1,033
|
Timothy Tuti
|
75,946,563
| 10,299,633
|
not able to show both insample and out-of-sample plots for pycaret time series in streamlit columns
|
<p>I am making a Streamlit application to do experimentation on data using pycaret time series. I created a function to return the experiment and return the information I need, but for some reason I am getting only one of the 2 plots I am returning (out-of-sample). <strong>The <code>insample</code> doesn't show!</strong></p>
<p>Here is my code:</p>
<pre><code>from pycaret.time_series import TSForecastingExperiment
import streamlit as st
exp_auto = TSForecastingExperiment()
def run_pycaret(df, target='qty', horizon=12):
exp_auto.setup(
data=df, target=target, fh=horizon, enforce_exogenous=False,
numeric_imputation_target="ffill", numeric_imputation_exogenous="ffill",
scale_target="minmax",
scale_exogenous="minmax",
fold_strategy="expanding",
session_id=42, verbose=False)
best = exp_auto.compare_models(sort="mape", turbo=False, verbose=False)
metrics = exp_auto.pull()
insample = exp_auto.plot_model(best, plot='insample',display_format='streamlit')
outsample = exp_auto.plot_model(best, plot='forecast', display_format='streamlit')
return best, metrics, insample, outsample
if st.button("Run Time series models:"):
best, metrics, insample, outsample = run_pycaret(df_exog, horizon=steps)
st.write(metrics)
# Plot graph
col1_ts_exp, col2_ts_exp = st.columns(2)
with col1_ts_exp:
insample
with col2_ts_exp:
outsample
</code></pre>
<p>The results:
<a href="https://i.sstatic.net/ZG6t7.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ZG6t7.png" alt="enter image description here" /></a></p>
|
<python><streamlit><pycaret>
|
2023-04-06 06:40:38
| 1
| 327
|
Sam.H
|
75,946,355
| 10,829,044
|
Pandas create a new column based on exact match of text values
|
<p>I have two dataframes that look like below</p>
<pre><code>proj_df = pd.DataFrame({'reg_id':[1,2,3,4],
'part_no':['P1','P2','P3','P4'],
'partner':['A','B','C','D'],
'cust_name_1': ['ABC PVT LTD','Tesla','Apple','Google'],
'cust_name_2':['ABC','Tesla Ltd','Apple Inc','Google Enterprises'],
'cust_name_3':['ABC','Tesla America','Apple America','Google Ent Pvt ltd']})
data_df = pd.DataFrame({'cust_name': ['ABC','Tesla America','Apple Inc','Google','Google','ABC'],
'partner':['A','B','C','D','E','A'],
'part_no':['P1','P2','P3','P4','P5','P6'],
'qty':[100,100,600,150,320,410]})
</code></pre>
<p>I would like to do the below</p>
<p>a) Identify the exactly matching customer name column from <code>proj_df</code> by comparing it with <code>data_df</code>.</p>
<p>b) Ex: select one exactly matching column from <code>cust_name_1</code>, <code>cust_name_2</code>, <code>cust_name_3</code> by comparing it with <code>cust_name</code> column from data_df. If two or more columns has 100% match, then choose any one of the columns.</p>
<p>b) Compare/merge both dataframes based on matching <code>part_no</code>, <code>partner</code> columns.</p>
<p>I tried the below but it is going nowhere</p>
<pre><code>unique_names = data_df['cust_name'].tolist()
for name in unique_names:
proj_df['similarity_ratio'] = proj_df.apply(lambda x: difflib.SequenceMatcher(None, name, x.name_1).ratio(), axis=1)
</code></pre>
<p>I expect my output to be like as below</p>
<p><a href="https://i.sstatic.net/a7N9x.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/a7N9x.png" alt="enter image description here" /></a></p>
|
<python><pandas><dataframe><group-by><merge>
|
2023-04-06 06:07:23
| 1
| 7,793
|
The Great
|
75,946,272
| 5,380,901
|
struct.pack gives different results when calling it again after reassigning one of its inputs
|
<p>I am writing a Python script to send ICMP packets by following an example from a <a href="https://euniclus.com/article/python-route-scan/" rel="nofollow noreferrer">Japanese website</a>.
There is part of the code where <code>struct.pack</code> is used to pack series of variables into a bytes array.
It looks somehow like the following:</p>
<pre class="lang-py prettyprint-override"><code>import struct
def make_icmp_echo_request():
_type = 8
code = 0
check = 0
_id = 1
seq = 1
packed = struct.pack("!BBHHH", _type, code, check, _id, seq)
return packed
make_icmp_echo_request()
</code></pre>
<p>No matter how much you call <code>make_icmp_echo_request</code>, the output will be the same.
However, the website also implements a <code>checksum</code> function which will be used after the ICMP packet is packed.
The weird thing is that the implementation from the website will call <code>struct.pack</code> one more time after the call to <code>checksum</code>.
Something like below:</p>
<pre class="lang-py prettyprint-override"><code>import struct
def checksum(data):
data_len = len(data) // 2 * 2
csum = 0
for i in range(0, data_len, 2):
csum += (data[i + 1] << 8) + data[i]
if len(data) % 2 != 0:
csum += data[-1]
while csum >> 16:
csum = (csum >> 16) + (csum & 0xffff)
csum = csum >> 8 | (csum << 8 & 0xff00)
return ~csum&0xffff
def make_icmp_echo_request():
_type = 8
code = 0
check = 0
_id = 1
seq = 1
packed = struct.pack("!BBHHH", _type, code, check, _id, seq)
check = checksum(packed)
return struct.pack("!BBHHH", _type, code, check, _id, seq)
make_icmp_echo_request()
</code></pre>
<p>I found out that the output of the first call to <code>struct.pack</code> is different from the second one.
And this only happens if <code>checksum</code> is being called after the first call.</p>
<p>I confirmed this with below code (I also unpacked back the packed byte array to make things clearer).</p>
<pre class="lang-py prettyprint-override"><code>import struct
def checksum(data):
data_len = len(data) // 2 * 2
csum = 0
for i in range(0, data_len, 2):
csum += (data[i + 1] << 8) + data[i]
if len(data) % 2 != 0:
csum += data[-1]
while csum >> 16:
csum = (csum >> 16) + (csum & 0xffff)
csum = csum >> 8 | (csum << 8 & 0xff00)
return ~csum&0xffff
def make_icmp_echo_request():
_type = 8
code = 0
check = 0
_id = 1
seq = 1
for i in range(10):
print(f"[{i}]")
packed = struct.pack("!BBHHH", _type, code, check, _id, seq)
check = checksum(packed)
print(packed, check)
unpacked = struct.unpack("!BBHHH", packed)
print(unpacked)
return packed
make_icmp_echo_request()
</code></pre>
<pre class="lang-none prettyprint-override"><code>*** Loop: 0 ***
b'\x08\x00\x00\x00\x00\x01\x00\x01' 63485
(8, 0, 0, 1, 1)
*** Loop: 1 ***
b'\x08\x00\xf7\xfd\x00\x01\x00\x01' 0
(8, 0, 63485, 1, 1)
*** Loop: 2 ***
b'\x08\x00\x00\x00\x00\x01\x00\x01' 63485
(8, 0, 0, 1, 1)
*** Loop: 3 ***
b'\x08\x00\xf7\xfd\x00\x01\x00\x01' 0
(8, 0, 63485, 1, 1)
*** Loop: 4 ***
b'\x08\x00\x00\x00\x00\x01\x00\x01' 63485
(8, 0, 0, 1, 1)
*** Loop: 5 ***
b'\x08\x00\xf7\xfd\x00\x01\x00\x01' 0
(8, 0, 63485, 1, 1)
*** Loop: 6 ***
b'\x08\x00\x00\x00\x00\x01\x00\x01' 63485
(8, 0, 0, 1, 1)
*** Loop: 7 ***
b'\x08\x00\xf7\xfd\x00\x01\x00\x01' 0
(8, 0, 63485, 1, 1)
*** Loop: 8 ***
b'\x08\x00\x00\x00\x00\x01\x00\x01' 63485
(8, 0, 0, 1, 1)
*** Loop: 9 ***
b'\x08\x00\xf7\xfd\x00\x01\x00\x01' 0
(8, 0, 63485, 1, 1)
</code></pre>
<p>Can anyone explain this?
It is also weird that the ICMP request will fail if I use the result of the first call to <code>struct.pack</code>.</p>
|
<python><struct><bytebuffer><icmp>
|
2023-04-06 05:52:19
| 1
| 1,583
|
Hafiz Hilman Mohammad Sofian
|
75,946,267
| 18,157,326
|
does PyCharm read the zsh environment by default
|
<p>Today when I start the python project in PyCharm, I found the environment fetched failed:</p>
<pre><code>db_conn = os.environ.get('CLUSTER_POSTGRESQL_CONN')
</code></pre>
<p>this statement get None from environment. Yesterday it works fine, I check the environment in terminal:</p>
<pre><code>β ai-web git:(main) β env|grep "POST"
CLUSTER_POSTGRESQL_CONN=postgresql://postgres:123456@reddwarf-postgresql.reddwarf-storage.svc.cluster.local:5432/dolphin
</code></pre>
<p>and I already add the environment variable into <code>.zshrc</code>. why the PyCharm code could not get the environment? what should I do to fix it? does PyCharm read zsh environment by default? This is the system debug configuration:</p>
<p><a href="https://i.sstatic.net/bqQ8F.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/bqQ8F.png" alt="enter image description here" /></a></p>
<p>Now I found the PyCharm only read part of the system environment and I tried to restart the PyCharm, the environment still difference with the value I saw in terminal.</p>
|
<python><postgresql><pycharm><zsh>
|
2023-04-06 05:51:31
| 1
| 1,173
|
spark
|
75,946,255
| 19,079,397
|
How to write geopandas data into osm.pbf file using python?
|
<p>I have sample nodes, edges data like below. I am using <code>ElementTree</code> to write the data into <code>.osm</code> file and then trying to convert into <code>.osm.pbf</code> using osmosis but when trying to convert from <code>.osm</code> to <code>.osm.pbf</code> osmosis throws error saying <code>"osm format is not not supported"</code> .Is my output format worng? Also this process is very slow,time consuming and not cost effiecnt. Is there any library that converts geopandas node,edges data into <code>.osm.pbf</code>? What is the best way to convert geopandas(nodes,edges) data into <code>.osm.pbf</code> file?</p>
<p>nodes data:-
<a href="https://easyupload.io/4vib5o" rel="nofollow noreferrer">https://easyupload.io/4vib5o</a>
edges:-
<a href="https://easyupload.io/4k9du7" rel="nofollow noreferrer">https://easyupload.io/4k9du7</a></p>
<p>code:-</p>
<pre><code>import xml.etree.ElementTree as ET
import geopandas as gpd
import pandas as pd
def gpd_to_osm(n_gdf,e_gdf):
root = ET.Element("osm")
root.set("version", "0.6")
root.set("generator", "MyNetworkGenerator")
for i,row in n_gdf.iterrows():
current_node = ET.SubElement(root, 'node', attrib={
'id': str(n_gdf.loc[i,'id']),
'lat': str(n_gdf.loc[i,'lat']),
'lon': str(n_gdf.loc[i,'lon']),
'changeset': 'false'})
root.append(current_node)
for i,row in e_gdf.iterrows():
print(e_gdf.loc[i,'u'])
current_ways = ET.SubElement(root, 'ways', attrib={'u':str(e_gdf.loc[i,'u']),
'v':str(e_gdf.loc[i,'v']),
'key':str(e_gdf.loc[i,'key']),
'access':str(e_gdf.loc[i,'access']),
'area':str(e_gdf.loc[i,'area']),
'bicycle':str(e_gdf.loc[i,'bicycle']),
'bridge':str(e_gdf.loc[i,'bridge']),
'busway':str(e_gdf.loc[i,'busway']),
'cycleway':str(e_gdf.loc[i,'cycleway']),
'est_width':str(e_gdf.loc[i,'est_width']),
'foot':str(e_gdf.loc[i,'foot']),
'footway':str(e_gdf.loc[i,'footway']),
'highway':str(e_gdf.loc[i,'highway']),
'int_ref':str(e_gdf.loc[i,'int_ref']),
'junction':str(e_gdf.loc[i,'junction']),
'lanes':str(e_gdf.loc[i,'lanes']),
'lit':str(e_gdf.loc[i,'lit']),
'maxspeed':str(e_gdf.loc[i,'maxspeed']),
'motorcar':str(e_gdf.loc[i,'motorcar']),
'motorroad':str(e_gdf.loc[i,'motorroad']),
'motor_vehicle':str(e_gdf.loc[i,'motor_vehicle']),
'name':str(e_gdf.loc[i,'name']),
'oneway':str(e_gdf.loc[i,'oneway']),
'overtaking':str(e_gdf.loc[i,'overtaking']),
'path':str(e_gdf.loc[i,'path']),
'passing_places':str(e_gdf.loc[i,'passing_places']),
'psv':str(e_gdf.loc[i,'psv']),
'ref':str(e_gdf.loc[i,'ref']),
'service':str(e_gdf.loc[i,'service']),
'segregated':str(e_gdf.loc[i,'segregated']),
'sidewalk':str(e_gdf.loc[i,'sidewalk']),
'smoothness':str(e_gdf.loc[i,'smoothness']),
'surface':str(e_gdf.loc[i,'surface']),
'tracktype':str(e_gdf.loc[i,'tracktype']),
'tunnel':str(e_gdf.loc[i,'tunnel']),
'width':str(e_gdf.loc[i,'width']),
'timestamp':str(e_gdf.loc[i,'timestamp']),
'version':str(e_gdf.loc[i,'version']),
'tags':str(e_gdf.loc[i,'tags']),
'osm_type':str(e_gdf.loc[i,'osm_type']),
'geometry':str(e_gdf.loc[i,'geometry']),
'length':str(e_gdf.loc[i,'length'])})
root.append(current_ways)
tree = ET.ElementTree(root)
tree.write("mynetwork.osm")
</code></pre>
<p>Ouput file:-
<a href="https://easyupload.io/1z6u3e" rel="nofollow noreferrer">https://easyupload.io/1z6u3e</a></p>
<p>Osmosis command and error:-</p>
<pre><code>osmosis --read-xml file="mynetwork.osm" --write-pbf file="output.osm.pbf"
</code></pre>
<p>error:-</p>
<pre><code>osm format is not not supported
</code></pre>
|
<python><openstreetmap><elementtree><osmosis><osm.pbf>
|
2023-04-06 05:50:00
| 1
| 615
|
data en
|
75,946,162
| 7,838,040
|
How to convert a 2d-numpy array to diagonal matrix with padded 0?
|
<p>I'm not sure how to go about this,
example:</p>
<pre><code>array([[1, 1],
[2, 2],
[3, 3]])
</code></pre>
<p>convert it to this:</p>
<pre><code>array([[1, 1, 0, 0],
[0, 2, 2, 0],
[0, 0, 3, 3]])
</code></pre>
<p><code>np.diag</code> only works on 1d array to diagonal matrix.
I can get it with iterative approach with for loop and slices, but I feel there might be a better approach.</p>
|
<python><numpy>
|
2023-04-06 05:34:55
| 2
| 408
|
Chandan Gm
|
75,946,196
| 1,581,090
|
How to receive multicast UDP data on windows using python?
|
<p>I have a device connected to a windows 10 machine and this device is sending out various multicast UDP packages. I can see them on the windows machine using <code>wireshark</code>:</p>
<p><a href="https://i.sstatic.net/52qMK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/52qMK.png" alt="enter image description here" /></a></p>
<p>Now to get them in python (3.10.10) I am using the following script:</p>
<pre><code>import struct
import socket
import select
HOST = "192.168.200.5"
MCAST_GRP = "239.0.0.12"
PORT = 45013
def initSocket(group, port, host):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("0.0.0.0", port))
# struct.pack converts non-bytes values to bytes. To be used as the last parameter of
# setsockopt which needs to be a bytes-like object representing a buffer.
# "4sl" is a format specifier for a 4-bytes string and a long int.
mreq = struct.pack("4sl", socket.inet_aton(group), socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
return sock
sock = initSocket(MCAST_GRP, PORT, HOST)
while True:
ready = select.select([sock], [], [], 1)
if ready[0]:
data = sock.recv(4096)
print(f"received message: {data}")
else:
print("No data received")
</code></pre>
<p>But no message seems to be received! I only get <code>No data received</code>.</p>
<p>I am running this script as admin, and no other process seems to be using port 45013 (according to <code>netstat -ano -p udp</code>). I also allowed the "python" app through the firewall.</p>
<p>The device itself is connected to an ethernet adaptor (with IP address <code>192.168.200.5</code>) to the computer via USB. And the computer DOES receive the UDP messages (see wireshark).</p>
<p><code>netsh int ip show join</code> shows</p>
<pre><code>Interface 25: Ethernet
Scope References Last Address
---------- ---------- ---- ---------------------------------
0 0 Yes 224.0.0.1
0 4 Yes 224.0.0.251
0 1 Yes 224.0.0.252
0 3 Yes 239.255.255.250
</code></pre>
<p>So what else can I try? How to make it work? What is the problem?</p>
<p>Maybe there is a workaround to use wireshark inside python to receive the UDP data?</p>
<p>I have been using a C code to receive the UDP data on a Linux VM running on windows, and after some configuring and re-configuring settings and IP addresses the C code is able to receive the data. But not the python code. The python code now chooses to create a new error (on Linux VM only):</p>
<pre><code>Traceback (most recent call last):
File "udp_receiver.py", line 54, in <module>
sock = initSocket(MCAST_GRP, PORT, HOST)
File "udp_receiver.py", line 32, in initSocket
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
OSError: [Errno 19] No such device
</code></pre>
|
<python><sockets><network-programming><wireshark>
|
2023-04-06 05:29:50
| 1
| 45,023
|
Alex
|
75,946,126
| 2,791,346
|
Count consecutive boolean values in Python/pandas array for whole subset
|
<p>I am looking for a way to aggregate pandas data frame by consecutive same values and perform actions like count or max on this aggregation.</p>
<p>for example, if I would have one column in df:</p>
<pre><code> my_column
0 0
1 0
2 1
3 1
4 1
5 0
6 0
7 0
8 0
9 1
10 1
11 0
</code></pre>
<p>the result needs to be:</p>
<pre><code> result
0 2
1 2
2 3
3 3
4 3
5 4
6 4
7 4
8 4
9 2
10 2
11 1
</code></pre>
<p>Why: We have two 0 at the beginning, and three 1 next,...</p>
<p>What I need, is similar that this <a href="https://stackoverflow.com/questions/27626542/counting-consecutive-positive-values-in-python-pandas-array">answer</a> but for all elements in the group I need the same value.</p>
<p>The preferred answer would be one that shows this aggregation of the consecutive same element and applies the aggregation function to it. So that I could do even max value:</p>
<pre><code> my_column other_value
0 0 7
1 0 4
2 1 1
3 1 0
4 1 5
5 0 1
6 0 1
7 0 2
8 0 8
9 1 1
10 1 0
11 0 2
</code></pre>
<p>and the result would be</p>
<pre><code> result
0 7
1 7
2 5
3 5
4 5
5 8
6 8
7 8
8 8
9 1
10 1
11 2
</code></pre>
|
<python><pandas><group-by>
|
2023-04-06 05:28:37
| 2
| 8,760
|
Marko Zadravec
|
75,946,037
| 2,789,334
|
custom errorbars for catplot with grouped bars in facets
|
<p><code>pandas 1.5.3</code> <code>seaborn 0.12.2</code></p>
<p>My code and part of the data is shown below. I am trying to plot the errorbars precomputed in the dataframe <code>(val_lo,val_hi)</code>. It seems that <code>sns.catplot</code> with <code>kind=bar</code> has support using <code>errorbar</code> as mentioned <a href="https://github.com/mwaskom/seaborn/pull/2407" rel="nofollow noreferrer">here</a> - how do I get that to work? Or any guidance into how to use matplotlib errorbar?</p>
<pre><code>import pandas as pd
import re
import seaborn as sns
from matplotlib.ticker import PercentFormatter
df = pd.DataFrame([
['C', 'G1', 'gbt', 'auc', 0.7999, 0.7944, 0.8032],
['C', 'G1', 'gbtv2', 'auc', 0.8199, 0.8144, 0.8232],
['C', 'G1', 'gbt', 'pr@2%', 0.0883, 0.0841, 0.0909],
['C', 'G1', 'gbt', 'pr@10%', 0.0430, 0.0416, 0.0435],
['C', 'G2', 'gbt', 'auc', 0.7554, 0.7506, 0.7573],
['C', 'G2', 'gbt', 'pr@2%', 0.0842, 0.0795, 0.0872],
['C', 'G2', 'gbt', 'pr@10%', 0.0572, 0.0556, 0.0585],
['C', 'G3', 'gbt', 'auc', 0.7442, 0.7404, 0.7460],
['C', 'G3', 'gbt', 'pr@2%', 0.0894, 0.0836, 0.0913],
['C', 'G3', 'gbt', 'pr@10%', 0.0736, 0.0714, 0.0742],
['E', 'G1', 'gbt', 'auc', 0.7988, 0.7939, 0.8017],
['E', 'G1', 'gbt', 'pr@2%', 0.0810, 0.0770, 0.0832],
['E', 'G1', 'gbt', 'pr@10%', 0.0354, 0.0342, 0.0361],
['E', 'G1', 'gbtv3','pr@10%',0.0454, 0.0442, 0.0461],
['E', 'G2', 'gbt', 'auc', 0.7296, 0.7253, 0.7311],
['E', 'G2', 'gbt', 'pr@2%', 0.1071, 0.1034, 0.1083],
['E', 'G2', 'gbt', 'pr@10%', 0.0528, 0.0508, 0.0532],
['E', 'G3', 'gbt', 'auc', 0.6958, 0.6914, 0.6978],
['E', 'G3', 'gbt', 'pr@2%', 0.1007, 0.0961, 0.1030],
['E', 'G3', 'gbt', 'pr@10%', 0.0536, 0.0518, 0.0541],
], columns=["src","grp","model","metric","val","val_lo","val_hi"])
sns.reset_defaults()
sns.set(style="whitegrid", font_scale=1.)
g = sns.catplot(data=df, x="grp", y="val", hue="model",
col="metric", row="src", kind="bar", sharey=False)
for ax in g.axes.flat:
ax.yaxis.set_major_formatter(PercentFormatter(1))
if re.search("metric = auc",ax.get_title(),re.IGNORECASE):
_ = ax.set_ylim((.5,1.))
plt.show()
</code></pre>
|
<python><matplotlib><seaborn><errorbar><grouped-bar-chart>
|
2023-04-06 05:14:21
| 1
| 1,068
|
ironv
|
75,946,021
| 8,884,239
|
Dataframe column name with $$ failing in filter condition with parse error
|
<p>I have dataframe with column names as "lastname$$" and "firstname$$"</p>
<pre><code>+-----------+----------+----------+------------------+-----+------+
|firstname$$|middlename|lastname$$|languages |state|gender|
+-----------+----------+----------+------------------+-----+------+
|James | |Smith |[Java, Scala, C++]|OH |M |
|Anna |Rose | |[Spark, Java, C++]|NY |F |
|Julia | |Williams |[CSharp, VB] |OH |F |
|Maria |Anne |Jones |[CSharp, VB] |NY |M |
|Jen |Mary |Brown |[CSharp, VB] |NY |M |
|Mike |Mary |Williams |[Python, VB] |OH |M |
+-----------+----------+----------+------------------+-----+------+
</code></pre>
<p>I am trying to filter this dataframe for firstname$$ = "James" and getting following error.</p>
<pre><code>{
"name": "ParseException",
"message": "\nSyntax error at or near '$'(line 1, pos 9)\n\n== SQL ==\nfirstname$$ == 'James'\n---------^^^\n",
"stack": "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[1;31mParseException\u001b[0m Traceback (most recent call last)\n\u001b[1;32md:\\Users\\sample.ipynb Cell 3\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> <a href='vscode-notebook-cell:/d%3A/Users/sample.ipynb#X20sZmlsZQ%3D%3D?line=0'>1</a>\u001b[0m df_sam1 \u001b[39m=\u001b[39m df_sam\u001b[39m.\u001b[39;49mwhere(\u001b[39m\"\u001b[39;49m\u001b[39mfirstname$$ == \u001b[39;49m\u001b[39m'\u001b[39;49m\u001b[39mJames\u001b[39;49m\u001b[39m'\u001b[39;49m\u001b[39m\"\u001b[39;49m)\n\u001b[0;32m <a href='vscode-notebook-cell:/d%3A/Users/sample.ipynb#X20sZmlsZQ%3D%3D?line=1'>2</a>\u001b[0m df_sam1\u001b[39m.\u001b[39mshow()\n\nFile \u001b[1;32mD:\\SparkApp\\spark-3.3.1-bin-hadoop3\\python\\pyspark\\sql\\dataframe.py:2077\u001b[0m, in \u001b[0;36mDataFrame.filter\u001b[1;34m(self, condition)\u001b[0m\n\u001b[0;32m 2052\u001b[0m \u001b[39m\"\"\"Filters rows using the given condition.\u001b[39;00m\n\u001b[0;32m 2053\u001b[0m \n\u001b[0;32m 2054\u001b[0m \u001b[39m:func:`where` is an alias for :func:`filter`.\u001b[39;00m\n\u001b[1;32m (...)\u001b[0m\n\u001b[0;32m 2074\u001b[0m \u001b[39m[Row(age=2, name='Alice')]\u001b[39;00m\n\u001b[0;32m 2075\u001b[0m \u001b[39m\"\"\"\u001b[39;00m\n\u001b[0;32m 2076\u001b[0m \u001b[39mif\u001b[39;00m \u001b[39misinstance\u001b[39m(condition, \u001b[39mstr\u001b[39m):\n\u001b[1;32m-> 2077\u001b[0m jdf \u001b[39m=\u001b[39m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49m_jdf\u001b[39m.\u001b[39;49mfilter(condition)\n\u001b[0;32m 2078\u001b[0m \u001b[39melif\u001b[39;00m \u001b[39misinstance\u001b[39m(condition, Column):\n\u001b[0;32m 2079\u001b[0m jdf \u001b[39m=\u001b[39m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39m_jdf\u001b[39m.\u001b[39mfilter(condition\u001b[39m.\u001b[39m_jc)\n\nFile \u001b[1;32mD:\\SparkApp\\spark-3.3.1-bin-hadoop3\\python\\lib\\py4j-0.10.9.5-src.zip\\py4j\\java_gateway.py:1321\u001b[0m, in \u001b[0;36mJavaMember.__call__\u001b[1;34m(self, *args)\u001b[0m\n\u001b[0;32m 1315\u001b[0m command \u001b[39m=\u001b[39m proto\u001b[39m.\u001b[39mCALL_COMMAND_NAME \u001b[39m+\u001b[39m\\\n\u001b[0;32m 1316\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mcommand_header \u001b[39m+\u001b[39m\\\n\u001b[0;32m 1317\u001b[0m args_command \u001b[39m+\u001b[39m\\\n\u001b[0;32m 1318\u001b[0m proto\u001b[39m.\u001b[39mEND_COMMAND_PART\n\u001b[0;32m 1320\u001b[0m answer \u001b[39m=\u001b[39m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mgateway_client\u001b[39m.\u001b[39msend_command(command)\n\u001b[1;32m-> 1321\u001b[0m return_value \u001b[39m=\u001b[39m get_return_value(\n\u001b[0;32m 1322\u001b[0m answer, \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mgateway_client, \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mtarget_id, \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mname)\n\u001b[0;32m 1324\u001b[0m \u001b[39mfor\u001b[39;00m temp_arg \u001b[39min\u001b[39;00m temp_args:\n\u001b[0;32m 1325\u001b[0m temp_arg\u001b[39m.\u001b[39m_detach()\n\nFile \u001b[1;32mD:\\SparkApp\\spark-3.3.1-bin-hadoop3\\python\\pyspark\\sql\\utils.py:196\u001b[0m, in \u001b[0;36mcapture_sql_exception.<locals>.deco\u001b[1;34m(*a, **kw)\u001b[0m\n\u001b[0;32m 192\u001b[0m converted \u001b[39m=\u001b[39m convert_exception(e\u001b[39m.\u001b[39mjava_exception)\n\u001b[0;32m 193\u001b[0m \u001b[39mif\u001b[39;00m \u001b[39mnot\u001b[39;00m \u001b[39misinstance\u001b[39m(converted, UnknownException):\n\u001b[0;32m 194\u001b[0m \u001b[39m# Hide where the exception came from that shows a non-Pythonic\u001b[39;00m\n\u001b[0;32m 195\u001b[0m \u001b[39m# JVM exception message.\u001b[39;00m\n\u001b[1;32m--> 196\u001b[0m \u001b[39mraise\u001b[39;00m converted \u001b[39mfrom\u001b[39;00m \u001b[39mNone\u001b[39m\n\u001b[0;32m 197\u001b[0m \u001b[39melse\u001b[39;00m:\n\u001b[0;32m 198\u001b[0m \u001b[39mraise\u001b[39;00m\n\n\u001b[1;31mParseException\u001b[0m: \nSyntax error at or near '$'(line 1, pos 9)\n\n== SQL ==\nfirstname$$ == 'James'\n---------^^^\n"
}
</code></pre>
<p>Here is the code I am trying.</p>
<pre><code>df_sam1 = df_sam.where("firstname$$ == 'James'")
df_sam1.show()
</code></pre>
<p>I tried to rename the column to fitstname and still getting the same error.</p>
<p>Can anyone look at it and help me to resolve this issue.</p>
<p>Thanks,
Bab</p>
|
<python><apache-spark><pyspark><apache-spark-sql>
|
2023-04-06 05:11:42
| 2
| 301
|
Bab
|
75,945,928
| 4,420,797
|
Pytorch: RuntimeError: CUDA error: device-side assert triggered on CUDA 11.7
|
<p>I am training two models in the same environment and one of them works fine with the same configuration but another one is giving errors without any further reason. I have also added <code>CUDA_LAUNCH_BLOCKING=1</code> but still, the problem remains the same.</p>
<p><strong>Script Command</strong></p>
<pre><code>CUDA_LAUNCH_BLOCKING=1 python3 train_pytorch.py sar_resnet31 --train_path /media/cvpr/CM_24/KR_2M/train --val_path /media/cvpr/CM_24/KR_2M/val --font "ko/NanumBarunGothicBold.ttf" --batch_size 56 --epochs 10
</code></pre>
<p><strong>Traceback</strong></p>
<pre><code>Validation set loaded in 0.0005977s (81 samples in 2 batches)
Train set loaded in 7.846s (3000000 samples in 53571 batches)
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [32,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [33,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [34,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [35,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [36,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [37,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [38,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [39,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [40,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [41,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [42,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [43,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [44,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [45,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [46,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [47,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [48,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [49,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [50,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [51,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [52,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [53,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [54,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [55,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [56,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [57,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [58,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [59,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [60,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [61,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [62,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [63,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [0,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [1,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [2,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [3,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [4,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [5,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [6,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [7,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [8,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [9,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [10,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [11,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [12,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [13,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [14,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [15,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [16,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [17,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [18,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [19,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [20,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [21,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [22,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [23,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [24,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [25,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [26,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [27,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [28,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [29,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [30,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
/opt/conda/conda-bld/pytorch_1639180487213/work/aten/src/ATen/native/cuda/Indexing.cu:699: indexSelectLargeIndex: block: [88,0,0], thread: [31,0,0] Assertion `srcIndex < srcSelectDimSize` failed.
Traceback (most recent call last):
File "/media/cvpr/CM_1/doctr-main/references/recognition/train_pytorch.py", line 470, in <module>
main(args)
File "/media/cvpr/CM_1/doctr-main/references/recognition/train_pytorch.py", line 381, in main
fit_one_epoch(model, train_loader, batch_transforms, optimizer, scheduler, mb, amp=args.amp)
File "/media/cvpr/CM_1/doctr-main/references/recognition/train_pytorch.py", line 121, in fit_one_epoch
train_loss = model(images, targets)["loss"]
File "/home/cvpr/anaconda3/envs/pytesseract/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1102, in _call_impl
return forward_call(*input, **kwargs)
File "/media/cvpr/CM_1/doctr-main/doctr/models/recognition/sar/pytorch.py", line 242, in forward
decoded_features = self.decoder(features, encoded, gt=None if target is None else gt)
File "/home/cvpr/anaconda3/envs/pytesseract/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1102, in _call_impl
return forward_call(*input, **kwargs)
File "/media/cvpr/CM_1/doctr-main/doctr/models/recognition/sar/pytorch.py", line 119, in forward
gt_embedding = self.embed_tgt(gt)
File "/home/cvpr/anaconda3/envs/pytesseract/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1102, in _call_impl
return forward_call(*input, **kwargs)
File "/home/cvpr/anaconda3/envs/pytesseract/lib/python3.9/site-packages/torch/nn/modules/sparse.py", line 158, in forward
return F.embedding(
File "/home/cvpr/anaconda3/envs/pytesseract/lib/python3.9/site-packages/torch/nn/functional.py", line 2044, in embedding
return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse)
RuntimeError: CUDA error: device-side assert triggered
</code></pre>
|
<python><pytorch><ocr><tesseract><doctr>
|
2023-04-06 04:52:08
| 1
| 2,984
|
Khawar Islam
|
75,945,914
| 13,512,544
|
Python saying that module doesn't exist
|
<p>This question has been asked a lot of times and I can't find an issue that's similar to mine. I was trying to import <code>consolemenu</code> which has a member called <code>SelectionMenu</code>. But when I try to use it</p>
<pre class="lang-py prettyprint-override"><code>selected_integer = consolemenu.SelectionMenu.get_selection(option_manager.get_all_keysets())
</code></pre>
<p>I get an error saying</p>
<pre><code>Traceback (most recent call last):
File "---\main.py", line 56, in <module>
main()
File "---\main.py", line 11, in main
selected_integer = consolemenu.SelectionMenu.get_selection(option_manager.get_all_keysets())
^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'consolemenu' has no attribute 'SelectionMenu'
</code></pre>
<p>But even intellisense knows it's there! I tried it on another computer and it worked just fine. The python version I'm using is python 3.11.3 and pip 23.0.1.</p>
|
<python><pip>
|
2023-04-06 04:50:03
| 2
| 466
|
Pro Poop
|
75,945,832
| 9,042,093
|
What is the output type of Subprocess.communicate?
|
<p>I was going through official documentation of <a href="https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate" rel="noreferrer">Popen.communicate()</a>.</p>
<pre><code>p = subprocess.Popen('echo hello',stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,universal_newlines=True)
r,e = p.communicate()
</code></pre>
<p>I want to know at which case it will return string output and which case it will return in bytes.(with example would be great)</p>
<p>In the above case <code>r</code> type is string.</p>
<pre><code>Popen.communicate(input=None, timeout=None)
Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate and set the returncode attribute. The optional input argument should be data to be sent to the child process, or None, if no data should be sent to the child. If streams were opened in text mode, input must be a string. Otherwise, it must be bytes.
communicate() returns a tuple (stdout_data, stderr_data). The data will be strings if streams were opened in text mode; otherwise, bytes.
</code></pre>
|
<python><subprocess><popen>
|
2023-04-06 04:32:03
| 2
| 349
|
bad_coder9042093
|
75,945,804
| 5,942,100
|
Tricky Long Pivot by Reverse Aggregation transformation (Pandas)
|
<p>I have a dataset where I would like to de aggregate the values into their own unique rows as well as perform a pivot, grouping by category.</p>
<p><strong>Data</strong> updated</p>
<pre><code>Period Date Area BB stat AA stat CC stat DD stat BB test AA test CC test DD test BB re AA re CC re BB test2 AA test2 CC test2 DD test2
8/1/2016 9/1/2016 NY 5 5 5 1 1 1 0 0 0 0 0 0 0
9/1/2016 10/1/2016 NY 6 6 6 4 4 4 0 0 0 0 0 0 0
8/1/2016 9/1/2016 CA 2 2 2 4 4 4 0 0 0 0 0 0 0
9/1/2016 10/1/2016 CA 1 1 1 -2 -2 -2 0 0 0 0 0 0 0
</code></pre>
<p><strong>Desired</strong></p>
<pre><code>Period Date Area stat test type re test2
8/1/2016 9/1/2016 NY 5 1 BB 0 0
9/1/2016 10/1/2016 NY 6 4 BB 0 0
8/1/2016 9/1/2016 NY 5 1 AA 0 0
9/1/2016 10/1/2016 NY 6 4 AA 0 0
8/1/2016 9/1/2016 NY 5 1 CC 0 0
9/1/2016 10/1/2016 NY 6 4 CC 0 0
8/1/2016 9/1/2016 NY 0 0 DD 0 0
9/1/2016 10/1/2016 NY 0 0 DD 0 0
8/1/2016 9/1/2016 CA 2 4 BB 0 0
9/1/2016 10/1/2016 CA 1 -2 BB 0 0
8/1/2016 9/1/2016 CA 2 4 AA 0 0
9/1/2016 10/1/2016 CA 1 -2 AA 0 0
8/1/2016 9/1/2016 CA 2 4 CC 0 0
9/1/2016 10/1/2016 CA 1 -2 CC 0 0
8/1/2016 9/1/2016 CA 0 0 DD 0 0
9/1/2016 10/1/2016 CA 0 0 DD 0 0
</code></pre>
<p><strong>Doing</strong></p>
<pre><code>value_vars = ["BB stat", "AA stat", "CC stat", "DD stat", "BB test",
"AA test", "CC test", "DD test", "BB re", "AA re", "CC re"]
df = df.melt(id_vars=["Period", "Date", "Area"], value_vars=value_vars)
temp_df = df.variable.str.split("_", 1, expand=True)
df["type"] = temp_df[0]
df["name"] = temp_df[1]
df = df.drop(columns=["variable"])
first_half = df.iloc[:len(df)//2]
second_half = df.iloc[len(df)//2:]
df = pd.merge(first_half, second_half, on=["Period", "Date", "Area", "type"], suffixes=("_1", "_2"))
df.rename(columns = {'value_3':'stat''value_2':'test', 'value_1':'re'}, inplace = True)
df.drop(columns=["name_1", "name_2"], inplace=True)
df = df[[ "Period", "Date", "Area", "stat", "test", "type", "re" ]]
df.sort_values(["Area", "type"], ascending=False, inplace=True)
df.to_markdown()
</code></pre>
<p>The following code fails to capture all the output columns. Any suggestion is appreciated.</p>
|
<python><pandas><numpy>
|
2023-04-06 04:24:01
| 4
| 4,428
|
Lynn
|
75,945,735
| 188,331
|
XLNet or BERT Chinese for HuggingFace AutoModelForSeq2SeqLM Training
|
<p>I want to use the pre-trained XLNet (<code>xlnet-base-cased</code>, which the model type is <em>Text Generation</em>) or BERT Chinese (<code>bert-base-chinese</code>, which the model type is <em>Fill Mask</em>) for Sequence to Sequence Language Model (<code>Seq2SeqLM</code>) training.</p>
<p>I can use <code>facebook/bart-large</code> (which the model type is <em>Feature Extraction</em>) for constructing the <code>Seq2SeqLM</code>, but not the 2 pretrained models mentioned above. Here is my code below:</p>
<p><strong>Load Dataset</strong></p>
<pre><code>from datasets import load_dataset
yuezh = load_dataset("my-custom-dataset")
</code></pre>
<p><strong>Sample data from the dataset</strong> <code>my-custom-dataset</code></p>
<pre><code>{"translation": {"yue": "εη", "zh": "εη"}}
{"translation": {"yue": "ει ", "zh": "ιε§ηζε"}}
</code></pre>
<p><strong>Create Test Split</strong></p>
<pre><code>yuezh = yuezh["train"].train_test_split(test_size=0.2)
print(yuezh)
</code></pre>
<p>Output:</p>
<pre><code>DatasetDict({
train: Dataset({
features: ['translation'],
num_rows: 4246
})
test: Dataset({
features: ['translation'],
num_rows: 1062
})
})
</code></pre>
<p><strong>Tokenizer</strong></p>
<pre><code>from transformers import AutoTokenizer
checkpoint = 'bert-base-chinese'
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
</code></pre>
<p><strong>Pre-process Function</strong></p>
<pre><code>def preprocess_function(examples):
inputs = [prefix + example[source_lang] for example in examples["translation"]]
targets = [example[target_lang] for example in examples["translation"]]
model_inputs = tokenizer(inputs, text_target=targets, max_length=128, truncation=True)
return model_inputs
</code></pre>
<p><strong>Parameters</strong></p>
<pre><code>source_lang = "yue"
target_lang = "zh"
prefix = "Translate this: "
tokenized_yuezh = yuezh.map(preprocess_function, batched=True)
tokenized_yuezh = tokenized_yuezh.remove_columns(yuezh["train"].column_names)
print(tokenized_yuezh)
</code></pre>
<p>Output:</p>
<pre><code>DatasetDict({
train: Dataset({
features: ['input_ids', 'token_type_ids', 'attention_mask', 'labels'],
num_rows: 4246
})
test: Dataset({
features: ['input_ids', 'token_type_ids', 'attention_mask', 'labels'],
num_rows: 1062
})
})
</code></pre>
<p><strong>Evaluate Performance</strong></p>
<pre><code># Use ScareBLEU to evaluate the performance
import evaluate
metric = evaluate.load("sacrebleu")
</code></pre>
<p><strong>Data Collator</strong></p>
<pre><code>from transformers import DataCollatorForSeq2Seq
data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint)
</code></pre>
<p><strong>Supporting Functions</strong></p>
<pre><code>import numpy as np
def postprocess_text(preds, labels):
preds = [pred.strip() for pred in preds]
labels = [[label.strip()] for label in labels]
return preds, labels
def compute_metrics(eval_preds):
preds, labels = eval_preds
if isinstance(preds, tuple):
preds = preds[0]
decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)
labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels)
result = metric.compute(predictions=decoded_preds, references=decoded_labels)
result = {"bleu": result["score"]}
prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in preds]
result["gen_len"] = np.mean(prediction_lens)
result = {k: round(v, 4) for k, v in result.items()}
return result
</code></pre>
<p><strong>Training</strong></p>
<pre><code>model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint)
training_args = CustomSeq2SeqTrainingArguments(
output_dir="my-output-dir",
evaluation_strategy="epoch",
learning_rate=2e-5,
per_device_train_batch_size=16,
per_device_eval_batch_size=16,
weight_decay=0.01,
save_total_limit=3,
num_train_epochs=2,
predict_with_generate=True,
remove_unused_columns=False,
fp16=True,
push_to_hub=False, # Don't push to Hub yet
)
trainer = Seq2SeqTrainer(
model=model,
args=training_args,
train_dataset=tokenized_yuezh["train"],
eval_dataset=tokenized_yuezh["test"],
tokenizer=tokenizer,
data_collator=data_collator,
compute_metrics=compute_metrics,
)
trainer.train()
</code></pre>
<p>It results in the following errors:</p>
<pre><code>ValueError: Unrecognized configuration class <class
'transformers.models.bert.configuration_bert.BertConfig'> for this kind of AutoModel:
AutoModelForSeq2SeqLM.
Model type should be one of BartConfig, BigBirdPegasusConfig, BlenderbotConfig,
BlenderbotSmallConfig, EncoderDecoderConfig, FSMTConfig, LEDConfig, LongT5Config,
M2M100Config, MarianConfig, MBartConfig, MT5Config, MvpConfig, PegasusConfig, PegasusXConfig,
PLBartConfig, ProphetNetConfig, SwitchTransformersConfig, T5Config, XLMProphetNetConfig.
</code></pre>
<p>The <code>AutoModelForSeq2SeqLM</code> does not support XLNet or BERT. What should I do to make the Sequence-to-Sequence training work?</p>
|
<python><pytorch><huggingface-transformers><huggingface>
|
2023-04-06 04:09:22
| 1
| 54,395
|
Raptor
|
75,945,695
| 14,864,907
|
How to create a class instance directly with a call to a class method?
|
<p>I'm facing a problem that I can't solve. Is it possible to make <em>pipe</em> be an instance of the class <em>MyClass</em> concerning the call to the class method <em>do_something</em>? And make <em>print(isinstance(pipe, MyClass))</em> return True. This means that on the call <em>pipe</em> goes through the class method <em>do_something</em> and then reads the constructor <code>__init__</code>.</p>
<pre class="lang-py prettyprint-override"><code>class MyClass:
def __init__(self):
self.my_attr = 42
print("Attribute initialized to", self.my_attr)
@classmethod
def do_something(cls):
print("Doing something...")
pipe = MyClass.do_something()
print(isinstance(pipe, MyClass)) # True
</code></pre>
|
<python>
|
2023-04-06 03:59:37
| 3
| 583
|
Tim
|
75,945,689
| 6,055,629
|
Python - Efficient calculation where end value of one row is the start value of another row
|
<p>I would like to make simple calculations on a rolling basis, but have heavy performance issues when I try to solve this with a nested for-loop. I need to perform this kind of operations on very large data, but have to use standard Python (incl. Pandas). The values are floats and can be negative, zero or positive.</p>
<p>I have a pd.DataFrame (df1) which contains (structured by some dimensions, lets call them key1 and key2) a start column, a end column and some operations-columns in between, which are supposed to be used to calculate the end column based on the start column.</p>
<p>Basically, the simple logic is: start + plus - minus = end, where the end value of each row is the start value of the next row.</p>
<p>This would need to be done by the two keys, i.e. for AX, AY and BX seperately.</p>
<p>df2 shows the desired result, but I don't know how to get there in an efficient way without blowing up my memory if this task is done on much larger tables.</p>
<pre><code>import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.array([["A", "X", 3,6,4,0], ["A", "X", 0,2,10,0], ["A", "X", 0,9,3,0], ["A", "Y", 8,3,1,0], ["A", "Y", 0,2,3,0], ["B", "X", 4,4,2,0], ["B", "X", 0,1,0,0]]),
columns=['key1', 'key2', 'start', 'plus', 'minus', 'end'])
>>> df1
key1 key2 start plus minus end
0 A X 3 6 4 0
1 A X 0 2 10 0
2 A X 0 9 3 0
3 A Y 8 3 1 0
4 A Y 0 2 3 0
5 B X 4 4 2 0
6 B X 0 1 0 0
df2 = pd.DataFrame(np.array([["A", "X", 3,6,4,5], ["A", "X", 5,2,10,-3], ["A", "X", -3,9,3,3], ["A", "Y", 8,3,1,10], ["A", "Y", 10,2,3,9], ["B", "X", 4,4,2,2], ["B", "X", 2,1,0,3]]),
columns=['key1', 'key2', 'start', 'plus', 'minus', 'end'])
>>> df2
key1 key2 start plus minus end
0 A X 3 6 4 5
1 A X 5 2 10 -3
2 A X -3 9 3 3
3 A Y 8 3 1 10
4 A Y 10 2 3 9
5 B X 4 4 2 2
6 B X 2 1 0 3
</code></pre>
|
<python><pandas><performance><for-loop><apply>
|
2023-04-06 03:57:22
| 4
| 648
|
constiii
|
75,945,624
| 7,700,802
|
Calculating the percentage change by year for a particular column
|
<p>Suppose I have this dataframe</p>
<pre><code>data = {'Year': ['2010', '2011', '2012'],
'Total_Population': [1000, 1200, 1600]}
df_sample = pd.DataFrame(data=data)
df_sample.head()
</code></pre>
<p>I want to calculate the percentage change in <code>Year</code> for <code>Total_Population</code>. I tried following this <a href="https://stackoverflow.com/questions/72776327/how-to-calculate-the-percentage-of-change-based-on-previous-years-where-the-firs">here</a>. Which boiled down to this code</p>
<pre><code>cols1 = ['Year', 'Total_Population']
vals = df[cols1].merge(df.assign(year=df['Year']+1), on=cols1, how='left')['values']
df['change_in_population'] = df['values'].sub(vals).div(vals).mul(100).fillna(0)
</code></pre>
<p>For the actual .csv file the size is about 215.2 MB and when I try the latter my memory blows up and I have 64 gb of RAM. Is there a better way of doing this?</p>
|
<python><pandas>
|
2023-04-06 03:41:28
| 1
| 480
|
Wolfy
|
75,945,584
| 179,234
|
How to extract Error-Code from REPORT.IPM.Note.NDR outlook object using Python
|
<p>I am trying to extract certain details from an outlook mailbox. I want to extract bounced emails and get the error code of why these emails were bounced.</p>
<p>I know with using regular expression I can extract that from the body of the message. but I am wondering if there is a MAPI ID that I can use or an existing property that can give me this error code straightaway instead of having to process the body?</p>
<p>I was able to use this to extract receivers email,</p>
<pre><code>print(message.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x0E04001E")) #receiver address
</code></pre>
<p>I got that ID from the solution in <a href="https://stackoverflow.com/questions/62284859/retrieve-email-address-from-outlooks-undeliverable-email-using-vba">this link</a> and it shows that we can use other MAPI ids to extract certain details about the email. I am wondering if there is an ID that extracts the error code from REPORT.IPM.Note.NDR same way. Seems like a logical attribute to have but somehow I cannot find it anywhere.</p>
<p>I asked GPT and it gave me this ID</p>
<p>"http://schemas.microsoft.com/mapi/proptag/0x1001F001"</p>
<p>I tried using it but I am getting this error</p>
<pre><code>com_error: (-2147352571, 'Type mismatch.', None, 1)
</code></pre>
<p>I also understand that IDs beyond certain range cannot be retrieved via the PropertyAccessor.</p>
<p>Any recommendations that is more straightforward than using a regex on the body?</p>
|
<python><outlook><win32com><office-automation><mapi>
|
2023-04-06 03:26:49
| 2
| 1,417
|
Sarah
|
75,945,523
| 18,171,350
|
ModuleNotFoundError: No module named 'PIL' Windows ERROR
|
<p>Getting the below error when I run my python code. any suggestions?</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\User\OneDrive\Desktop\crop recommend Final\app.py", line 11, in <module>
from torchvision import transforms
File "C:\Users\User\OneDrive\Desktop\crop recommend Final\venv\lib\site-packages\torchvision\__init__.py", line 6, in <module>
from torchvision import datasets, io, models, ops, transforms, utils
File "C:\Users\User\OneDrive\Desktop\crop recommend Final\venv\lib\site-packages\torchvision\datasets\__init__.py", line 1, in <module>
from ._optical_flow import FlyingChairs, FlyingThings3D, HD1K, KittiFlow, Sintel
File "C:\Users\User\OneDrive\Desktop\crop recommend Final\venv\lib\site-packages\torchvision\datasets\_optical_flow.py", line 10, in <module>
from PIL import Image
ModuleNotFoundError: No module named 'PIL'
</code></pre>
<p><a href="https://i.sstatic.net/UYQlt.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/UYQlt.png" alt="enter image description here" /></a></p>
|
<python>
|
2023-04-06 03:12:03
| 0
| 487
|
Nidew
|
75,945,484
| 2,655,102
|
Call subclass static methods from superclass in Python
|
<p>What I want:
To define some rich static methods based on simple methods in the superclass and to implement the simple methods in every subclass. The methods are all static, so I don't want to instantiate first to use them.</p>
<p>Example Code:</p>
<pre class="lang-py prettyprint-override"><code>import abc
from abc import ABC
class Direction(ABC):
@staticmethod
@abc.abstractmethod
def expr() -> str:
pass
@staticmethod
def turn() -> str:
# SUBCLASS does not exist, but that's what I want
return "turn " + SUBCLASS.expr()
class Left(Direction):
@staticmethod
def expr() -> str:
return "left"
class Right(Direction):
@staticmethod
def expr() -> str:
return "right"
if __name__ == "__main__":
print(Left.turn())
# Want "turn left"
print(Right.turn())
# Want "turn right"
</code></pre>
|
<python><python-3.x>
|
2023-04-06 03:02:34
| 1
| 2,141
|
Renkai
|
75,945,390
| 885,287
|
tqdm progress bar with estimated duration
|
<p>I want to use TQDM to show a progress bar for a process. I know roughly how long this process will take (based on an empirical model I have fit).</p>
<p>The <code>tqdm()</code> <code>length</code> parameter makes it easy to set a progress bar's length based on a known iterable size, but I can't see a way to do the same thing when you know a duration, not a size.</p>
|
<python><progress-bar><tqdm>
|
2023-04-06 02:36:17
| 1
| 6,263
|
aaronsnoswell
|
75,945,273
| 8,878,774
|
How to download all files from a link by selecting date
|
<p>I have a url as mentioned below. I want to select date field and fill in some date and then click on "select all reports" box. Then download all the files from "multiple file download"</p>
<p>url = 'https://www.nseindia.com/all-reports-derivatives#cr_deriv_equity_archives'</p>
<p>Is it possible using request or selenium is the only way. Any help?</p>
|
<python><python-3.x><selenium-webdriver><python-requests>
|
2023-04-06 02:02:08
| 1
| 329
|
Pravat
|
75,945,197
| 2,272,824
|
How best to apply successive filters to a Polars Dataframe?
|
<p>I have a Polars Dataframe with a bunch of columns (I'm working in Python)
I need to group the dataframe by three different row criteria - every row will match exactly one of the three criteria.
Minimal example data would look something like this</p>
<pre class="lang-py prettyprint-override"><code>df = pl.from_repr("""
βββββββ¬ββββββββ¬βββββββββ
β a β b β c β
β --- β --- β --- β
β i64 β i64 β i64 β
βββββββͺββββββββͺβββββββββ‘
β 1 β 0 β 0 β
β 2 β 1 β 1 β
β 3 β 0 β 1 β
βββββββ΄ββββββββ΄βββββββββ
""")
</code></pre>
<p>My goal is to identify,</p>
<ol>
<li>rows where b and c are both zero</li>
<li>rows where b and c are both non-zero</li>
<li>rows where b and c are mixed zero/non-zero</li>
</ol>
<p>In the real use case the dataframes are large - millions of rows and ~30 columns and the row queries are more complex, but satisfy the same basic row uniqueness criteria.</p>
<p>I can find the rows with b and c= 0 using</p>
<pre><code>all_zeros = df.filter(pl.all_horizontal(pl.col('b','c')==0))
</code></pre>
<p>and the the non-zero rows using</p>
<pre><code>no_zeros = df.filter(pl.all_horizontal(pl.col('b','c')!=0))
</code></pre>
<p>The third classification is whatever doesn't match these two queries.</p>
<p>What is the most efficient way of implementing these queries?</p>
<p>As written above, the second filter has to process the entire dataframe, even though the first filter has identified rows that could be omitted from the second filter? Is there some way I can uses these filters in a group_by?</p>
|
<python><python-polars>
|
2023-04-06 01:41:14
| 1
| 391
|
scotsman60
|
75,945,078
| 329,443
|
String interpolation failing inside os.system call
|
<p>Editing to skip to the answer: The problem was that the string I was interpolating had a non-ascii character in it that was invisible to the naked eye.</p>
<p>I'm trying to run this ImageMagick Command:</p>
<pre><code>convert -verbose -size 732x142 xc:transparent -fill black -stroke black -strokewidth 2 -draw "roundrectangle 0,0 732,142 18,18" "Sample Card Title.png"
</code></pre>
<p>And it runs without error if I run it directly from the command line.</p>
<p>Only I'm trying to run it inside of a Python script, with most of those values being generated by the script. And when I launch it from there, with the same values, ImageMagick errors, reporting:</p>
<pre><code>convert: non-conforming drawing primitive definition `roundrectangle' @ error/draw.c/RenderMVGContent/4506.
</code></pre>
<p>When it's run as:</p>
<pre><code> rectangle_coordinates = f"\"roundrectangle 0,0 {mm_to_px(62)},{mm_to_px(box_height)}Β {mm_to_px(1.5)},{mm_to_px(1.5)}\""
command = f"convert -verbose -size {dimensions} xc:transparent -fill black -stroke black -strokewidth 2 -draw {rectangle_coordinates} \"{filename}\""
print(command)
os.system(command)
</code></pre>
<p>If I remove the variable "rectangle_coordinates" and replace it with hardcode, then it works:</p>
<pre><code>command = f"convert -size {dimensions} xc:transparent -fill black -stroke black -strokewidth 2 -draw \"roundrectangle 0,0 732,142 18,18\" \"{filename}\""
print(command)
os.system(command)
</code></pre>
<p>If I literally copy-paste the results of that print(command) line from the output to the prompt and run it, it runs without error. But when run with os.system, the command it's calling errors.</p>
<p>Anyone see why the command would fail with that one part interpolated, but run fine when it's hardcoded?</p>
<p>P.S. Yes, I know that subprocess.run() is preferred over os.system(). I've tried <em>so many variations</em> of this command during the debugging, splitting up the arguments into a list for each different thing I tried was just adding one more source of (human) errors. I went back to os.system while I hunt the bug. Once I get the bug hammered out, I'll be happy to go back to subprocess.run().</p>
<p>Running the script call as...</p>
<pre><code>subprocess.run(["convert", "-size", dimensions, "xc:transparent", "-fill", "black", "-stroke", "black", "-strokewidth", "2", "-draw", rectangle_coordinates, "\"{resisted_consequence_filename}\""])
</code></pre>
<p>...produces the same (or more) error(s) than the os.system version.</p>
<p>P.P.S. Yes, I'm also aware there are multiple ImageMagick wrappers for Python. I prefer to not add that additional layer of abstraction, especially when bug-hunting.</p>
|
<python><subprocess><imagemagick><string-interpolation><os.system>
|
2023-04-06 01:11:37
| 2
| 1,618
|
baudot
|
75,944,864
| 1,942,603
|
Google Drive API Not showing all revisions
|
<p>I have a Google Sheet that I use to track a project. It has a table on the first page with a bunch of project status stuff on it and I want to write a program to get that table for every revision and show how things have changed. The way to do that should be <a href="https://developers.google.com/drive/api/v3/reference/revisions/list" rel="nofollow noreferrer">this method</a> of the Google Drive API. I did a simple <code>versions = self.drive.revisions().list(fileId=document_id).execute()</code> which at first seemed to work, but only has versions going back to 2023-03-25 while looking at the version history through docs.google.com shows versions going well into last year. I counted how many I see from that line of code and get 78 revisions. In fact, here's the full output.</p>
<pre><code>{
"kind": "drive#revisionList",
"revisions": [
{
"id": "43965",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-25T04:05:30.207Z"
},
{
"id": "43995",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-25T19:41:57.778Z"
},
{
"id": "44001",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-25T20:46:32.836Z"
},
{
"id": "44003",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-25T23:35:26.866Z"
},
{
"id": "44016",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-26T01:13:46.495Z"
},
{
"id": "44022",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-26T03:53:14.166Z"
},
{
"id": "44046",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-26T05:00:20.680Z"
},
{
"id": "44053",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-26T18:24:55.648Z"
},
{
"id": "44059",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-26T20:41:01.992Z"
},
{
"id": "44060",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-27T05:05:01.388Z"
},
{
"id": "44090",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-27T08:47:04.164Z"
},
{
"id": "44104",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-27T15:33:17.366Z"
},
{
"id": "44112",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-27T19:18:54.392Z"
},
{
"id": "44116",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-27T20:27:10.369Z"
},
{
"id": "44119",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-27T22:04:14.144Z"
},
{
"id": "44131",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-28T00:36:44.902Z"
},
{
"id": "44161",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-28T05:28:48.960Z"
},
{
"id": "44180",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-28T15:22:06.105Z"
},
{
"id": "44196",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-28T17:17:20.094Z"
},
{
"id": "44198",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-28T18:41:19.696Z"
},
{
"id": "44200",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-28T19:48:34.181Z"
},
{
"id": "44202",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-28T20:33:35.024Z"
},
{
"id": "44211",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-28T21:53:54.675Z"
},
{
"id": "44220",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-28T23:55:24.729Z"
},
{
"id": "44248",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-29T05:02:39.648Z"
},
{
"id": "44291",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-29T15:31:04.617Z"
},
{
"id": "44298",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-29T18:33:24.005Z"
},
{
"id": "44317",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-30T17:59:07.158Z"
},
{
"id": "44357",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-30T19:36:08.531Z"
},
{
"id": "44363",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-30T20:31:52.080Z"
},
{
"id": "44369",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-31T03:10:20.864Z"
},
{
"id": "44400",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-31T06:44:00.598Z"
},
{
"id": "44407",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-31T17:07:06.371Z"
},
{
"id": "44432",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-03-31T19:23:29.108Z"
},
{
"id": "44457",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-01T10:02:35.601Z"
},
{
"id": "44459",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-01T12:50:52.237Z"
},
{
"id": "44469",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-01T15:57:27.930Z"
},
{
"id": "44477",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-01T16:41:27.471Z"
},
{
"id": "44487",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-01T18:00:38.356Z"
},
{
"id": "44494",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-01T22:20:56.778Z"
},
{
"id": "44520",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-01T23:57:37.239Z"
},
{
"id": "44533",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-02T01:05:43.422Z"
},
{
"id": "44555",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-02T02:31:42.116Z"
},
{
"id": "44602",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-02T04:06:10.102Z"
},
{
"id": "44613",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-02T14:20:36.278Z"
},
{
"id": "44617",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-02T14:52:09.802Z"
},
{
"id": "44661",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-02T16:37:41.966Z"
},
{
"id": "44671",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-02T18:04:39.310Z"
},
{
"id": "44677",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-03T03:02:32.600Z"
},
{
"id": "44707",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-03T04:12:13.984Z"
},
{
"id": "44754",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-03T05:29:27.675Z"
},
{
"id": "44760",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-03T06:42:45.964Z"
},
{
"id": "44781",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-03T16:03:11.685Z"
},
{
"id": "44785",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-03T18:09:33.417Z"
},
{
"id": "44789",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-03T18:51:08.286Z"
},
{
"id": "44793",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-03T20:31:42.634Z"
},
{
"id": "44797",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-03T21:33:15.528Z"
},
{
"id": "44809",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-04T01:41:33.395Z"
},
{
"id": "44816",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-04T03:17:24.988Z"
},
{
"id": "44854",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-04T03:59:19.549Z"
},
{
"id": "44873",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-04T06:08:36.895Z"
},
{
"id": "44890",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-04T08:34:15.162Z"
},
{
"id": "44934",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-04T17:41:27.133Z"
},
{
"id": "44948",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-04T18:31:12.263Z"
},
{
"id": "44979",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-04T19:41:40.078Z"
},
{
"id": "44981",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-04T20:38:27.040Z"
},
{
"id": "44987",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-04T21:22:10.843Z"
},
{
"id": "44989",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-04T22:35:15.787Z"
},
{
"id": "44991",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-05T01:42:06.510Z"
},
{
"id": "45001",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-05T03:23:40.312Z"
},
{
"id": "45110",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-05T06:10:13.567Z"
},
{
"id": "45128",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-05T15:00:26.732Z"
},
{
"id": "45142",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-05T15:59:47.505Z"
},
{
"id": "45155",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-05T16:44:13.218Z"
},
{
"id": "45184",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-05T18:38:09.832Z"
},
{
"id": "45191",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-05T19:22:16.895Z"
},
{
"id": "45201",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-05T20:47:59.776Z"
},
{
"id": "45205",
"mimeType": "application/vnd.google-apps.spreadsheet",
"kind": "drive#revision",
"modifiedTime": "2023-04-05T22:16:58.745Z"
}
]
}
</code></pre>
<p>The API documentation says that if there are too many revisions it will respond with a <code>nextPageToken</code> that can be used to get the excess revisions, but that response doesn't contain one of those. Is there some other method I should be using or what?</p>
|
<python><google-sheets><google-drive-api>
|
2023-04-06 00:12:09
| 1
| 797
|
Joshua Snider
|
75,944,772
| 4,132,818
|
Python can't initialize the sys module when compiling from source (3.11.1) on rhel machine
|
<p>My process was:</p>
<pre><code>wget https://www.python.org/ftp/python/3.11.1/Python-3.11.1.tgz
tar -xvf Python-3.11.1.tgz
cd Python-3.11.1
./configure --enable-shared --prefix=$INSTALL_DIR --enable-optimizations
make
</code></pre>
<p>I get the following error</p>
<pre><code>./Programs/_freeze_module importlib._bootstrap ./Lib/importlib/_bootstrap.py Python/frozen_modules/importlib._bootstrap.h
Fatal Python error: _PySys_InitCore: can't initialize sys module
Python runtime state: preinitialized
Current thread 0x00007f163a9d4740 (most recent call first):
<no Python frame>
make[1]: *** [Python/frozen_modules/importlib._bootstrap.h] Error 1
</code></pre>
<p>What's going on? What is being done wrong?</p>
|
<python><python-3.x>
|
2023-04-05 23:45:13
| 0
| 363
|
Bryan Tan
|
75,944,607
| 1,096,949
|
python is buffering it's stdout in aws eks
|
<p>I am running a python script inside a pod container in aws eks (managed kubernetes service). My script is something like following:</p>
<pre><code>from model import startRunner
import time
while 1:
startRunner()
time.sleep(3600)
print("waited for 1 hour", flush=True)
</code></pre>
<p>I only get the logs if the process crashes. If I run without loop, I only get the logs when it crashes or exited. My expectation was to flush the log as it runs, not buffering it.</p>
<p>I have also added environment variable into the pod as below (true is string though, as I haven't found as way to cast to boolean in manifest of kubernetes configmap):</p>
<pre><code>PYTHONUNBUFFERED : true
</code></pre>
<p>Also, as I am running script with conda, I have the following command to run the script:</p>
<pre><code>CMD ["conda", "run", "-n", "pymc3_env", "python", "-u", "sqs-poll.py"]
</code></pre>
<p>In the above command I have used <code>-u</code> to unbuffer the logs, however, it is still buffering.</p>
<p>Feels like, I am out of tricks. I am a newby in python and using python 3.5 or above to run the script. If anyone can help me to resolve this, that would be amazing. Thanks a lot in advance for any suggestion.</p>
|
<python><kubernetes>
|
2023-04-05 23:05:09
| 1
| 655
|
MD. Jahidul Islam
|
75,944,603
| 2,623,317
|
How to repeat a specific value 'n' times based on other column's list length?
|
<p>I would like to repeat a None value 'n' times, but 'n' should be defined by other column's list length. I give some simple code example to better illustrate this:</p>
<pre class="lang-py prettyprint-override"><code>import polars as pl
# Create dummy LazyFrame
lf = pl.LazyFrame(
{
"col1": [[1, 2, 3], [1, 2], [1]],
"col2": [["A", "B", "C"], ["C"], ["D", "E"]],
}
)
# Print DataFrame
print(lf.collect())
</code></pre>
<pre><code>shape: (3, 2)
βββββββββββββ¬ββββββββββββββββββ
β col1 β col2 β
β --- β --- β
β list[i64] β list[str] β
βββββββββββββͺββββββββββββββββββ‘
β [1, 2, 3] β ["A", "B", "C"] β
β [1, 2] β ["C"] β
β [1] β ["D", "E"] β
βββββββββββββ΄ββββββββββββββββββ
</code></pre>
<p>My attempt:</p>
<pre class="lang-py prettyprint-override"><code># Define condition
condition = pl.col("col2").list.len().eq(pl.col("col1").list.len())
# Apply condition (does not work as I expected)
lf = lf.with_columns(
pl.when(condition)
.then(pl.col("col2"))
.otherwise(
pl.repeat(
value=None,
n=pl.col("col1").list.len(),
)
)
.alias("col3")
).collect()
# Output
print(lf)
</code></pre>
<pre><code>shape: (3, 3)
βββββββββββββ¬ββββββββββββββββββ¬ββββββββββββββββββ
β col1 β col2 β col3 β
β --- β --- β --- β
β list[i64] β list[str] β list[str] β
βββββββββββββͺββββββββββββββββββͺββββββββββββββββββ‘
β [1, 2, 3] β ["A", "B", "C"] β ["A", "B", "C"] β
β [1, 2] β ["C"] β null β
β [1] β ["D", "E"] β null β
βββββββββββββ΄ββββββββββββββββββ΄ββββββββββββββββββ
</code></pre>
<p>But my expected result is:</p>
<pre class="lang-py prettyprint-override"><code>shape: (3, 3)
βββββββββββββ¬ββββββββββββββββββ¬ββββββββββββββββββ
β col1 β col2 β col3 β
β --- β --- β --- β
β list[i64] β list[str] β list[str] β
βββββββββββββͺββββββββββββββββββͺββββββββββββββββββ‘
β [1, 2, 3] β ["A", "B", "C"] β ["A", "B", "C"] β
β [1, 2] β ["C"] β [null, null] β
β [1] β ["D", "E"] β [null] β
βββββββββββββ΄ββββββββββββββββββ΄ββββββββββββββββββ
</code></pre>
<p>Where <code>col3</code> has lists with the same length as <code>col1</code> lists for each row.</p>
|
<python><python-polars>
|
2023-04-05 23:04:13
| 1
| 477
|
Guz
|
75,944,486
| 5,847,282
|
Draw a graph with node size and edge width proportional to number of repetitions
|
<p>I'm working on a paper that is similar to <a href="https://www.pnas.org/doi/10.1073/pnas.0305937101" rel="nofollow noreferrer">this</a>. I have to draw a directed graph that looks similar to <a href="https://www.pnas.org/doi/10.1073/pnas.0305937101#fig2" rel="nofollow noreferrer">the one</a> presented in the paper.</p>
<p>I work primarily in Python, and have explored various options in matplotlib, seaborn and networkx to draw a similar graph, but could not work it out. The input of nodes in my case are a few list of binary numbers of fixed length for a graph. Here I am giving example of binary number of length 5, but the length can go upto 15. So you can imagine the number of all possible nodes can become really large!</p>
<p>For example, the lists that represent the paths may look like:</p>
<pre class="lang-py prettyprint-override"><code>all_possible = [f"{i:>05b}" for i in range(2**5)] # Code to generate all possible states
# Paths taken by the graph
path1 = ['start', '01101', '00001', '11000', '11100', '00010', '00100', 'end']
path2 = ['start', '10001', '00111', '01100', '01110', '10000', '11000', '00101', '11011', '01010', 'end']
path3 = ['start', '11100', '01001', '01100', '00011', '10111', '10000', '00001', 'end']
path4 = ['start', '01100', '01110', '11111', '11011', '10001', '11011', '11101', '00000', 'end']
path5 = ['start', '10001', '11100', '01101', '01001', '01000', '00101', '11001', '00101', '11100', 'end']
</code></pre>
<p>You can imagine the paths all starting from <code>start</code> state and ending at <code>end</code> state. In between they go via various combinations of the possible states. For <code>path1</code> it goes like <code>start -> 01101 -> 00001 -> 11000 -> 11100 -> 00010 -> 00100 -> end</code></p>
<p>Now as more and more edges will merge to, for example node <code>11100</code>, it should become larger or at least change color to indicate a larger number. Same goes for edges, i.e. if same edge is traversed multiple times, for example the edge <code>01100 -> 01110</code> should be wider to represent the number of times it was traversed.</p>
<p>So far I have tried various solutions, but the closest one would be with <code>networkx</code> module:</p>
<pre class="lang-py prettyprint-override"><code>def draw_complete_graph(all_graph_edges: list, fig_size: tuple = (50, 50), graph_img_name: str = "test_graph"):
G = nx.MultiDiGraph()
plt.figure(figsize=fig_size)
for single_edge in all_graph_edges:
G.add_edge(
single_edge[0],
single_edge[-1],
weight=all_graph_edges.count(single_edge),
width=all_graph_edges.count(single_edge),
)
width_list = list(nx.get_edge_attributes(G, "width").values())
nx.draw(
G,
with_labels=True,
node_shape="o",
width=width_list,
connectionstyle="arc3, rad = 0.1",
nodelist=["start", "end"],
)
plt.savefig(graph_img_name)
plt.close()
def get_all_edges(all_paths: list[list]) -> list:
graph_edges = list()
for single_path in all_paths:
graph_edges.append((single_path[0], single_path[1]))
for ix, node in enumerate(graph_edges[1:-2]):
graph_edges.append((node, single_path[ix + 1]))
return graph_edges
if __name__ == "__main__":
edges = get_all_edges([path1, path2, path3, path4, path5])
draw_complete_graph(edges)
</code></pre>
<p>But this does not give me such a result.</p>
<p>My first thought was, is it even possible to do anything close to the graph linked above with Python3? If possible, please help me out and point out what else should I add to reach closer to the graph I require.</p>
|
<python><graph><networkx>
|
2023-04-05 22:37:29
| 1
| 521
|
Asif Iqbal
|
75,944,266
| 15,724,084
|
python tkinter GUI sys exit does not work[multithreading added]
|
<p>my code is mainly scraping pages by clicking <code>next</code> button. I wanted to add a button, when scraping continuously runs having possibility to stop it and exit running the main thread. - just stop program execution. I learnt from this <a href="https://stackoverflow.com/questions/27050492/how-do-you-create-a-tkinter-gui-stop-button-to-break-an-infinite-loop">SO</a> better to run <code>thread</code> asynchronously then I would have a possibility to stop of execution and exit scraping in any moment.
threading added one fine thing that close <code>button</code> does not freeze any more when code is running in the background. But when I click to stop it, the screen of GUI freezes and in background code runs...</p>
<p><code>main</code> module;</p>
<pre><code>...from tk_class_wdgs import *...
def start_app():
create_sheets()
def starting_scraping():
conn(search_var[0])
t=threading.Thread(target=starting_scraping)
t.start()
if __name__=='__main__':
tk_wdg=ClassWidgets()
tk_wdg.btnS['command']=start_app
tk_wdg.btnC['command']=sys.exit
tk_wdg.root.mainloop()
</code></pre>
<p><code>tk_class_wdgs</code> module;</p>
<pre><code>import sys
from tkinter import *
class ClassWidgets():
def __init__(self):
self.root=Tk()
self.frm01=Frame(master=self.root,width=10,height=10,borderwidth=3,bg='red')
self.frm01.pack(expand='YES',fill=BOTH)
self.frm02=Frame(master=self.root,width=10,height=10,borderwidth=3,bg='blue')
self.frm02.pack(expand='YES',fill=BOTH)
self.btnC=Button(master=self.frm02,text='close',bg='yellow')
self.btnC.pack(expand='YES',side='right')
self.btnS=Button(master=self.frm02,text='scrape',foreground='green')
self.btnS.pack(expand='YES',side='left')
self.ent=Entry(master=self.frm01)
self.ent.pack(expand='YES',side='top',fill=X,padx=5,pady=5)
if __name__=='__main__':
tkinter_widgets=ClassWidgets()
tkinter_widgets.root.title('scraper')
tkinter_widgets.btnC['command']=sys.exit
tkinter_widgets.root.mainloop()
</code></pre>
|
<python><multithreading><tkinter>
|
2023-04-05 21:58:34
| 1
| 741
|
xlmaster
|
75,944,115
| 1,100,270
|
add custom tiles to geopandas dataframe
|
<p>I know I can add custom background maps to a geopandas data frame like below</p>
<pre><code>ax = df_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor='k')
cx.add_basemap(ax, source=cx.providers.Stamen.TonerLite)
ax.set_axis_off()
</code></pre>
<p>How could I use other map tiles. For example, USGS topo tiles like those from the national map below?
<a href="https://basemap.nationalmap.gov/arcgis/rest/services/USGSTopo/MapServer/tile/7/46/26" rel="nofollow noreferrer">https://basemap.nationalmap.gov/arcgis/rest/services/USGSTopo/MapServer/tile/7/46/26</a></p>
|
<python><geopandas><cartopy>
|
2023-04-05 21:29:31
| 1
| 1,623
|
jotamon
|
75,944,113
| 3,380,902
|
ProgrammingError: (redshift_connector.ProgrammingError) when running queries using Dask
|
<p>I am attempting to query aws redshift using dask' <a href="https://docs.dask.org/en/stable/generated/dask.dataframe.read_sql_query.html" rel="nofollow noreferrer">read_sql_query</a> method. When I run the below code it throws an</p>
<pre><code>import dask.dataframe as dd
from config import *
host=os.environ['host']
database=os.environ['database']
port='5439'
user=os.environ['user']
password=os.environ['password']
conn_str = f'redshift+redshift_connector://{user}:{password}@{host}:{port}/{database}'
# Query table using dask dataframe
query = text('''
SELECT *
FROM tbl
WHERE type = :type
AND created_at >= :start_date
AND created_at <= :end_date
''')
params = {
'type': 'type1',
'start_date': '2023-01-01 00:00:00',
'end_date': '2023-06-30 00:00:00'
}
selectable = select('*').select_from(query).params(**params)
print(type(selectable))
df = dd.read_sql_query(selectable, conn_str, index_col = 'id')
</code></pre>
<p>Traceback:</p>
<pre><code><class 'sqlalchemy.sql.selectable.Select'>
Unexpected exception formatting exception. Falling back to standard exception
Traceback (most recent call last):
File "/local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.9/site-packages/redshift_connector/core.py", line 1631, in execute
ps = cache["ps"][key]
KeyError: ('SELECT * \nFROM \n SELECT * \n FROM pmf\n WHERE event_type = %s\n AND created_at >= %s\n AND created_at <= %s \n \n LIMIT 5', ((<RedshiftOID.UNKNOWN: 705>, 0, <function text_out at 0x7f7a348d3790>), (<RedshiftOID.UNKNOWN: 705>, 0, <function text_out at 0x7f7a348d3790>), (<RedshiftOID.UNKNOWN: 705>, 0, <function text_out at 0x7f7a348d3790>)))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1900, in _execute_context
self.dialect.do_execute(
File "/local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 736, in do_execute
cursor.execute(statement, parameters)
File "/local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.9/site-packages/redshift_connector/cursor.py", line 240, in execute
self._c.execute(self, operation, args)
File "/local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.9/site-packages/redshift_connector/core.py", line 1701, in execute
self.handle_messages(cursor)
redshift_connector.error.ProgrammingError: {'S': 'ERROR', 'C': '42601', 'M': 'syntax error at or near "SELECT"', 'P': '30', 'F': '/home/ec2-user/padb/src/pg/src/backend/parser/parser_scan.l', 'L': '732', 'R': 'yyerror'}
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/databricks/python/lib/python3.9/site-packages/IPython/core/interactiveshell.py", line 3378, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<command-2539550446659032>", line 19, in <module>
df = dd.read_sql_query(selectable, conn_str, index_col = 'id')
File "/local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.9/site-packages/dask/dataframe/io/sql.py", line 120, in read_sql_query
head = pd.read_sql(q, engine, **kwargs)
File "/local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.9/site-packages/redshift_connector/core.py", line 1969, in handle_messages
raise self.error
sqlalchemy.exc.ProgrammingError: (redshift_connector.error.ProgrammingError) {'S': 'ERROR', 'C': '42601', 'M': 'syntax error at or near "SELECT"', 'P': '30', 'F': '/home/ec2-user/padb/src/pg/src/backend/parser/parser_scan.l', 'L': '732', 'R': 'yyerror'}
[SQL: SELECT *
FROM
SELECT *
FROM pmf
WHERE event_type = %s
AND created_at >= %s
AND created_at <= %s
LIMIT 5]
[parameters: ('type1', '2023-01-01 00:00:00', '2023-06-30 00:00:00')]
(Background on this error at: https://sqlalche.me/e/14/f405)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/databricks/python/lib/python3.9/site-packages/IPython/core/interactiveshell.py", line 1997, in showtraceback
stb = self.InteractiveTB.structured_traceback(
File "/databricks/python/lib/python3.9/site-packages/IPython/core/ultratb.py", line 1112, in structured_traceback
return FormattedTB.structured_traceback(
File "/databricks/python/lib/python3.9/site-packages/IPython/core/ultratb.py", line 1006, in structured_traceback
return VerboseTB.structured_traceback(
File "/databricks/python/lib/python3.9/site-packages/IPython/core/ultratb.py", line 859, in structured_traceback
formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
File "/databricks/python/lib/python3.9/site-packages/IPython/core/ultratb.py", line 812, in format_exception_as_a_whole
frames.append(self.format_record(r))
File "/databricks/python/lib/python3.9/site-packages/IPython/core/ultratb.py", line 730, in format_record
result += ''.join(_format_traceback_lines(frame_info.lines, Colors, self.has_colors, lvals))
File "/databricks/python/lib/python3.9/site-packages/stack_data/utils.py", line 145, in cached_property_wrapper
value = obj.__dict__[self.func.__name__] = self.func(obj)
return only(
File "/databricks/python/lib/python3.9/site-packages/executing/executing.py", line 164, in only
raise NotOneValueFound('Expected one value, found 0')
executing.executing.NotOneValueFound: Expected one value, found 0
ProgrammingError: (redshift_connector.error.ProgrammingError) {'S': 'ERROR', 'C': '42601', 'M': 'syntax error at or near "SELECT"', 'P': '30', 'F': '/home/ec2-user/padb/src/pg/src/backend/parser/parser_scan.l', 'L': '732', 'R': 'yyerror'}
[SQL: SELECT *
FROM
SELECT *
FROM tbl
WHERE event_type = %s
AND created_at >= %s
AND created_at
</code></pre>
|
<python><sqlalchemy><amazon-redshift><dask><dask-dataframe>
|
2023-04-05 21:29:24
| 0
| 2,022
|
kms
|
75,944,022
| 3,681,427
|
How do I ensure that two modules use the same string cache?
|
<p>I'd like to have polars dataframes in multiple modules use the same string cache, but I'm finding it difficult to manage. Imagine I have a package with modules <code>A</code> and <code>B</code>:</p>
<pre class="lang-py prettyprint-override"><code># A.py
import polars as pl
df_A = pl.DataFrame({
'A': pl.Series(['a', 'b', 'c'], dtype=pl.Category)
})
</code></pre>
<pre class="lang-py prettyprint-override"><code># B.py
import polars as pl
df_B = pl.DataFrame({
'A': pl.Series(['a', 'b', 'c'], dtype=pl.Category),
'B': pl.Series(['d', 'e', 'f'], dtype=pl.Category)
})
</code></pre>
<pre class="lang-py prettyprint-override"><code># __init__.py
from . import A, B
pl.toggle_string_cache(True)
df_C = A.df_A.join(B.df_B, on='A')
</code></pre>
<pre><code>exceptions.ComputeError: joins/or comparisons on categoricals can only happen if they were created under the same global string cache
</code></pre>
<p>This works if I move the <code>import</code> after the call to <code>pl.toggle_string_cache(True)</code>, but this is bad code design: imports should always come first. I can think of moving <code>A.df_A</code> and <code>B.df_B</code> into global variables with generator functions, but I was hoping for a more elegant solution.</p>
|
<python><dataframe><python-polars><categorical-data>
|
2023-04-05 21:14:01
| 1
| 382
|
NedDasty
|
75,943,981
| 14,721,356
|
GridSearchCV y should be a 1d array, got an array of shape (54000, 10) instead
|
<p>I've been trying to do grid search on <code>mnist</code> dataset with an <code>MLP</code>. Since <code>mnist</code> dataset is labeled from 0 to 9 and I have 10 neurons in output, I'm using <code>one-hot encoding</code>. But as soon as I try to run grid search, I get the following error: <code>y should be a 1d array, got an array of shape (54000, 10) instead</code>. When I try to use labels as argmax using <code>y.argmax(axis=1)</code> I get another error: <code>ValueError: Shapes (10, 1) and (10, 10) are incompatible</code>. How can I overcome this issue?<br />
I also need to mention that I'm new to data science and neural networks. Thanks in advance</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
from sklearn.experimental import enable_halving_search_cv
from sklearn.model_selection import HalvingGridSearchCV
from tensorflow.keras import Sequential
from tensorflow.keras import optimizers
from tensorflow.keras.layers import Dense
from scikeras.wrappers import KerasClassifier
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
</code></pre>
<pre class="lang-py prettyprint-override"><code>X_train = X_train.reshape((X_train.shape[0], 28 * 28)) / 255.0
Y_train = to_categorical(Y_train)
</code></pre>
<pre class="lang-py prettyprint-override"><code>def create_MLP(hlayer_count=1, hlayer_1_size=64, hlayer_2_size=64,
activation="relu", optimizer="adam", learning_rate=0.01):
print(hlayer_count)
model = Sequential()
# first hidden layer
model.add(Dense(hlayer_1_size, activation=activation, input_shape=(28 * 28,)))
if hlayer_count == 2:
# second hidden layer
model.add(Dense(hlayer_2_size, activation=activation))
# output layer
model.add(Dense(10, activation="softmax"))
# compile model
metrics = ["accuracy"]
if optimizer == "adam":
o = optimizers.Adam(learning_rate=learning_rate)
elif optimizer == "sgd":
o = optimizers.SGD(learning_rate=learning_rate, momentum=0.9)
else:
o = optimizers.RMSprop(learning_rate=learning_rate)
model.compile(loss="categorical_crossentropy",
optimizer=o,
metrics=metrics)
return model
</code></pre>
<pre class="lang-py prettyprint-override"><code>grid_model = KerasClassifier(model=create_MLP, epochs=30, verbose=4)
batch_size = [10, 20, 40, 80]
hlayer_size = [32, 64, 96, 128]
activation = ["relu", "tanh", "sigmoid"]
optimizer = ["adam", "sgd", "rmsprop"]
learning_rate = [0.001, 0.01, 0.05, 0.1]
dict1 = dict(batch_size=batch_size,
model__hlayer_count=[1],
model__hlayer_1_size=hlayer_size,
model__activation=activation,
model__optimizer=optimizer,
model__learning_rate=learning_rate)
dict2 = dict(batch_size=batch_size,
model__hlayer_count=[2],
model__hlayer_1_size=hlayer_size,
model__hlayer_2_size=hlayer_size,
model__activation=activation,
model__optimizer=optimizer,
model__learning_rate=learning_rate)
grid = HalvingGridSearchCV(estimator=grid_model, param_grid=[dict1, dict2], n_jobs=-1, cv=3, error_score="raise")
grid_results = grid.fit(X_train, Y_train)
</code></pre>
|
<python><tensorflow><machine-learning><keras><scikit-learn>
|
2023-04-05 21:08:14
| 1
| 868
|
Ardalan
|
75,943,938
| 1,549,736
|
Why is conda not installing a dist-info for my main installation target, but is for all its dependencies?
|
<p>I'm building/installing a package: <code>foo</code>, using <code>conda</code>, which has several dependencies: <code>bar</code> and <code>blatz</code>, which I'm also building/installing with <code>conda</code>.
They all build without error.
When I <code>conda install foo</code>, <code>foo</code> and all its dependencies get installed correctly and I can run <code>foo</code> just fine.
But, while all <code>foo</code>'s dependencies get equivalent <code>...dist-info</code> folders installed into <code>site-packages/</code>, <code>foo</code> does not!
And that makes it impossible to use the following trick for automatic version reporting:</p>
<p>(<code>foo/__init__.py</code>):</p>
<pre class="lang-py prettyprint-override"><code>from importlib.metadata import version
__version__ = version('foo')
</code></pre>
<p><strong>Why does <code>conda</code> omit the <code>...dist-info</code> folder for the main installation target, while including it for the dependencies?</strong></p>
|
<python><conda><metadata><conda-build>
|
2023-04-05 21:02:37
| 1
| 2,018
|
David Banas
|
75,943,919
| 19,299,757
|
Runtime.ImportModuleError: Unable to import module 'app': No module named 'app'
|
<p>I've a lambda function as a Docker image in my ECR repository.
The lambda function just prints "Welcome" and nothing more.
I've set it up to be invoked whenever there is an S3 bucket activity.
When I upload a file to the S3 bucket, the lambda seem to be invoked but errors out as:</p>
<pre><code>[ERROR] Runtime.ImportModuleError: Unable to import module 'app': No module named 'app' Traceback (most recent call last):
</code></pre>
<p>I can see the error in AWS lambda functions cloudwatch logs.</p>
<p>Below is my app.py</p>
<pre><code>import os
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.info('In app.py................................')
def handler(event, context) -> None:
logger.info('Inside handler....Welcome')
logger.info("Iam from app.py")
logger.info('event: ', event)
logger.info('context: ', context)
</code></pre>
<p>Below is my Dockerfile</p>
<pre><code>FROM public.ecr.aws/lambda/python:3.9
WORKDIR /var/task
COPY . .
RUN pip3 install --no-cache-dir \
--trusted-host pypi.org \
--trusted-host pypi.python.org \
--trusted-host files.pythonhosted.org \
--upgrade pip
RUN pip3 install --no-cache-dir \
--trusted-host pypi.org \
--trusted-host pypi.python.org \
--trusted-host files.pythonhosted.org \
-r requirements.txt \
--target "${LAMBDA_TASK_ROOT}"
CMD [ "app.handler" ]
</code></pre>
<p>I don't know if I ever need WORKDIR since LAMBDA_TASK_ROOT is anyway going to point to /var/task?
But the main issue is that "No module named app"</p>
<p>There is also a <strong>requirements.txt</strong> file but I am not using anything from it.</p>
<pre><code>boto3>=1.24.1
</code></pre>
<p>Appreciate your help.</p>
|
<python><docker><aws-lambda>
|
2023-04-05 21:00:17
| 0
| 433
|
Ram
|
75,943,852
| 13,803,549
|
How to have choices for multiple slash command arguments Discord.py
|
<p>I have a discord.py slash command that takes in two arguments. I wanted to provide choices for these arguments but I can't figure out how.</p>
<p>This is what I have so far but its not working.</p>
<pre class="lang-py prettyprint-override"><code> import discord
from discord import app_commands
from discord.ext import commands
@bot.tree.command(name="schedule")
@app_commands.Argument(name="name", required=True, choices=[])
@app_commands.Argument(name="day", required=True, choices=[], default="Today")
async def schedule(interaction: discord.Interaction, name: str, day: str):
await interaction.response.send_message(f"{name} and {day}")
</code></pre>
|
<python><discord.py>
|
2023-04-05 20:50:15
| 1
| 526
|
Ryan Thomas
|
75,943,803
| 4,332,644
|
Using a Fargate image as lambda
|
<p>I am using AWS Fargate to run a python based Docker image (stored in AWS ECR), and it is working as expected. The invocation is done by a lambda function, which populates the environment and then invokes the Fargate task.</p>
<p>Now I would like to use the same Docker image, but invoke it via SQS trigger. I defined a new function as follows:</p>
<pre><code>def handler(event, context):
print("Handler called!")
print(orjson.dumps(event))
print(orjson.dumps(context))
</code></pre>
<p>and attempted to invoke it by sending a test SQS message.</p>
<p>The docker image is using the following:</p>
<pre><code>ENTRYPOINT [ "python3", "/app/main.py", "run" ]
</code></pre>
<p>I would like to invoke the above handler function instead, and ensure that event and context are available to the handler. How can I embed the event and context as part of either ENTRYPOINT or CMD for the lambda handler?</p>
<p>Clarification:
Right now main.py is using click to handle command-line arguments. If I add another click command for invocation through lambda, the context and event parameters will be lost. I am trying to somehow call /app/main.py and invoke the "handler" function within it, passing event and context as the parameters to the handler function.</p>
|
<python><amazon-web-services><aws-lambda><amazon-ecr>
|
2023-04-05 20:42:48
| 1
| 3,201
|
LNI
|
75,943,689
| 528,369
|
Values returned from Python function differ in caller and callee
|
<p>Running the Python program</p>
<pre><code>import sys
from bisect import bisect
import numpy as np
def insert_sorted(vec, x):
""" insert x in sorted numpy array vec. Return the insertion position
and the new list """
ipos = bisect(vec, x)
print("\nexiting insert_sorted, len(vec), ipos, x =", len(vec), ipos, x)
return ipos, np.insert(vec, ipos, x)
def growing_pos(vec):
""" return the successive positions where the elements of vec would be inserted """
n = len(vec)
if n < 1:
return vec.astype(int)
vec_sorted = np.array([vec[0]])
ipos = np.zeros(shape=n, dtype=np.int8)
for i in range(n):
if i > 0:
ipos[i], vec_sorted = insert_sorted(vec_sorted, vec[i])
print("i, ipos[i], vec[i] =", i, ipos[i], vec[i])
if ipos[i] < 0: # debug
# print("vec_sorted =",vec_sorted)
sys.exit("in growing_pos, should not have ipos[i] < 0")
return ipos
np.random.seed(123)
vec = np.random.uniform(size=1000)
print(growing_pos(vec))
</code></pre>
<p>The program stops with</p>
<pre><code>exiting insert_sorted, len(vec), ipos, x = 132 83 0.6006985678335899
i, ipos[i], vec[i] = 132 83 0.6006985678335899
exiting insert_sorted, len(vec), ipos, x = 133 120 0.8658644583032646
i, ipos[i], vec[i] = 133 120 0.8658644583032646
exiting insert_sorted, len(vec), ipos, x = 134 130 0.9835216092035556
i, ipos[i], vec[i] = 134 -126 0.9835216092035556
in growing_pos, should not have ipos[i] < 0
</code></pre>
<p>I don't understand why at the end <code>ipos</code> in <code>insert_sorted()</code> does not equal <code>ipos[i]</code> in <code>growing_pos()</code>. Using <code>bisect_left()</code> or <code>bisect_right()</code> instead of <code>bisect()</code> gives the same result.</p>
|
<python>
|
2023-04-05 20:23:52
| 1
| 2,605
|
Fortranner
|
75,943,681
| 11,628,437
|
How do I copy all instances of a keyword from a dataframe to another?
|
<p>I have the following data frame A -</p>
<pre><code># Import pandas library
import pandas as pd
data = ['mechanical@engineer', 'field engineer','lab_scientist', 'doctor', 'computer-engineer', 'scientist/engineer']# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['Job'])
print("df = ", df.head())
</code></pre>
<p>Let's say I have a list with the keywords - <code>[engineer, scientist]</code>. I want to create another dataframe B from dataframe A containing A's rows like this -</p>
<pre><code> Keyword Job
0 engineer mechanical@engineer
1 engineer field engineer
2 engineer computer-engineer
3 engineer scientist/engineer
4 scientist lab_scientist
5 scientist scientist/engineer
</code></pre>
<p>I am not really sure how to proceed. Here is my strategy -
I could start by looping over the list and then looping over dataframe A and doing a <code>str.contains()</code>. However, I am not sure how to copy the rows over to another dataframe.</p>
|
<python><pandas>
|
2023-04-05 20:22:37
| 2
| 1,851
|
desert_ranger
|
75,943,587
| 4,972,716
|
Divide a multi column dataframe by a one column dataframe
|
<p>I have 2 dataframes (<code>x_axis</code> and <code>y_axis</code>). I wish to divide <code>y_axis</code> by <code>x_axis</code>, however I get a <code>NaN</code> error. As you can see the index of the two dataframes is the same.</p>
<pre><code>import pandas as pd
x_axis = pd.DataFrame({'I': [1, -3, 4],},
index=['2021-01-01', '2021-01-02', '2021-01-03'])
y_axis = pd.DataFrame({'A': [6, 2, -7],
'B': [-5, 3, 2]},
index=['2021-01-01', '2021-01-02', '2021-01-03'])
z_axis = y_axis / x_axis
</code></pre>
<p>the output I get is:</p>
<pre><code> A B I
2021-01-01 NaN NaN NaN
2021-01-02 NaN NaN NaN
2021-01-03 NaN NaN NaN
</code></pre>
<p>my desired output is:</p>
<pre><code> A B
01/01/2021 6 -5
02/01/2021 -0.666666667 -1
03/01/2021 -1.75 0.5
</code></pre>
|
<python>
|
2023-04-05 20:08:05
| 2
| 5,177
|
Stacey
|
75,943,513
| 1,317,018
|
Cupy is slower than numpy at emulating dot product with one hot vector
|
<p>I was trying to implement neural network from scratch. However it is not possible to run numpy on GPU. So I tried using cupy and benchmarking performance improvement over numpy.</p>
<p>I have following code in numpy:</p>
<pre><code>import numpy as np
emb = 300 # embedding size
m = 2048 # minibatch size
V = 50000 # vocabulary size
# generate 100 random one hot vectors
J = np.random.choice(emb, m)
X = np.zeros((m, emb))
for i, j in enumerate(J):
X[i, j] = 1
W0 = np.random.uniform(-0.8, 0.8, (V, emb)).astype("float32")
# actual computation
start_time = time.time()
for epoch in range(5):
for mb in range(314): # number of minibatches per epoch
h = np.zeros((1), dtype='float32')
for xi in X.T:
w0i = np.argmax(xi)
if not h.any(): h = W0[w0i]
else: h = np.vstack((h, W0[w0i]))
print("%s seconds" % (time.time() - start_time))
</code></pre>
<p>The <code>actual computation</code> part takes 16.55 seconds.</p>
<p>I converted above code into cupy equivalent by simply replacing numpy with cupy</p>
<pre><code>import cupy as cp
# generate 100 random one hot vectors
J = cp.random.choice(emb, m)
X = cp.zeros((m, emb))
for i, j in enumerate(J):
X[i, j] = 1
W0 = cp.random.uniform(-0.8, 0.8, (V, emb)).astype("float32") # V⨯e
# actual computation
start_time = time.time()
for epoch in range(5):
for mb in range(314): # minibatches
h = cp.zeros((1), dtype='float32')
for xi in X.T: # m times
w0i = cp.argmax(xi)
if not h.any(): h = W0[w0i] # (1xe)
else: h = cp.vstack((h, W0[w0i]))
print("%s seconds" % (time.time() - start_time))
</code></pre>
<p>The <code>actual computation</code> part took 2 min 32 seconds (total 152.15 seconds) to execute. I was expecting it to take far lesser time than numpy. But it did not. What I am missing here?</p>
<p><strong>PS:</strong></p>
<ol>
<li>You can access the corresponding colab notebook <a href="https://colab.research.google.com/drive/18BA91hyjImDz8sixTrp_II8Recbh42Bh?usp=sharing" rel="nofollow noreferrer">here</a>.</li>
<li>cupy comes pre-installed in GPU runtime of google colab.</li>
<li>What I am trying to do with that computation?<br />
Actually, I am trying reduce matrix dot product computation time. Above every column of <code>X</code> is one hot vector. So multiply it by any matrix (<code>W0</code> above) has effect of selecting row of a matrix corresponding to position where one hot vector has 1. So, I am trying to iterate through each vector of X, find position of <code>1</code> in the vector and fetch corresponding row from <code>W0</code> and stack them for all <code>m</code> vectors in <code>X</code>. Here is the example for one vector [<a href="https://aegis4048.github.io/optimize_computational_efficiency_of_skip-gram_with_negative_sampling#Review-on-Word2Vec-Skip-Gram" rel="nofollow noreferrer">ref</a>]:</li>
</ol>
<p><a href="https://i.sstatic.net/uNu2L.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/uNu2L.png" alt="enter image description here" /></a></p>
<ol start="4">
<li><p>The linked colab notebook shows <code>np.dot</code> takes 1518.75 seconds while numpy emulation of dot product takes 16.55 seconds. So, numpy emulation is indeed faster than <code>np.dot</code>, but I was expecting cupy on GPU to be even faster, but this is not the case. It takes 152.15 seconds.</p>
</li>
<li><p>The linked colab notebook also shows how the emulation produces same result as <code>np.dot</code> with smaller matrices.</p>
</li>
</ol>
|
<python><python-3.x><numpy><cupy>
|
2023-04-05 19:57:13
| 1
| 25,281
|
Mahesha999
|
75,943,409
| 6,095,646
|
Heroku deployment not picking up latest commits when building Django app (e.g. recent changes to settings.py )
|
<p>I'm using git trying to deploy to a staging pipeline on Heroku.</p>
<p>My build is failing. Based on the traceback (two of them, below), I have a general sense as to why. It involves my dynamic SECRET_KEY configuration variable in <strong>settings.py</strong>. The traceback refers to a python-decouple module installed previously. So I commented out the import line to that package in <strong>settings.py</strong>, removed the package from my requirements.txt, and used this instead:</p>
<pre><code>from dotenv import load_dotenv
load_dotenv()
...
SECRET_KEY = str(os.getenv('SECRET_KEY'))
</code></pre>
<p>That's the latest version. When I save my changes, commit them, and then push to the staging pipeline, the traceback being returned refers to line 27 as if is still like this:</p>
<pre><code>from decouple import config
...
SECRET_KEY = config('SECRET_KEY')
</code></pre>
<p>Iβm not sure why Heroku is not picking up the latest and most recent changes. Any ideas?</p>
<p>Here is my full build traceback:</p>
<pre><code>$ git push staging main
Enumerating objects: 4016, done.
Counting objects: 100% (4016/4016), done.
Delta compression using up to 20 threads
Compressing objects: 100% (3932/3932), done.
Writing objects: 100% (3965/3965), 6.41 MiB | 3.71 MiB/s, done.
Total 3965 (delta 302), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (302/302), completed with 15 local objects.
remote: Updated 7290 paths from c9c269d
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Building on the Heroku-22 stack
remote: -----> Using buildpack: heroku/python
remote: -----> Python app detected
remote: -----> Using Python version specified in runtime.txt
remote: -----> Python version has changed from python-3.11.2 to python-3.10.10, clearing cache
remote: -----> Requirements file has been changed, clearing cached dependencies
remote: -----> Installing python-3.10.10
remote: -----> Installing pip 23.0.1, setuptools 63.4.3 and wheel 0.38.4
remote: -----> Installing SQLite3
remote: -----> Installing requirements with pip
remote: Collecting asgiref==3.6.0
remote: Downloading asgiref-3.6.0-py3-none-any.whl (23 kB)
remote: Collecting certifi==2022.12.7
remote: Downloading certifi-2022.12.7-py3-none-any.whl (155 kB)
remote: Collecting charset-normalizer==3.1.0
remote: Downloading charset_normalizer-3.1.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (199 kB)
remote: Collecting dj-database-url==1.3.0
remote: Downloading dj_database_url-1.3.0-py3-none-any.whl (7.4 kB)
remote: Collecting django==4.1.8
remote: Downloading Django-4.1.8-py3-none-any.whl (8.1 MB)
remote: Collecting django-ckeditor==6.5.1
remote: Downloading django_ckeditor-6.5.1-py3-none-any.whl (2.4 MB)
remote: Collecting django-heroku==0.3.1
remote: Downloading django_heroku-0.3.1-py2.py3-none-any.whl (6.2 kB)
remote: Collecting django-jazzmin==2.6.0
remote: Downloading django_jazzmin-2.6.0-py3-none-any.whl (2.8 MB)
remote: Collecting django-js-asset==2.0.0
remote: Downloading django_js_asset-2.0.0-py3-none-any.whl (4.9 kB)
remote: Collecting gunicorn==20.1.0
remote: Downloading gunicorn-20.1.0-py3-none-any.whl (79 kB)
remote: Collecting heroku3==5.2.0
remote: Downloading heroku3-5.2.0-py2.py3-none-any.whl (161 kB)
remote: Collecting idna==3.4
remote: Downloading idna-3.4-py3-none-any.whl (61 kB)
remote: Collecting pillow==9.5.0
remote: Downloading Pillow-9.5.0-cp310-cp310-manylinux_2_28_x86_64.whl (3.4 MB)
remote: Collecting psycopg2==2.9.6
remote: Downloading psycopg2-2.9.6.tar.gz (383 kB)
remote: Preparing metadata (setup.py): started
remote: Preparing metadata (setup.py): finished with status 'done'
remote: Collecting python-dateutil==2.8.2
remote: Downloading python_dateutil-2.8.2-py2.py3-none-any.whl (247 kB)
remote: Collecting python-dotenv==1.0.0
remote: Downloading python_dotenv-1.0.0-py3-none-any.whl (19 kB)
remote: Collecting pytz==2023.3
remote: Downloading pytz-2023.3-py2.py3-none-any.whl (502 kB)
remote: Collecting requests==2.28.2
remote: Downloading requests-2.28.2-py3-none-any.whl (62 kB)
remote: Collecting six==1.16.0
remote: Downloading six-1.16.0-py2.py3-none-any.whl (11 kB)
remote: Collecting sqlparse==0.4.3
remote: Downloading sqlparse-0.4.3-py3-none-any.whl (42 kB)
remote: Collecting typing-extensions==4.5.0
remote: Downloading typing_extensions-4.5.0-py3-none-any.whl (27 kB)
remote: Collecting urllib3==1.26.15
remote: Downloading urllib3-1.26.15-py2.py3-none-any.whl (140 kB)
remote: Collecting whitenoise==6.4.0
remote: Downloading whitenoise-6.4.0-py3-none-any.whl (19 kB)
remote: Building wheels for collected packages: psycopg2
remote: Building wheel for psycopg2 (setup.py): started
remote: Building wheel for psycopg2 (setup.py): finished with status 'done'
remote: Created wheel for psycopg2: filename=psycopg2-2.9.6-cp310-cp310-linux_x86_64.whl size=159971 sha256=633a65b5bc08894912275e69ae23e45eb18511e0fb0be56037f9da7f9d301ceb
remote: Stored in directory: /tmp/pip-ephem-wheel-cache-pghrau7m/wheels/a2/65/83/78e6f42d3b8e22115e894576b71799d96ab5a790b8f7bcfa85
remote: Successfully built psycopg2
remote: Installing collected packages: pytz, whitenoise, urllib3, typing-extensions, sqlparse, six, python-dotenv, psycopg2, pillow, idna, gunicorn, charset-normalizer, certifi, asgiref, requests, python-dateutil, django, heroku3, django-js-asset, django-jazzmin, dj-database-url, django-heroku, django-ckeditor
remote: Successfully installed asgiref-3.6.0 certifi-2022.12.7 charset-normalizer-3.1.0 dj-database-url-1.3.0 django-4.1.8 django-ckeditor-6.5.1 django-heroku-0.3.1 django-jazzmin-2.6.0 django-js-asset-2.0.0 gunicorn-20.1.0 heroku3-5.2.0 idna-3.4 pillow-9.5.0 psycopg2-2.9.6 python-dateutil-2.8.2 python-dotenv-1.0.0 pytz-2023.3 requests-2.28.2 six-1.16.0 sqlparse-0.4.3 typing-extensions-4.5.0 urllib3-1.26.15 whitenoise-6.4.0
remote: -----> $ python manage.py collectstatic --noinput
remote: Found another file with the destination path 'admin/js/popup_response.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path.
remote: Found another file with the destination path 'admin/js/cancel.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path.
remote: Post-processing 'vendor/bootswatch/default/bootstrap.min.css' failed!
remote: Traceback (most recent call last):
remote: File "/tmp/build_6ab523f7/manage.py", line 22, in <module>
remote: main()
remote: File "/tmp/build_6ab523f7/manage.py", line 18, in main
remote: execute_from_command_line(sys.argv)
remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
remote: utility.execute()
remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute
remote: self.fetch_command(subcommand).run_from_argv(self.argv)
remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv
remote: self.execute(*args, **cmd_options)
remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute
remote: output = self.handle(*args, **options)
remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 209, in handle
remote: collected = self.collect()
remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 154, in collect
remote: raise processed
remote: whitenoise.storage.MissingFileError: The file 'vendor/bootswatch/default/bootstrap.min.css.map' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x7f0bf2f350c0>.
remote: The CSS file 'vendor/bootswatch/default/bootstrap.min.css' references a file which could not be found:
remote: vendor/bootswatch/default/bootstrap.min.css.map
remote: Please check the URL references in this CSS file, particularly any
remote: relative paths which might be pointing to the wrong location.
remote:
remote: ! Error while running '$ python manage.py collectstatic --noinput'.
remote: See traceback above for details.
remote:
remote: You may need to update application code to resolve this error.
remote: Or, you can disable collectstatic for this application:
remote:
remote: $ heroku config:set DISABLE_COLLECTSTATIC=1
remote:
remote: https://devcenter.heroku.com/articles/django-assets
remote: ! Push rejected, failed to compile Python app.
remote:
remote: ! Push failed
remote: Verifying deploy...
remote:
remote: ! Push rejected to <project-name>
remote:
To https://git.heroku.com/<project-name>.git
! [remote rejected] main -> main (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/<project-name>.git'
</code></pre>
<p>As you can see, it says: βError while running '$ python manage.py collectstatic --noinput'.
remote: See traceback above for details.β So here is <strong>$ python manage.py collectstatic --noinput</strong> on my remote server which does provide further insight:</p>
<pre><code>βΊ heroku ps:exec -a <project-name>
βΊ Warning: heroku update available from 7.67.2 to 7.68.2.
Establishing credentials... done
Connecting to web.1 on β¬’ <project-name>..
(failed reverse-i-search)`': ^C
~ $ python manage.py collectstatic --noinput
Traceback (most recent call last):
File "/app/manage.py", line 22, in <module>
main()
File "/app/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python3.11/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python3.11/site-packages/django/core/management/__init__.py", line 386, in execute
settings.INSTALLED_APPS
File "/app/.heroku/python/lib/python3.11/site-packages/django/conf/__init__.py", line 92, in __getattr__
self._setup(name)
File "/app/.heroku/python/lib/python3.11/site-packages/django/conf/__init__.py", line 79, in _setup
self._wrapped = Settings(settings_module)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/app/.heroku/python/lib/python3.11/site-packages/django/conf/__init__.py", line 190, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/app/.heroku/python/lib/python3.11/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/app/<project-name>/settings.py", line 27, in <module>
SECRET_KEY = config('SECRET_KEY')
^^^^^^^^^^^^^^^^^^^^
File "/app/.heroku/python/lib/python3.11/site-packages/decouple.py", line 248, in __call__
return self.config(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/app/.heroku/python/lib/python3.11/site-packages/decouple.py", line 107, in __call__
return self.get(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/app/.heroku/python/lib/python3.11/site-packages/decouple.py", line 92, in get
raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option))
decouple.UndefinedValueError: SECRET_KEY not found. Declare it as envvar or define a default value.
</code></pre>
<p>As you can see it is referring to line 27 with a SECRET_KEY using decoupleβs config function but I have assuredly commented that out in my latest settings.py as described originally above. So I am not sure why Heroku is not looking at the most recent version in my latest commit.</p>
<p>Any idea what could be going on?</p>
<p>Please note: I added <strong>git</strong> as a tag because that is the tool I am using to handle my Heroku deploys.</p>
<p>For what it may be worth, if it helps, here is my full settings.py that I am working with:</p>
<pre><code>"""
Django settings for <project-name>.
Generated by 'django-admin startproject' using Django 4.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
import os
import django_heroku
# from decouple import config
import dj_database_url
from dotenv import load_dotenv
load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# SECRET_KEY = config('SECRET_KEY')
SECRET_KEY = str(os.getenv('SECRET_KEY'))
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*',]
# Application definition
INSTALLED_APPS = [
'jazzmin',
'django.contrib.admin',
'ckeditor',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'contributors',
'articles',
# 'landings.apps.LandingsConfig',
'stock_pages',
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = '<project-name>.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = '<project-name>.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
'''
DATABASES = {
'default': dj_database_url.config(
default='sqlite:///'+os.path.join(BASE_DIR, 'db.sqlite3'),
conn_max_age=600)
}
# DATABASES['default'] = dj_database_url.config(default='')
db_from_env=dj_database_url.config(conn_max_age=600)
DATABASES['default'].update(db_from_env)\
'''
DATABASES = { 'default' :
{'ENGINE': 'django.db.backends.postgresql'}
}
DATABASES = {
'default': dj_database_url.config(
default='sqlite:///'+os.path.join(BASE_DIR, 'db.sqlite3'),
conn_max_age=600)
}
# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [BASE_DIR / 'static']
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
CKEDITOR_BASEPATH = "/staticfiles/ckeditor/ckeditor/"
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
django_heroku.settings(locals())
JAZZMIN_SETTINGS = {
"order_with_respect_to": ["stock_pages", "contributors", "articles",],
}
</code></pre>
|
<python><django><git><heroku>
|
2023-04-05 19:40:57
| 1
| 443
|
enoren5
|
75,943,319
| 220,255
|
pysftp listdir_attr empty on a folder with files
|
<p>I have a small utility that scans ftp server and does some analytics around available data. This code works fine for many servers but does not work for one particular server. I am sure the data is available on the server, lots of data, but it only lists the top folders and when goes inside of them just gets nothing.</p>
<p>Nothing fails, just empty data in the <code>listdir_attr</code></p>
<p>I tried looking into the connection options that may influence this, but there doesn't seem any relevant. Has anyone faced similar issues?</p>
<pre class="lang-py prettyprint-override"><code>import pysftp
import os
class Connector:
def __init__(self, host: str, user: str, password: str, port: int = 22, root: str = "."):
ops = pysftp.CnOpts()
ops.hostkeys = None
self.root = root
self.client = pysftp.Connection(host=host, username=user, password=password, port=port, cnopts=ops)
self.stats = list()
def __looper(self, folder):
for f in self.client.listdir_attr(folder):
f.attr["path"] = folder
f.attr["props"] = f.longname[:10]
self.stats.append(f)
if f.longname.startswith("d"):
self.__looper(os.path.join(folder, f.filename))
def build_stats(self):
self.__looper(self.root)
self.client.close()
return self.stats
</code></pre>
|
<python><pysftp>
|
2023-04-05 19:26:45
| 1
| 4,350
|
abolotnov
|
75,943,276
| 19,797,660
|
Pipe connection between Python and C# in two directions - sending data
|
<p>I have a huge problem with connection between my <code>python</code> script and <code>C#</code> WFA application.
For some reason the code worked two days ago last I checked and today when I started the script the connection is not establishing which is very odd.</p>
<p>So below is my C# code connection:</p>
<pre><code> if (result == DialogResult.Yes)
{
Thread t = new Thread(() =>
{
// Create a named pipe server
NamedPipeServerStream server = new NamedPipeServerStream("mypipe");
// Wait for a client to connect
server.WaitForConnection();
// Send data to the client
byte[] data = Encoding.UTF8.GetBytes("Hello from C#!");
server.Write(data, 0, data.Length);
// Disconnect from the client and cleanup resources
server.Disconnect();
server.Dispose();
});
t.Start();
this.Close();
Application.Exit();
}
</code></pre>
<p>Here is my python code that is calling the C# application:</p>
<pre><code> # Run the C# subprocess in parallel
p = subprocess.Popen(['C:/Users/.../source/repos/UI_Variables_Prompt/UI_Variables_Prompt/bin/Debug/UI_Variables_Prompt.exe', str(calculation_tool)])
p.wait()
# Connect to the named pipe server
client = win32file.CreateFile(r'\\.\pipe\mypipe', win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None)
# Receive data from the server
data = win32file.ReadFile(client, 4096)[1].decode('utf-8')
print(data)
# Disconnect from the server and cleanup resources
win32file.CloseHandle(client)
</code></pre>
<p>The <code>calculation_tool</code> variable is succesfully being sent to C# but that is all, when I click <code>confirm button</code> i.e. start this case <code>if (result == DialogResult.Yes)</code> in <code>C#</code> the process is freezing and It seems that the data is not being sent.</p>
<p>I am struggling with this for two hours, and I can't seem to find a solution, please help.</p>
<p>Thank You in advance!</p>
<p>EDIT:</p>
<pre><code>p.wait() in your Python code will wait until the process
terminates. The process can't terminate until it has communicated,
but it can't communicate because the Python is waiting.
You do NOT want p.wait() there. β
Tim Roberts
</code></pre>
<p>This is right, however without <code>p.wait()</code> python tries to communicate with a non-existing pipe, because the C# process terminates before it can establish a connection.</p>
<pre><code>client = win32file.CreateFile(r'\\.\pipe\mypipe', win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None)
pywintypes.error: (2, 'CreateFile', 'The system cannot find the file specified.')
</code></pre>
<p>EDIT 2:</p>
<p>It worked with <code>try-except</code> instead of <code>p.wait()</code> <strong>BUT</strong> how can I change the code so the pipe will be connected so the user won't have to wait a couple of seconds for the app to connect - because on first try it always throws back the same error I posted above.</p>
<pre><code># Connect to the named pipe server
connected = False
while not connected:
try:
client = win32file.CreateFile(r'\\.\pipe\mypipe', win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0,
None, win32file.OPEN_EXISTING, 0, None)
connected = True
print('Connected')
except:
print('Failed to connect to named pipe, retrying in 5 seconds...')
time.sleep(5)
</code></pre>
|
<python><c#><python-3.x><pipe>
|
2023-04-05 19:21:32
| 0
| 329
|
Jakub Szurlej
|
75,943,159
| 12,297,666
|
How to manually set the validation set size in 10-Fold CV
|
<p>I have a dataset with <code>5829</code> rows and i need to do cross validation to assess my model. Using <code>Sklearn</code> is there anyway i can fix the size of the validation set (let's say to <code>20%</code> of my data) and keep fixed the number of folds to <code>10</code>?</p>
<p>If i use <code>5</code> folds, i get <code>20%</code> of the data into the validation set at each fold, but i need to use 10 folds instead. So, at each fold, i need to have <code>5829*0.2 = 1165</code> samples for validation.</p>
<p><strong>EDIT:</strong> The data should look like this, not shuffled/randomized, but with 10 CV iterations. The first iteration should use the first 20% of data for validation. The second iteration should use the next 20% and so on.</p>
<p><a href="https://i.sstatic.net/OM0MK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/OM0MK.png" alt="enter image description here" /></a></p>
|
<python><scikit-learn><cross-validation>
|
2023-04-05 19:04:00
| 2
| 679
|
Murilo
|
75,943,057
| 6,131,786
|
I can't find how to reproducibly run a Python gymnasium taxi-v3 environment
|
<p>I'm using Gymnasium library (<a href="https://github.com/Farama-Foundation/Gymnasium" rel="nofollow noreferrer">https://github.com/Farama-Foundation/Gymnasium</a>) for some research in reinforcement learning algorithms.</p>
<p>Gymnasium is the actual development of the old Gym library (<a href="https://github.com/openai/gym" rel="nofollow noreferrer">https://github.com/openai/gym</a>).</p>
<p>I want to reproducibly run a Python Gymnasium environment "taxi-v3".</p>
<p>What is usually done is to pass a seed to the random number generators involved.</p>
<p>But, even doing things like this:</p>
<pre><code>import gymnasium as gym
import numpy as np
import random
seed = 42
random.seed(seed)
np.random.seed(seed)
env = gym.make("Taxi-v3")
state, info = env.reset(seed=seed)
</code></pre>
<p>I couldn't reach my goal.</p>
<p>What am I not understanding?</p>
<p>What is missing?</p>
|
<python><reinforcement-learning><openai-gym>
|
2023-04-05 18:50:15
| 1
| 319
|
Anselmo Blanco Dominguez
|
75,943,045
| 11,192,275
|
Passing parameters to a function when aggregating using pandas and numpy in python
|
<p>I have the following code and data frame:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5],
'B': [6, 7, 8, 9, 10]})
</code></pre>
<p>I want to calculate the 0.25 percentile for the column 'A' and the 0.75 percentile for the column 'B' using np.quantile. I try the following code:</p>
<pre><code>(df.
agg({'A' : lambda x: np.quantile(a=x, q=0.25),
'B' : lambda x: np.quantile(a=x, q=0.75)}))
</code></pre>
<p>I obtain the following result:</p>
<pre><code> A B
0 1.0 6.0
1 2.0 7.0
2 3.0 8.0
3 4.0 9.0
4 5.0 10.0
</code></pre>
<p>However I was expecting the following result or something similar:</p>
<pre><code>A 2.0
B 9.0
dtype: float64
</code></pre>
<p>The problem is that the lambda functions are computing the quantiles for each element of the series, rather than for the series as a whole.</p>
<p>My question is how I can obtain the expected result if a I want to use the agg function from pandas and the quantile function from numpy if I want to pass different parameters to a function using lambda functions.</p>
<p>I already read the posts <a href="https://stackoverflow.com/questions/26354329/python-pandas-passing-multiple-functions-to-agg-with-arguments">Python Pandas: Passing Multiple Functions to agg() with Arguments</a> and <a href="https://stackoverflow.com/questions/43964439/specifying-arguments-to-pandas-aggregate-function">Specifying arguments to pandas aggregate function</a> but they only work when the data is grouped and not when the data is not grouped.</p>
|
<python><pandas><numpy>
|
2023-04-05 18:49:06
| 2
| 456
|
luifrancgom
|
75,943,023
| 14,465,381
|
TypeError: 'float' object is not callable in for loop declaration
|
<p>I'm attempting to display an <code>.obj</code> file in the console, and ran into a strange issue where a TypeError popped up for a <code>for</code> loop declaration that I had previously used, word for word. I can't seem to find the cause of this error.</p>
<pre><code>vertices = [[2.4,5.6,2.1],[54.3,67.1,90.8],[21.9,73.5,12.3]]
def main():
vertMinX = minmax(vertices, False)
vertRangeX = minmax(vertices, True)-vertMinX
for i in range(len(vertices)):
print(1)
normalize(vertices,vertMinX,vertRangeX)
def minmax(data, max):
n=0
val = data[0][n]
if max:
for i in range(len(data)):
if val < data[i][n]:
val = data[i][n]
else:
for i in range(len(data)):
if val > data[i][n]:
val = data[i][n]
return val
def normalize(data, min, range):
for i in range(len(data)):
print(1)
main()
</code></pre>
<p>returns</p>
<pre class="lang-sh prettyprint-override"><code>1
1
1
Traceback (most recent call last):
File "main.py", line 25, in <module>
main()
File "main.py", line 7, in main
normalize(vertices,vertMinX,vertRangeX)
File "main.py", line 23, in normalize
for i in range(len(data)):
TypeError: 'float' object is not callable
</code></pre>
|
<python><list><for-loop><floating-point><typeerror>
|
2023-04-05 18:44:53
| 0
| 336
|
Baby_Boy
|
75,942,928
| 20,947,319
|
How to scrape all data from Linkedin using Python in incognito mode
|
<p>I am working on a python project whereby I am scraping data from linkedin using selenium and beautifulsoup. My program works fine but the problem is that it gets only 25 results instead of all the results. I have gone through previous solutions to this and they are saying that I can use the page number. The problem is that to load more data, one has to scroll to the bottom and the loaded data does not change the page number.
Also after scrolling for some time, you will get a "load more" button which has to be clicked to load more items. Here is my program:</p>
<pre><code> from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup as beauty
import re
import requests
import logging
import time
from datetime import datetime, timedelta
chrome_options = Options()
chrome_options.add_argument("--headless=new")
chrome_options.add_argument("incognito")
url_link = 'https://www.linkedin.com/jobs/search/?currentJobId=3187861296&geoId=102713980&keywords=mckinsey&location=India&refresh=true'
driver = webdriver.Chrome(
service=Service(ChromeDriverManager().install()), options=chrome_options
)
if url_link.split(".")[1] == "linkedin":
print(f"{url_link} is found and active. Scraping jobs from it")
response = requests.get(url_link)
soup = beauty(response.content, "html.parser")
jobs = soup.find_all(
"div",
class_="base-card relative w-full hover:no-underline focus:no-underline base-card--link base-search-card base-search-card--link job-search-card",
)
for job in jobs:
try:
job_title = job.find(
"h3", class_="base-search-card__title"
).text.strip()
with open("job_title.txt", "a") as f:
print(f"Job title is {job_title}", file=f)
job_company = job.find(
"h4", class_="base-search-card__subtitle"
).text.strip()
with open("job_company.txt", "a") as f:
print(f"Job company is {job_company}", file=f)
job_location = job.find(
"span", class_="job-search-card__location"
).text.strip()
except Exception as e:
print(f"warning {e}")
continue
</code></pre>
<p>Any help will be highly appreciated. Thanks.</p>
|
<python><selenium-webdriver><web-scraping><beautifulsoup>
|
2023-04-05 18:31:21
| 1
| 446
|
victor
|
75,942,865
| 1,006,183
|
Async solution for factory boy style fixtures in FastAPI?
|
<p>I really like the <a href="https://factoryboy.readthedocs.io/en/stable/" rel="noreferrer">factory boy</a> style of generated factories that can handle things like sequences, complex relationships etc.</p>
<p>For a FastAPI app with fully async database access using factory boy seems likely problematic. There is <a href="https://github.com/FactoryBoy/factory_boy/issues/679" rel="noreferrer">dated discussion here</a> and an <a href="https://github.com/FactoryBoy/factory_boy/pull/803" rel="noreferrer">old PR</a> to add async support that seems stuck.</p>
<p>Is there a good solution for these kinds of fixtures that has full async support?</p>
|
<python><fastapi><fixtures><factory-boy>
|
2023-04-05 18:24:45
| 1
| 11,485
|
Matt Sanders
|
75,942,747
| 10,303,685
|
No mic get detected as sound.query_devices() returns empty list?
|
<p>Im trying to get the feed of the mic using "sounddevice" library in Python.</p>
<pre><code>import sounddevice as sd
print(sd.query_devices())
</code></pre>
<p>But it returns empty list.</p>
<p>I tried <code>arecord -f cd -d 6 test.wav</code> to record a voice note and it works fine. Also i checked the mic using online voice recorder tools where the mic works fine. Any idea what could be the possible error ?</p>
|
<python><audio><speech-recognition><audio-processing><python-sounddevice>
|
2023-04-05 18:09:55
| 2
| 388
|
imtiaz ul Hassan
|
75,942,685
| 1,761,521
|
AWS CDK: Conditional resources?
|
<p>I am trying to create a cron event that runs daily on the <code>PROD</code> environment and just once a week on the <code>DEV</code> environment. My code looks like this,</p>
<pre><code>environment = CfnParameter(
self,
"environment",
type="String",
description="Environment e.g. DEV|PROD",
default="DEV",
allowed_values=["DEV", "PROD"],
)
if environment.value_as_string == "PROD":
rule = events.Rule(
self,
"Some clever description",
schedule=events.Schedule.cron(minute="0", hour="2", week_day="TUE,WED,THU,FRI,SAT"),
)
else:
rule = events.Rule(
self,
"Some clever description",
schedule=events.Schedule.cron(minute="0", hour="2", week_day="TUE"),
)
</code></pre>
<p>My issue is that on my prod account when I check the cloudformation parameters its showing <code>PROD</code> however the event is only running once a week?</p>
|
<python><amazon-web-services><aws-cdk>
|
2023-04-05 18:01:41
| 1
| 3,145
|
spitfiredd
|
75,942,588
| 2,444,751
|
headless cli scripting (in my case, bash, Ubuntu 20)
|
<p>I'm curious if there is a way to write scripts in php, python, or nodejs that interact with a virtual command line interface as if you were typing on a keyboard, and which reads all characters sent to the screen, even if the command you called starts its own separate process (thus bypassing the stdin/stdout streams).</p>
<p>Something analogous to a headless web browsing library but for a cli such as bash.</p>
<p>I tried doing this with macro scripts but that involved precise positioning of the window so that the mouse could select and copy the correct text.</p>
<p>Edit (response to Barmar): like an "except" script but using something like php so writing complex scripts is easier.</p>
|
<python><php><node.js><command-line-interface>
|
2023-04-05 17:48:15
| 0
| 593
|
Dustin Soodak
|
75,942,526
| 1,999,585
|
How can I fix the "A value is trying to be set on a copy of a slice from a DataFrame" warning in pandas?
|
<p>I have the following Python function:</p>
<pre><code>def compute_average_fg_rating(df, mask=''):
df = df[['HorseId', 'FGrating']]
if len(mask) == 0:
df.loc['cumsum'] = df.groupby('HorseId', group_keys=False)['FGrating'].apply(
lambda x: x.shift(fill_value=0).cumsum())
return df.loc['cumsum'] / df.groupby('HorseId')['FGrating'].cumcount()
else:
return df.loc[mask].groupby('HorseId', group_keys=False)['FGrating'].apply(
lambda x: x.shift().expanding().mean())
</code></pre>
<p>When I try to run the code, I get the "A value is trying to be set on a copy of a slice from a DataFrame" warning at the line:</p>
<pre><code> df.loc['cumsum'] = df.groupby('HorseId', group_keys=False)['FGrating'].apply(
lambda x: x.shift(fill_value=0).cumsum())
</code></pre>
<p>I cannot see where the problematic code is. Can you help me?</p>
|
<python><pandas><dataframe><warnings>
|
2023-04-05 17:41:34
| 2
| 2,424
|
Bogdan Doicin
|
75,942,420
| 7,245,066
|
run post_install on pyproject.toml
|
<p>In my classic <code>setup.py</code> script, I have a post_install method that registers my python widget with a jupyter notebook. How do I do this using the pyproject.toml file? I can't seem to find any documentation on this.</p>
<p>doc: <a href="https://setuptools.pypa.io/en/latest/userguide/extension.html" rel="nofollow noreferrer">https://setuptools.pypa.io/en/latest/userguide/extension.html</a></p>
<p>I have these classes defined in my <code>setup.py</code> file that need to be run. Is there a way to replicate this in the new pyproject.toml system?</p>
<pre><code># Each of these classes represent the different modes that pip install
# can go into, and what logic can be run after pip install finishes
class develop(_develop):
"""Post-installation logic to run for development mode"""
def run(self):
self.execute(_post_install, (), msg="Running post-install...")
super().run()
class install(_install):
"""Post-installation logic to run for installation mode"""
def run(self):
self.execute(_post_install, (), msg="Running post-install...")
super().run()
class egg_info(_egg_info):
"""Post-installation logic to run for 'egg_info' mode"""
def run(self):
self.execute(_post_install, (), msg="Running post-install...")
super().run()
</code></pre>
<p>In the setup.py here is the part that I need to call:</p>
<pre><code> "cmdclass": {
"develop": develop,
"install": install,
"egg_info": egg_info,
},
</code></pre>
|
<python><setuptools><setup.py><python-packaging><pyproject.toml>
|
2023-04-05 17:29:21
| 0
| 403
|
JabberJabber
|
75,942,381
| 875,806
|
Implement Acuity (Squarespace scheduling) webhook signature validation in python
|
<p>The <a href="https://developers.acuityscheduling.com/docs/webhooks#verifying-webhook-requests" rel="nofollow noreferrer">Acuity webhook documentation</a> describes the steps to verify the source of the webhook is from Acuity.</p>
<blockquote>
<p>First compute the base64 <code>HMAC-SHA256</code> signature of the notification using the request's body as the message and your API key as the shared secret. Then compare this signature to the request header <code>X-Acuity-Signature</code>. If they match, the notification is authentic.</p>
</blockquote>
<p>And then it provides some code samples for PHP, JavaScript, and Ruby. These samples help clarify a bit, but use variables without describing their source, leaving me to guess what they refer to. I haven't been able to verify messages.</p>
<p>Here's the code I'm using:</p>
<pre class="lang-py prettyprint-override"><code>acuity_api_key = 'redacted'
key_bytes = acuity_api_key.encode('utf-8')
signature = request.headers['x-acuity-signature']
message = request.body
message_bytes = message.encode('utf-8')
signed_body = base64.b64encode(
hmac.new(key_bytes, message_bytes, hashlib.sha256).digest()
).decode('utf-8')
if signature != signed_body:
raise RuntimeError('Failed to validate message signature')
</code></pre>
|
<python><squarespace>
|
2023-04-05 17:24:30
| 1
| 4,388
|
CoatedMoose
|
75,942,274
| 6,042,824
|
Replit: Getting error 'couldn't connect to display' on a repl using Tkinter
|
<p>Getting the following error on a <code>repl</code> of mine (<a href="https://replit.com/@BileshGanguly/Tic-Tac-Toe-GUI" rel="nofollow noreferrer">Tic-Tac-Toe GUI</a>) where I'm using <code>Tkinter</code>.</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 99, in <module>
root = tk.Tk()
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/tkinter/__init__.py", line 2299, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: couldn't connect to display ":0"
</code></pre>
<p>It was working up until yesterday.</p>
<p>This seems to be an error faced by people working on less popular Linux distros (<a href="https://stackoverflow.com/questions/59006466/local-machine-tkinter-tclerror-couldnt-connect-to-display-0">local machine _tkinter.TclError: couldn't connect to display ":0"</a>) and the following update to the PATH variable seems to be fixing the issue.</p>
<pre><code>export DISPLAY=unix$DISPLAY
</code></pre>
<p>Not sure why suddenly this became an issue, also, not sure how I can fix it on Replit. Any suggestions/help will be appreciated.</p>
|
<python><tkinter><replit>
|
2023-04-05 17:12:12
| 0
| 4,171
|
Bilesh Ganguly
|
75,942,106
| 11,629,296
|
pandas/python : Get each distinct values of each column as columns and their counts as rows
|
<p>I have a data frame like this with below code,</p>
<pre><code>df=pd.DataFrame(columns=['col1', 'col2', 'col3'])
df.col1=['q1', 'q2', 'q2', 'q3', 'q4', 'q4']
df.col2=['b', 'a', 'a', 'c', 'b', 'b']
df.col3=['p', 'q', 'r', 'p', 'q', 'q']
df
col1 col2 col3
0 q1 b p
1 q2 a q
2 q2 a r
3 q3 c p
4 q4 b q
5 q4 b q
</code></pre>
<p>Now I want to col1 wise count of each col2 and col3 variables as rows and unique values of col2 and col3 as columns, so that the final dataframe would look like,</p>
<pre><code>col1 a b c p q r
q1 0 1 0 1 0 0
q2 2 0 0 0 1 1
q3 0 0 1 1 0 0
q4 0 2 0 0 2 0
</code></pre>
<p>I could do this using a for loop iterating through the dataframe and storing the results, but this is computationally expensive and not a right way to do it.</p>
<p>Looking for alternatives pythonic/pandas way to do it efficiently.</p>
|
<python><pandas><dataframe><pivot-table><one-hot-encoding>
|
2023-04-05 16:51:15
| 1
| 2,189
|
Kallol
|
75,941,954
| 417,896
|
Input shape for functional Tensorflow api
|
<p>What would be an example of properly shaped inputs for the following nn?</p>
<pre><code> inputA = Input(shape=(240, 1))
inputB = Input(shape=(240, 1))
layerA1 = LSTM(60, return_sequences=True)(inputA)
layerB1 = LSTM(60, return_sequences=True)(inputB)
layerA2 = LSTM(60, return_sequences=True)(layerA1)
layerB2 = LSTM(60, return_sequences=True)(layerB1)
layerA3 = LSTM(60, return_sequences=False)(layerA2)
layerB3 = LSTM(60, return_sequences=False)(layerB2)
x = Concatenate()([layerA3, layerB3])
output = Dense(5, activation='linear', name='dense')(x)
model = tf.keras.Model([inputA, inputB], output)
# What inputs into
model.fit(...)
</code></pre>
|
<python><tensorflow>
|
2023-04-05 16:32:53
| 1
| 17,480
|
BAR
|
75,941,872
| 1,056,563
|
How to run code coverage to completion with the report even if pytest is failing?
|
<p>We have some test cases that are known to fail: those are in our backlog to complete. The tests that fail are not consistent.</p>
<p>I have a separate branch that cleans this all up: but we need the coverage done before that other PR can be merged due to its complexity. We have maybe a hundred test <code>skip</code>'s already.</p>
<p>I was unable to find command line option for <code>coverage</code> to do this.</p>
<p>What has been tried:</p>
<p><code>python -m</code> . This runs the tests but does not generate coverage info.</p>
<p>Here is the <code>coverage --help</code>:</p>
<pre><code>$coverage --help
Coverage.py, version 7.2.2 with C extension
Measure, collect, and report on code coverage in Python programs.
usage: coverage <command> [options] [args]
Commands:
annotate Annotate source files with execution information.
combine Combine a number of data files.
debug Display information about the internals of coverage.py
erase Erase previously collected coverage data.
help Get help on using coverage.py.
html Create an HTML report.
json Create a JSON report of coverage results.
lcov Create an LCOV report of coverage results.
report Report coverage stats on modules.
run Run a Python program and measure code execution.
xml Create an XML report of coverage results.
</code></pre>
<p>What is the mechanism to force an output?</p>
|
<python><coverage.py>
|
2023-04-05 16:23:06
| 0
| 63,891
|
WestCoastProjects
|
75,941,832
| 15,528,750
|
Follow-up to "How do I execute a program or call a system command?"
|
<p>I have a related question to <a href="https://stackoverflow.com/questions/89228/how-do-i-execute-a-program-or-call-a-system-command">this one</a>. The command that I'd like to execute is this one:</p>
<pre class="lang-bash prettyprint-override"><code>program test.in > test.out
</code></pre>
<p>where <code>program</code> takes as input <code>test.in</code> and outputs <code>test.out</code>. In python, I do</p>
<pre><code>import subprocess
subprocess.Popen([program] + ['test.in > test.out'])
</code></pre>
<p>yet I get the error</p>
<pre><code>Cannot open file 'test.in > test.out' for reading.
</code></pre>
<p>I've also tried</p>
<pre><code>subprocess.Popen([program] + 'test.in > test.out'.split())
</code></pre>
<p>yet this results in the error</p>
<pre><code>Cannot open file `>` for reading.
</code></pre>
<p>How do I need to modify my script without using <code>shell=True</code>, which would pose a security threat? Thanks.</p>
|
<python><shell><terminal><subprocess><command>
|
2023-04-05 16:18:33
| 2
| 566
|
Imahn
|
75,941,748
| 13,827,753
|
How do I improve the speed of getting the average pixel color on sections of my screen
|
<p>I'm working on a project where I get the average rgb value of all the pixels in a section of the screen ex: <code>top_left</code> and <code>bottom_middle</code>. These values are then mapped to pixels on an led strip which acts as a backlight on my monitor.</p>
<p>My problem is that to get the average rgb value of each section it takes about .8 seconds. This makes the backlights look very laggy. Is there any way to quicken the process of getting the rgb values, the code is below.</p>
<pre class="lang-py prettyprint-override"><code>import serial, time, tkinter as tk, PIL.ImageGrab as ImageGrab
root = tk.Tk()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
root.destroy()
lastx = 23
class Ordinator:
"""get the average color of 8 boxes on the screen so that I can do less math on arduino"""
def __init__(self,sw,sh):
self.grab()
self.screenW = sw
self.screenH = sh
self.top_left = tuple(map(int, (0, 0, 0.33 * self.screenW, 0.33 * self.screenH)))
self.top_middle = tuple(map(int, (0.33 * self.screenW, 0, 0.66 * self.screenW, 0.33 * self.screenH)))
self.top_right = tuple(map(int, (0.66 * self.screenW, 0, self.screenW, 0.33 * self.screenH)))
self.middle_left = tuple(map(int, (0, 0.33 * self.screenH, 0.33 * self.screenW, 0.66 * self.screenH)))
self.middle_right = tuple(map(int, (0.66 * self.screenW, 0.33 * self.screenH, self.screenW, 0.66 * self.screenH)))
self.bottom_left = tuple(map(int, (0, 0.66 * self.screenH, 0.33 * self.screenW, self.screenH)))
self.bottom_middle = tuple(map(int, (0.33 * self.screenW, 0.66 * self.screenH, 0.66 * self.screenW, self.screenH)))
self.bottom_right = tuple(map(int, (0.66 * self.screenW, 0.66 * self.screenH, self.screenW, self.screenH)))
#turn get_average_color into a class method
def grab(self):
self.pixels = (ImageGrab.grab())
def get_average_color(self,box):
"""Uses PIL to get the average color of a box on the screen"""
#get screenshot with all windows that are pulled up not just background
pixels = (self.pixels.crop(box)).getdata()
num_pixels = len(pixels)
r = g = b = 0
for pixel in pixels:
r += pixel[0]
g += pixel[1]
b += pixel[2]
avg_r, avg_g, avg_b = [x // num_pixels for x in (r, g, b)]
#if var doesnt have 3 digits add 0s in front
if len(str(avg_r)) < 3:
avg_r = str(avg_r).zfill(3)
if len(str(avg_g)) < 3:
avg_g = str(avg_g).zfill(3)
if len(str(avg_b)) < 3:
avg_b = str(avg_b).zfill(3)
#return as rgb ex: 255010255
return str(avg_r) + str(avg_g) + str(avg_b)
#turn get_all_colors into a class method
def get_all_colors(self):
"""Returns a string of all the colors in the order of the boxes"""
self.grab()
return (self.get_average_color(self.top_right)+self.get_average_color(self.top_middle) + self.get_average_color(self.top_left) + self.get_average_color(self.middle_left) +self.get_average_color(self.bottom_left) + self.get_average_color(self.bottom_middle) + self.get_average_color(self.bottom_right) + self.get_average_color(self.middle_right))
#example output 255 ffffff|ffffff|ffffff|ffffff|ffffff|ffffff|ffffff|ffffff
#or 255255255255255255255255255255255255255255255255255255255255255255255255
Ord = Ordinator(screen_width,screen_height)
#ser = serial.Serial('/dev/tty.usbmodem14101', 9600)
while True:
#time how fast the loop is
start = time.time()
x =Ord.get_all_colors()
if x != lastx:
#ser.write(x.encode())
print(x)
lastx = x
#print end time in seconds
print("End:" + str(time.time()- start))
time.sleep(0.1)
</code></pre>
<p>What I've tried so far:
Instead of taking 8 screenshots I have 1 screenshot of the screen and I crop from there.</p>
|
<python><performance><python-imaging-library><led>
|
2023-04-05 16:09:09
| 1
| 478
|
Seaver Olson
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.