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,375,058
| 12,436,050
|
Replace substring with multiple words in python3
|
<p>I am trying to replace a word in a string with multilple words and produce all the strings as an output.</p>
<p>For example 'disease' in 'lysosome storage disease' should be replaced by 'disease' , 'diseases', 'disorder', 'disorders','syndrome','syndromes' and produce following output.</p>
<pre><code>lysosome storage disease
lysosome storage diseases
lysosome storage disorder
lysosome storage disorders
lysosome storage syndrome
lysosome storage syndromes
</code></pre>
<p>I am trying following lines of code but, in the end I am getting only the last string.</p>
<pre><code>def multiple_replace(string, rep_dict):
pattern = re.compile("|".join([re.escape(k) for k in sorted(rep_dict,key=len,reverse=True)]), flags=re.DOTALL)
return pattern.sub(lambda x: rep_dict[x.group(0)], string)
multiple_replace("lysosome storage disease", {'disease':'disease', 'disease':'diseases', 'disease':'disorder', 'disease':'disorders','disease':'syndrome','disease':'syndromes'})
</code></pre>
|
<python><python-3.x><replace>
|
2023-02-07 14:51:52
| 2
| 1,495
|
rshar
|
75,375,036
| 11,710,304
|
What is the alternative for iterrows in polars python?
|
<p>I want to detect rows with null values when they are mandatory. The column <code>mandatory</code> gives information about this. If the value <code>"M"</code> occurs, the row is mandatory. If this is the case, this row should be checked for null values. If there is at least one null value, this row should be reported. First I tried it with Python and pandas. Finally I wanted to try it with Polars and failed because of iterrows. Therefore I have the question how can I translate this code into polars?</p>
<pre><code>from typing import List
import pandas as pd
def detect_infringements(self, df):
report = []
df = df[df["mandatory"] == "M"]
for index, row in df.iterrows():
if row.isnull().sum() > 0:
report.append({"Index": index, "Warning": "Infringement detected"})
return report
</code></pre>
<p>Here is the polars df:</p>
<pre><code>import polars as pl
df = pl.DataFrame({
'ID': ["1", "2", "3", "4", "5"],
'Entity': ['Entity 1', 'Entity 2', 'Entity 3', 'Entity 4', 'Entity 5'],
'Table': ['Table 1', 'Table 2', 'Table 3', 'Table 4', None],
'Local': ['Local 1', 'Local 2', None, 'Local 4', 'Local 5'],
'Global': ['Global 1', 'Global 2', 'Global 3', None, 'Global 5'],
'mandatory': ['M', 'M', 'M', 'CM', 'M']
})
</code></pre>
|
<python><python-polars>
|
2023-02-07 14:49:57
| 1
| 437
|
Horseman
|
75,375,013
| 15,913,281
|
Calculate Mean By Two Columns in Dataframe
|
<p>Given the df extract below, how can I calculate the mean Prob per SelectionId per MarketId?</p>
<p>I thought this would work but it doesn't:</p>
<pre><code>df.groupby(['MarketId', 'SelectionId', ], as_index=False)['Prob'].mean()
</code></pre>
<p>Example df:-</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>Time</th>
<th>MarketId</th>
<th>SelectionId</th>
<th>Prob</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>06/01/2016 19:58:01</td>
<td>1.12211769</td>
<td>56343</td>
<td>3.3</td>
</tr>
<tr>
<td>1</td>
<td>06/01/2016 19:58:01</td>
<td>1.12211769</td>
<td>47999</td>
<td>2.34</td>
</tr>
<tr>
<td>2</td>
<td>06/01/2016 19:58:01</td>
<td>1.12211769</td>
<td>58805</td>
<td>3.8</td>
</tr>
<tr>
<td>3</td>
<td>06/01/2016 19:59:01</td>
<td>1.12211769</td>
<td>56343</td>
<td>3.2</td>
</tr>
<tr>
<td>4</td>
<td>06/01/2016 19:59:01</td>
<td>1.12211769</td>
<td>47999</td>
<td>2.3</td>
</tr>
<tr>
<td>5</td>
<td>06/01/2016 19:59:01</td>
<td>1.12211769</td>
<td>58805</td>
<td>3.8</td>
</tr>
<tr>
<td>6</td>
<td>06/01/2016 20:00:01</td>
<td>1.12211769</td>
<td>56343</td>
<td>3.2</td>
</tr>
<tr>
<td>7</td>
<td>06/01/2016 20:00:01</td>
<td>1.12211769</td>
<td>47999</td>
<td>2.34</td>
</tr>
<tr>
<td>8</td>
<td>06/01/2016 20:00:01</td>
<td>1.12211769</td>
<td>58805</td>
<td>3.8</td>
</tr>
<tr>
<td>9</td>
<td>15/06/2016 18:59:43</td>
<td>1.122271208</td>
<td>24</td>
<td>1.25</td>
</tr>
<tr>
<td>10</td>
<td>15/06/2016 18:59:43</td>
<td>1.122271208</td>
<td>15285</td>
<td>19</td>
</tr>
<tr>
<td>11</td>
<td>15/06/2016 18:59:43</td>
<td>1.122271208</td>
<td>58805</td>
<td>6.6</td>
</tr>
<tr>
<td>12</td>
<td>15/06/2016 19:01:43</td>
<td>1.122271208</td>
<td>24</td>
<td>1.26</td>
</tr>
<tr>
<td>13</td>
<td>15/06/2016 19:01:43</td>
<td>1.122271208</td>
<td>15285</td>
<td>18</td>
</tr>
<tr>
<td>14</td>
<td>15/06/2016 19:01:43</td>
<td>1.122271208</td>
<td>58805</td>
<td>6.8</td>
</tr>
<tr>
<td>15</td>
<td>15/06/2016 19:02:43</td>
<td>1.122271208</td>
<td>24</td>
<td>1.27</td>
</tr>
<tr>
<td>16</td>
<td>15/06/2016 19:02:43</td>
<td>1.122271208</td>
<td>15285</td>
<td>19</td>
</tr>
<tr>
<td>17</td>
<td>15/06/2016 19:02:43</td>
<td>1.122271208</td>
<td>58805</td>
<td>6.6</td>
</tr>
</tbody>
</table>
</div><h2>Desired df:</h2>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>MarketId</th>
<th>SelectionId</th>
<th>Prob</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>1.12211769</td>
<td>56343</td>
<td>3.233</td>
</tr>
<tr>
<td>1</td>
<td>1.12211769</td>
<td>47999</td>
<td>2.326</td>
</tr>
<tr>
<td>2</td>
<td>1.12211769</td>
<td>58805</td>
<td>3.8</td>
</tr>
<tr>
<td>3</td>
<td>1.122271208</td>
<td>24</td>
<td>1.26</td>
</tr>
<tr>
<td>4</td>
<td>1.122271208</td>
<td>15285</td>
<td>18.667</td>
</tr>
<tr>
<td>5</td>
<td>1.122271208</td>
<td>58805</td>
<td>6.667</td>
</tr>
</tbody>
</table>
</div>
|
<python><pandas>
|
2023-02-07 14:48:01
| 1
| 471
|
Robsmith
|
75,374,936
| 14,606,987
|
Why are elements missing when calling `validation_step` in Pytorch Lightning?
|
<p>I have a dataset with 20 rows and I set</p>
<pre class="lang-py prettyprint-override"><code>eval_batch_size=10
num_train_epochs=1
</code></pre>
<p>Thats my validation_step</p>
<pre class="lang-py prettyprint-override"><code>def validation_step(self, batch, batch_idx):
print(len(batch[elements]))
</code></pre>
<p>What I expect to see is that the number of elements in one batch is always 10 because a dataset of size 20 in two batches is twice 10 but in the last print I get 8 for the length of the elements. Why are two elements missing?</p>
<p><strong>EDIT</strong></p>
<p>When tokenizing my dataset two rows of the dataset are going lost, this is why.</p>
|
<python><pytorch-lightning>
|
2023-02-07 14:43:01
| 0
| 868
|
yemy
|
75,374,930
| 11,192,771
|
Most resource-efficient way to calculate distance between coordinates
|
<p>I am trying to find all observations that are located within 100 meters of a set of coordinates.</p>
<p>I have two dataframes, Dataframe1 has 400 rows with coordinates, and for each row, I need to find all the observations from Dataframe2 that are located within 100 meters of that location, and count them. Ideally,</p>
<p>Both the dataframes are formatted like this:</p>
<pre><code>| Y | X | observations_within100m |
|:----:|:----:|:-------------------------:|
|100 |100 | 22 |
|110 |105 | 25 |
|110 |102 | 11 |
</code></pre>
<p>I am looking for the most efficient way to do this computation, as dataframe2 has over a 200 000 dwelling locations. I know it can be done with applying a distance function with something as a for loop but I was wondering what the best method is here.</p>
|
<python><pandas>
|
2023-02-07 14:42:37
| 2
| 425
|
TvCasteren
|
75,374,768
| 11,197,301
|
How to select in a numpy array all paris with a defined index difference?
|
<p>Let's say that I have this numpy array:</p>
<pre><code>import numpy as np
np.random.seed(0)
data = np.random.normal(size=(5,5))
</code></pre>
<p>which result in:</p>
<p><a href="https://i.sstatic.net/CdCHF.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/CdCHF.png" alt="enter image description here" /></a></p>
<p>I would like to select all pairs with a specific indexes distance along each row.
For example if I choose a index distance 4 along each row I expect to have:</p>
<pre><code>res[0,0]=1.76,res[0,1]=2.24
res[1,0]=0.40,res[1,1]=1.86
res[2,0]=-0.97,res[2,1]=-0.10
res[3,0]=0.95,res[3,1]=0.41
...
....
</code></pre>
<p>I now that I could that with a for cycle but I would like to have something smarter. I was thing to create two list of indexes and then to fill res but also in this I need a cycle.</p>
<p>Best</p>
|
<python><numpy><select><indexing>
|
2023-02-07 14:31:45
| 2
| 623
|
diedro
|
75,374,748
| 12,350,966
|
remove semicolon from end of string
|
<p>I want to remove semicolon from the end of a string in python:</p>
<pre><code>mystring = 'NM_000106.5:c.985+39G>A;c.886C>T;c.1457G>C;'
</code></pre>
<p>I tried something like this:</p>
<pre><code>clean_end = mystring[:-1] if mystring.endswith(';') else mystring
</code></pre>
<p>However in this case, <code>mystring.endswith(';')</code> returns <code>False</code>.</p>
<p>Why is this?</p>
|
<python>
|
2023-02-07 14:30:41
| 2
| 740
|
curious
|
75,374,667
| 1,007,566
|
Type hints when returning dynamically mixed generic types in Python
|
<p>I am writing a function that takes a tuple with an undetermined number of objects of the same class, but with varying generic types. The return values of this function will be a same-sized tuple with items of the specified types.</p>
<p>How can I rewrite the <code>process</code> function below to make this work? This current attempt requires that all objects use the same type. So it would work if <code>a</code>, <code>b</code>, and <code>c</code> were all specified as <code>int</code>. But in my use-case, types should be mixable and tuple size should be dynamic.</p>
<pre class="lang-py prettyprint-override"><code>from typing import Generic, Tuple, TypeVar
T = TypeVar("T")
class Command(Generic[T]):
def __init__(self, value: T):
self.value = value
def process(commands: Tuple[Command[T], ...]) -> Tuple[T, ...]:
return tuple([cmd.value for cmd in commands])
a = Command[int](1)
b = Command[str]("foobar")
c = Command[int](2)
a_, b_, c_ = process((a, b, c))
# How to make my language server understand that a_, b_, c_ are int, str, int?
</code></pre>
|
<python><generics><types>
|
2023-02-07 14:22:30
| 0
| 685
|
Wietse de Vries
|
75,374,582
| 10,270,590
|
How to use a python list as global variable pandas data frame with in @task.external_python?
|
<h2>Goal</h2>
<ul>
<li>I use the Docker 2.4.1 version of Airflow</li>
<li>I use my external python virtual environment for each task</li>
<li>I have a pandas data frame that I want to pass on from task to task.</li>
<li>I my previosue question <a href="https://stackoverflow.com/questions/75361423/how-to-use-a-python-list-as-global-variable-with-in-task-external-python">How to use a python list as global variable python list with in @task.external_python?</a> this was doen succesfully via a python list but when I switch to a pandas data frame the process crashes</li>
<li>The first task succesfully runs</li>
</ul>
<h2>CODE</h2>
<pre><code>from airflow.decorators import dag, task
from pendulum import datetime
from datetime import timedelta
my_default_args = {
'owner': 'Anonymus',
# 'email': ['random@random.com'],
# 'email_on_failure': True,
# 'email_on_retry': False, #only allow if it was allowed in the scheduler
# 'retries': 1, #only allow if it was allowed in the scheduler
# 'retry_delay': timedelta(minutes=1),
# 'depends_on_past': False,
}
@dag(
dag_id='test_global_variable',
schedule='12 11 * * *',
start_date=datetime(2023,2,1,tz="UTC"),
catchup=False,
default_args=my_default_args,
tags=['sample_tag', 'sample_tag2'],
)
def write_var():
@task.external_python(task_id="task_1", python='/opt/airflow/v1/bin/python3')
def add_to_list(my_list):
print(my_list)
import pandas as pd
df = pd.DataFrame(my_list)
return df
@task.external_python(task_id="task_2", python='/opt/airflow/v1/bin/python3')
def add_to_list_2(df):
print(df)
df = df.append([19])
return df
add_to_list_2(add_to_list([23, 5, 8]))
write_var()
</code></pre>
<h2>ERROR LOG of 2nd task</h2>
<pre><code>*** Reading local file: /opt/airflow/logs/dag_id=test_global_variable/run_id=manual__2023-02-07T14:06:17.432734+00:00/task_id=task_2/attempt=1.log
[2023-02-07, 14:06:22 GMT] {taskinstance.py:1165} INFO - Dependencies all met for <TaskInstance: test_global_variable.task_2 manual__2023-02-07T14:06:17.432734+00:00 [queued]>
[2023-02-07, 14:06:22 GMT] {taskinstance.py:1165} INFO - Dependencies all met for <TaskInstance: test_global_variable.task_2 manual__2023-02-07T14:06:17.432734+00:00 [queued]>
[2023-02-07, 14:06:22 GMT] {taskinstance.py:1362} INFO -
--------------------------------------------------------------------------------
[2023-02-07, 14:06:22 GMT] {taskinstance.py:1363} INFO - Starting attempt 1 of 1
[2023-02-07, 14:06:22 GMT] {taskinstance.py:1364} INFO -
--------------------------------------------------------------------------------
[2023-02-07, 14:06:22 GMT] {taskinstance.py:1383} INFO - Executing <Task(_PythonExternalDecoratedOperator): task_2> on 2023-02-07 14:06:17.432734+00:00
[2023-02-07, 14:06:22 GMT] {standard_task_runner.py:54} INFO - Started process 324831 to run task
[2023-02-07, 14:06:22 GMT] {standard_task_runner.py:82} INFO - Running: ['airflow', 'tasks', 'run', 'test_global_variable', 'task_2', 'manual__2023-02-07T14:06:17.432734+00:00', '--job-id', '74080', '--raw', '--subdir', 'DAGS_FOLDER/test_global_variable.py', '--cfg-path', '/tmp/tmpbm8tkk1i']
[2023-02-07, 14:06:22 GMT] {standard_task_runner.py:83} INFO - Job 74080: Subtask task_2
[2023-02-07, 14:06:22 GMT] {dagbag.py:525} INFO - Filling up the DagBag from /opt/airflow/dags/test_global_variable.py
[2023-02-07, 14:06:22 GMT] {taskmixin.py:205} WARNING - Dependency <Task(_PythonExternalDecoratedOperator): task_1>, task_2 already registered for DAG: test_global_variable
[2023-02-07, 14:06:22 GMT] {taskmixin.py:205} WARNING - Dependency <Task(_PythonExternalDecoratedOperator): task_2>, task_1 already registered for DAG: test_global_variable
[2023-02-07, 14:06:22 GMT] {taskmixin.py:205} WARNING - Dependency <Task(_PythonExternalDecoratedOperator): task_1>, task_2 already registered for DAG: test_global_variable
[2023-02-07, 14:06:22 GMT] {taskmixin.py:205} WARNING - Dependency <Task(_PythonExternalDecoratedOperator): task_2>, task_1 already registered for DAG: test_global_variable
[2023-02-07, 14:06:22 GMT] {taskmixin.py:205} WARNING - Dependency <Task(_PythonExternalDecoratedOperator): task_1>, task_2 already registered for DAG: test_global_variable
[2023-02-07, 14:06:22 GMT] {taskmixin.py:205} WARNING - Dependency <Task(_PythonExternalDecoratedOperator): task_2>, task_1 already registered for DAG: test_global_variable
[2023-02-07, 14:06:22 GMT] {taskmixin.py:205} WARNING - Dependency <Task(_PythonExternalDecoratedOperator): task_1>, task_2 already registered for DAG: test_global_variable
[2023-02-07, 14:06:22 GMT] {taskmixin.py:205} WARNING - Dependency <Task(_PythonExternalDecoratedOperator): task_2>, task_1 already registered for DAG: test_global_variable
[2023-02-07, 14:06:22 GMT] {taskmixin.py:205} WARNING - Dependency <Task(_PythonExternalDecoratedOperator): task_1>, task_2 already registered for DAG: test_global_variable
[2023-02-07, 14:06:22 GMT] {taskmixin.py:205} WARNING - Dependency <Task(_PythonExternalDecoratedOperator): task_2>, task_1 already registered for DAG: test_global_variable
[2023-02-07, 14:06:22 GMT] {taskmixin.py:205} WARNING - Dependency <Task(_PythonExternalDecoratedOperator): task_1>, task_2 already registered for DAG: test_global_variable
[2023-02-07, 14:06:22 GMT] {taskmixin.py:205} WARNING - Dependency <Task(_PythonExternalDecoratedOperator): task_2>, task_1 already registered for DAG: test_global_variable
[2023-02-07, 14:06:22 GMT] {taskmixin.py:205} WARNING - Dependency <Task(_PythonExternalDecoratedOperator): task_1>, task_2 already registered for DAG: test_global_variable
[2023-02-07, 14:06:22 GMT] {taskmixin.py:205} WARNING - Dependency <Task(_PythonExternalDecoratedOperator): task_2>, task_1 already registered for DAG: test_global_variable
[2023-02-07, 14:06:22 GMT] {task_command.py:384} INFO - Running <TaskInstance: test_global_variable.task_2 manual__2023-02-07T14:06:17.432734+00:00 [running]> on host 4851b30aa5cf
[2023-02-07, 14:06:22 GMT] {taskinstance.py:1590} INFO - Exporting the following env vars:
AIRFLOW_CTX_DAG_OWNER=Anonymus
AIRFLOW_CTX_DAG_ID=test_global_variable
AIRFLOW_CTX_TASK_ID=task_2
AIRFLOW_CTX_EXECUTION_DATE=2023-02-07T14:06:17.432734+00:00
AIRFLOW_CTX_TRY_NUMBER=1
AIRFLOW_CTX_DAG_RUN_ID=manual__2023-02-07T14:06:17.432734+00:00
[2023-02-07, 14:06:23 GMT] {process_utils.py:179} INFO - Executing cmd: /opt/airflow/venv1/bin/python3 /tmp/tmddiox599m/script.py /tmp/tmddiox599m/script.in /tmp/tmddiox599m/script.out /tmp/tmddiox599m/string_args.txt
[2023-02-07, 14:06:23 GMT] {process_utils.py:183} INFO - Output:
[2023-02-07, 14:06:24 GMT] {process_utils.py:187} INFO - Traceback (most recent call last):
[2023-02-07, 14:06:24 GMT] {process_utils.py:187} INFO - File "/tmp/tmddiox599m/script.py", line 17, in <module>
[2023-02-07, 14:06:24 GMT] {process_utils.py:187} INFO - arg_dict = pickle.load(file)
[2023-02-07, 14:06:24 GMT] {process_utils.py:187} INFO - AttributeError: Can't get attribute '_unpickle_block' on <module 'pandas._libs.internals' from '/opt/airflow/venv1/lib/python3.8/site-packages/pandas/_libs/internals.cpython-38-x86_64-linux-gnu.so'>
[2023-02-07, 14:06:24 GMT] {taskinstance.py:1851} ERROR - Task failed with exception
Traceback (most recent call last):
File "/home/airflow/.local/lib/python3.8/site-packages/airflow/decorators/base.py", line 188, in execute
return_value = super().execute(context)
File "/home/airflow/.local/lib/python3.8/site-packages/airflow/operators/python.py", line 370, in execute
return super().execute(context=serializable_context)
File "/home/airflow/.local/lib/python3.8/site-packages/airflow/operators/python.py", line 175, in execute
return_value = self.execute_callable()
File "/home/airflow/.local/lib/python3.8/site-packages/airflow/operators/python.py", line 678, in execute_callable
return self._execute_python_callable_in_subprocess(python_path, tmp_path)
File "/home/airflow/.local/lib/python3.8/site-packages/airflow/operators/python.py", line 426, in _execute_python_callable_in_subprocess
execute_in_subprocess(
File "/home/airflow/.local/lib/python3.8/site-packages/airflow/utils/process_utils.py", line 168, in execute_in_subprocess
execute_in_subprocess_with_kwargs(cmd, cwd=cwd)
File "/home/airflow/.local/lib/python3.8/site-packages/airflow/utils/process_utils.py", line 191, in execute_in_subprocess_with_kwargs
raise subprocess.CalledProcessError(exit_code, cmd)
subprocess.CalledProcessError: Command '['/opt/airflow/venv1/bin/python3', '/tmp/tmddiox599m/script.py', '/tmp/tmddiox599m/script.in', '/tmp/tmddiox599m/script.out', '/tmp/tmddiox599m/string_args.txt']' returned non-zero exit status 1.
[2023-02-07, 14:06:24 GMT] {taskinstance.py:1401} INFO - Marking task as FAILED. dag_id=test_global_variable, task_id=task_2, execution_date=20230207T140617, start_date=20230207T140622, end_date=20230207T140624
[2023-02-07, 14:06:24 GMT] {standard_task_runner.py:102} ERROR - Failed to execute job 74080 for task task_2 (Command '['/opt/airflow/venv1/bin/python3', '/tmp/tmddiox599m/script.py', '/tmp/tmddiox599m/script.in', '/tmp/tmddiox599m/script.out', '/tmp/tmddiox599m/string_args.txt']' returned non-zero exit status 1.; 324831)
[2023-02-07, 14:06:24 GMT] {local_task_job.py:164} INFO - Task exited with return code 1
[2023-02-07, 14:06:24 GMT] {local_task_job.py:273} INFO - 0 downstream tasks scheduled from follow-on schedule check
</code></pre>
|
<python><python-3.x><pandas><airflow><directed-acyclic-graphs>
|
2023-02-07 14:15:41
| 1
| 3,146
|
sogu
|
75,374,370
| 32,854
|
FastAPI python app error on Azure App Service
|
<p>I have a python web application that is using FastAPI. It works locally, but when I deploy it to a free linux Azure App Service (using GitHub Actions) and try to load the site it says "Internal Server Error". When I pull up the application logs I see the following error message</p>
<pre><code>2023-02-06T23:44:30.765055894Z [2023-02-06 23:44:30 +0000] [90] [ERROR] Error handling request /
2023-02-06T23:44:30.765101490Z Traceback (most recent call last):
2023-02-06T23:44:30.765109589Z File "/opt/python/3.10.9/lib/python3.10/site-packages/gunicorn/workers/sync.py", line 136, in handle
2023-02-06T23:44:30.765116389Z self.handle_request(listener, req, client, addr)
2023-02-06T23:44:30.765122088Z File "/opt/python/3.10.9/lib/python3.10/site-packages/gunicorn/workers/sync.py", line 179, in handle_request
2023-02-06T23:44:30.765128688Z respiter = self.wsgi(environ, resp.start_response)
2023-02-06T23:44:30.765134688Z TypeError: FastAPI.__call__() missing 1 required positional argument: 'send'
</code></pre>
<p>Any suggestions on how to fix this issue?</p>
|
<python><azure-web-app-service><github-actions><fastapi>
|
2023-02-07 13:56:41
| 1
| 4,788
|
Austin
|
75,374,337
| 4,244,609
|
Pybullet: limit joint torque in POSITION_COONTROL mode
|
<p>I'm working with a robot in Pybullet in POSITION_COONTROL mode (torque control is not convinient in my specific case). I would like to limit torque scalar on each joint. How can I achieve it without switching to torque control mode?</p>
|
<python><simulator><robotics><pybullet>
|
2023-02-07 13:54:50
| 1
| 1,483
|
Ivan Sudos
|
75,374,140
| 7,932,273
|
How to send followup message in Slack App using slack_bolt?
|
<p>I am building a bot that will answer a question asked in a slack App.</p>
<p>I want to configure a followup question</p>
<p><em>Note: Yes and No are radio buttons</em></p>
<p>eg.</p>
<pre><code>User: What is the event date?
Bot: 22nd Feb, 2023
(after the answer bot will trigger followup question with radio buttons)
Bot: Does this answer your query?
- Yes
- No
</code></pre>
<p>Here's my code</p>
<pre><code>import asyncio
from slack_bolt.adapter.socket_mode.async_handler import AsyncSocketModeHandler
from slack_bolt.async_app import AsyncApp
from slack_sdk import WebClient
client = WebClient(token=SLACK_BOT_TOKEN)
app = AsyncApp(token=SLACK_BOT_TOKEN)
# This event will be executed when User sends the message
@app.message('')
async def in_message(say, message):
if 'event' in message['text']:
response = '22nd Feb, 2023'
block = []
await say(text=response, blocks=block)
</code></pre>
<p>I also tried appending the followup message in the response and update it on ACK but updating doesn't handle the formatting, it treats the message as plain text.</p>
|
<python><chatbot><slack><slack-api><slack-bolt>
|
2023-02-07 13:36:44
| 1
| 13,436
|
Sociopath
|
75,374,097
| 1,143,558
|
Django (v4) request.META['REMOTE_ADDR'] not working anymore?
|
<p>I had been using for years (Django 1.9 & Python 2.7) <code>request.META</code> dictionary and <code>['REMOTE_ADDR']</code> header to get client's IP address.
I have recently moved to Django 4.1.5 and found out that my code is not able anymore to get client's IP address, so I had to use:</p>
<pre><code>x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
</code></pre>
<p>which works fine.</p>
<p>I've tested my old code in development mode and tried to log <code>request.META.get('REMOTE_ADDR')</code>. The code will log IP only if the IP address is localhost (127.0.0.1). With any other IP address, <code>REMOTE_ADDR</code> header stays blank.</p>
<p>I'm just curious, could someone tell me why this is happening?</p>
|
<python><django>
|
2023-02-07 13:33:55
| 1
| 842
|
Ljubisa Livac
|
75,374,063
| 14,359,801
|
Regression : how to handle multiple multivariate timeseries?
|
<p>I am trying to develop a model using machine learning that reproduces a biological behavior. My goal is to do a regression of timeseries e.g from multiple input each time_step predict multiple output and <strong>not forcasting</strong>.</p>
<p>For this, I have :</p>
<ul>
<li>as input: N [640*30] (time_steps * features) time series (execution cycle)</li>
<li>in output: N [640*1000] time series (result of the exceution cycle)</li>
</ul>
<p>To feed my data to an ML/DL algorithm, I can either:</p>
<ul>
<li>Reshape my data into (3D data)</li>
</ul>
<p><code>[nb_instances, time_steps, features]</code></p>
<ul>
<li>Remove the dimension nb instances and concatenate my data into</li>
</ul>
<p><code>[nb_instances * time_steps, features]</code></p>
<p>With the 3D data, I have a hard time to introduce them in a classical ml algo (for example, sklearn models...). I know that I could use a DL algorithm but I would like to have/test a "low resource" solution first. I am not considering dimensionality reduction for constraint purposes.</p>
<p>Is there a way to feed 3D data to a classic ML algo from sklearn or another python library?</p>
<p>If I choose the second option (removing the nb_instances dimension), I will lose some information (like the execution cycle) but I will be able to use both ML and DL.</p>
<p>Which option is better? Is there another way to look at the problem?</p>
|
<python><machine-learning><time-series><regression><multivariate-time-series>
|
2023-02-07 13:29:14
| 1
| 308
|
Ketchup
|
75,373,935
| 7,660,819
|
faster nested for loops for all pair of rows in a numpy array
|
<p>I have a numpy array, which is basically phase of oscillations recorded for 256 channels sampled at 1000 Hz for an hour. As a result, I have got a numpy array size of <code>256 x 5000000</code>. I want to calculate <code>Phase locking value</code> for all pair of channels (rows). Phase locking value is a measure of how coupled the oscillations are. Here is a method that works, but is obviously time-consuming. I've 128Gb RAM available.</p>
<pre><code>x = np.array([]) # 256 x 5000000
Nchans = 256
op = np.empty([Nchans, Nchans])
op[:] = np.nan
for a in range(Nchans):
for b in range(Nchans):
op[a,b] = np.abs(np.nansum(np.exp(np.complex(0,1)*(x[a] - x[b]))))/x.shape[1]
</code></pre>
<p>Is there any way I can speed up this calculation?</p>
|
<python><numpy><for-loop><signal-processing>
|
2023-02-07 13:18:38
| 1
| 305
|
deathracer
|
75,373,907
| 4,509,378
|
Retrieve data from multiple different Azure Tables asynchronously with Azure Tables client library
|
<p>Is it possible with the <a href="https://learn.microsoft.com/en-us/python/api/overview/azure/data-tables-readme?view=azure-python" rel="nofollow noreferrer">Azure Tables client library for Python</a> to retrieve data from multiple tables asynchronously? Let's say I have table A and B in different storage accounts, is it possible to retrieve data from both tabels simultaneously levering the <code>asyncio</code> module?</p>
<p>I cannot find any documentation specifying whether this is possible or how to implement this. I can think of building two async functions that can retrieve data from the tables and calling them via <code>asyncio.gather()</code>. Would this work or can the actual outbound call to the Azure endpoint not be done asynchronously?</p>
<p>I see that there exists a
<a href="https://azuresdkdocs.blob.core.windows.net/$web/python/azure-data-tables/12.0.0b6/azure.data.tables.aio.html" rel="nofollow noreferrer">Azure Data Tables aio</a> module which might be leveraged for this purpose?</p>
|
<python><azure><asynchronous><python-asyncio><azure-table-storage>
|
2023-02-07 13:15:59
| 1
| 749
|
Peter Lawrence
|
75,373,444
| 7,376,511
|
Mypy: using TypedDict as both kwargs for __init__ and as annotations for the class itself
|
<p>I am trying to have a class with dynamic properties that are pre-written inside a TypedDict, that is then passed as kwargs. Perhaps this is impossible to properly type with mypy, however I was thinking that I might be following the wrong approach.
This is my attempt so far:</p>
<pre><code>from typing import NotRequired, TypedDict, Unpack
class KwargsDict(TypedDict):
integer: int
string: NotRequired[str]
class DynamicDataClass:
def __init__(self, **kwargs: Unpack[KwargsDict]):
for key, value in kwargs.items():
setattr(self, key, value)
klass1 = DynamicDataClass(integer=1, string="2")
klass1.integer
klass2.string
klass2 = DynamicDataClass(integer=1)
klass2.integer
klass2.string
</code></pre>
<p>In the above example, Mypy returns <code>"DynamicDataClass" has no attribute "integer"</code> and so forth for all the dynamic properties of the DynamicDataClass instances.</p>
<p>Is there some better and compliant way to tell mypy that DynamicDataClass inherits annotations from KwargsDict, and all the attributes typed in KwargsDict are also present in DynamicDataClass?</p>
<p>I was thinking that perhaps Generics could help, but I have no idea how to assign a generic typeddict to the class's annotations.</p>
|
<python><python-typing><mypy>
|
2023-02-07 12:34:19
| 0
| 797
|
Some Guy
|
75,373,381
| 11,705,021
|
How I can compare two folders with multi-volume .7Z archive files, and get the output files/folders where the difference is more than 1GB
|
<p>I have 2 paths where each one them has multi-volume .7Z archive files.</p>
<p>Path A contains 4 files: <code>example1.7z.001, example1.7z.002, example1.7z.003, example1.7z.004</code> (Total size of all is 15 GB). Once you extract you get one 7z file of 20GB, and once your extract that one, you get folder of 40 GB. Inside there is a folder called <code>TEST1</code> which takes 5 GB.</p>
<p>Path B contains 5 files: <code>example2.7z.001, example2.7z.002, example2.7z.003, example2.7z.004, example2.7z.005</code> (Total size of all is 20 GB). Once you extract you get one 7z file of 22GB, and once your extract that one, you get folder of 50 GB. Now, the folder called <code>TEST1</code> increased to 7 GB, and there is also new folder calls <code>TEST2</code> which takes 1.2 GB.</p>
<p>I want to write python script which get these 2 paths as input, and as output prints me the existing and new files/folders which increase (in case of existing) or take (in case of new) more than 1 GB. In my example it should return <code>TEST1</code> and <code>TEST2</code>.</p>
<p>From short research, I got these ideas:</p>
<p>Using magic:</p>
<pre><code>import magic
def compare_7zip_content(file1, file2):
with open(file1, 'rb') as f1, open(file2, 'rb') as f2:
m1 = magic.Magic(mime=True)
m2 = magic.Magic(mime=True)
file1_content = f1.read()
file2_content = f2.read()
file1_type = m1.from_buffer(file1_content)
file2_type = m2.from_buffer(file2_content)
if file1_type == 'application/x-7z-compressed' and file2_type == 'application/x-7z-compressed':
if file1_content == file2_content:
return True
else:
return False
else:
raise ValueError('One or both of the files are not 7zip format')
</code></pre>
<p>Using py7zr</p>
<pre><code>import py7zr
import os
folder1 = '/path/to/folder1'
folder2 = '/path/to/folder2'
for filename in os.listdir(folder1):
if filename.endswith('.7z'):
file1 = os.path.join(folder1, filename)
file2 = os.path.join(folder2, filename)
with py7zr.SevenZipFile(file1, mode='r') as archive1, \
py7zr.SevenZipFile(file2, mode='r') as archive2:
archive1_files = archive1.getnames()
archive2_files = archive2.getnames()
for archive1_file, archive2_file in zip(archive1_files, archive2_files):
size_diff = abs(archive1.getmember(archive1_file).file_size -
archive2.getmember(archive2_file).file_size)
if size_diff >= 1000000000: # 1 GB in bytes
print(f"{filename}: {size_diff / 1000000000} GB")
</code></pre>
<p>Another option is use directly the 7z CLI</p>
<p>Can you recommend on which one I should use (or other idea)?</p>
|
<python><python-3.x><7zip><python-magic><py7zr>
|
2023-02-07 12:29:11
| 0
| 1,428
|
arielma
|
75,373,325
| 6,268,900
|
Reduce the Loop processing time in panda
|
<p>Concept : Count number of transition between two time and add the count as column in data frame. The Start time and End is first two Column in the data frame</p>
<p>Sample date</p>
<pre><code> Time_Completed Time_of_Fetch Base Number of event
03-06-2022 14:56 03-06-2022 14:14 Q112 12
03-06-2022 14:54 03-06-2022 14:14 Q112 11
03-06-2022 14:51 03-06-2022 14:18 Q112 9
03-06-2022 14:52 03-06-2022 14:21 Q112 8
03-06-2022 15:07 03-06-2022 14:25 Q112 8
03-06-2022 14:54 03-06-2022 14:25 Q112 7
03-06-2022 14:50 03-06-2022 14:25 Q112 5
03-06-2022 15:11 03-06-2022 14:27 Q112 5
03-06-2022 15:17 03-06-2022 14:29 Q112 4
03-06-2022 15:19 03-06-2022 14:47 Q112 3
03-06-2022 15:18 03-06-2022 14:49 Q112 2
03-06-2022 15:21 03-06-2022 14:54 Q112 1
03-06-2022 15:20 03-06-2022 14:58 Q106 2
03-06-2022 15:23 03-06-2022 14:59 Q106 1
</code></pre>
<p>Below is the code I am using to get the <code>Number of Count</code> column</p>
<pre><code>result = []
for i in range(0, len(df)):
result.append(df[(df['Time_of_Fetch'] >= df.iloc[i]['Time_of_Fetch']) & (df['Time_of_Fetch'] < df.iloc[i]['Time_Completed']) & (df['Base'] == df.iloc[i]['Base'])].count()['Base'])
df['Check_value'] = result
</code></pre>
<p>However this method is taking some much time to complete the calculation when processing large set of data</p>
<p>I have tried using <code>apply()</code> and <code>lambda()</code> to reduce the run time, still not able to reduce the runtime</p>
<p>below is the code that i have tired</p>
<pre><code>df_108.assign = df_108.apply((lambda row :df_108[(df_108['Time_of_Fetch'] >= df_108['Time_of_Fetch'])
& (df_108['Time_of_Fetch'] < df_108['Time_Completed'])& (df_108['Base'] == df_108['Base'])].count()['Base']),axis = 1)
</code></pre>
<p>How this can be re-written to reduce the runtime</p>
|
<python><pandas><dataframe><lambda><apply>
|
2023-02-07 12:24:55
| 1
| 354
|
Praveen DA
|
75,373,164
| 75,103
|
Is there something like python setup.py --version for pyproject.toml?
|
<p>With a simple <code>setup.py</code> file:</p>
<pre><code>from setuptools import setup
setup(
name='foo',
version='1.2.3',
)
</code></pre>
<p>I can do</p>
<pre><code>$> python setup.py --version
1.2.3
</code></pre>
<p>without installing the package.</p>
<p>Is there similar functionality for the equivalent <code>pyproject.toml</code> file:</p>
<pre><code>[project]
name = "foo"
version = "1.2.3"
</code></pre>
|
<python><pyproject.toml>
|
2023-02-07 12:10:42
| 1
| 27,572
|
thebjorn
|
75,373,139
| 14,606,987
|
Why is Pytorch Lightning `validation_step` executed more oftener than defined in `val_check_interval`?
|
<p>I have a dataset with 20 rows and want to have four times a <a href="https://pytorch-lightning.readthedocs.io/en/stable/common/trainer.html#:%7E:text=trainer%20%3D%20trainer(val_check_interval%3D0.25)" rel="nofollow noreferrer">Pytorch Lightning</a> <code>validation_step</code> called on this dataset. I am setting my</p>
<pre><code>`val_check_interval=0.25`,
`eval_batch_size=4` and
`num_train_epochs=1`
</code></pre>
<p>. Thats my validation_step:</p>
<pre class="lang-py prettyprint-override"><code>def validation_step(self, batch, batch_idx):
print("+"* 30)
</code></pre>
<p>What I expect is to see the <code>print</code> command four times because of the <code>val_check_interval</code> instead the print appears seven times. Why is this the case?</p>
|
<python><pytorch-lightning>
|
2023-02-07 12:09:00
| 1
| 868
|
yemy
|
75,373,084
| 14,790,056
|
groupby and drop groups if the sender is not in the list of receiver list in pandas
|
<p>I have exchange data. A transaction initiator sends USD and will receive Euro in return. I want to make sure that each transaction contains the correct information about the initiator. The way to ensure that is that the one who is sending money to the exchange always appear in <code>to</code> as well within the same transaction.</p>
<pre><code>transaction from to currency
1 A exchange USD
1 exchange A Euro
1 B C Euro
2 C exchange USD
2 B D Euro
2 A G Euro
3 F exchange USD
3 D A Euro
3 B F Euro
4 R exchange USD
4 A D Euro
4 B Q Euro
</code></pre>
<p>Desired df</p>
<pre><code>transaction from to currency
1 A exchange USD
1 exchange A Euro
3 F exchange USD
3 B F Euro
</code></pre>
<p>Here, for each transaction, the initiator is <code>A</code>, <code>C</code>, <code>F</code>, and <code>R</code>. But for <code>C</code>, <code>R</code>, there is no record of incoming transactions. So I want to exclude these transactions.</p>
|
<python><pandas><dataframe>
|
2023-02-07 12:03:24
| 2
| 654
|
Olive
|
75,373,069
| 9,861,647
|
Formatting issues with Python amd GSpread
|
<p>I have this panda Data Frame (DF1).</p>
<pre><code>DF1= DF1.groupby(['Name', 'Type', 'Metric'])
DF1= DF1.first()
</code></pre>
<p>If I output to df1.to_excel("output.xlsx"). The format is correct see bellow :</p>
<p><a href="https://i.sstatic.net/8xhh8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8xhh8.png" alt="screenshot 1" /></a></p>
<p>But when I upload to my google sheets using python and GSpread</p>
<pre><code>from gspread_formatting import *
worksheet5.clear()
set_with_dataframe(worksheet=worksheet1, dataframe=DF1, row=1, include_index=True,
include_column_header=True, resize=True)
</code></pre>
<p>That's the output</p>
<p><a href="https://i.sstatic.net/HQiDU.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/HQiDU.png" alt="screenshot 2" /></a></p>
<p>How can I keep the same format in my google sheets using gspread_formatting like in screenshot 1?</p>
|
<python><pandas><google-sheets><google-sheets-api><gspread>
|
2023-02-07 12:01:34
| 1
| 1,065
|
Simon GIS
|
75,373,002
| 163,573
|
Mocking pyodbc without unixODBC installed
|
<p>My python app uses pyodbc to connect to the database. I would like to mock the database in my tests.</p>
<p>When running tests on the build server <code>import pyodbc</code> throws <code>ImportError: libodbc.so.2: cannot open shared object file: No such file or directory</code> because unixODBC is not installed.</p>
<p>Is there a way to mock the pyodbc import before importing the main file into the test or do we have to install unixODBC in the build server (works but feels unnecessary)?</p>
<p>main.py</p>
<pre><code>import pyodbc
def function_to_test():
...
</code></pre>
<p>test_main.py</p>
<pre><code>from main import function_to_test # this throws
...
</code></pre>
|
<python><mocking><pyodbc><python-unittest>
|
2023-02-07 11:55:13
| 1
| 6,869
|
rickythefox
|
75,372,901
| 13,566,716
|
how to get unique pairs of items present in the same id with SQL
|
<p><strong>The initial table is like below:</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>session_id</th>
<th>item</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>t-shirt</td>
</tr>
<tr>
<td>1</td>
<td>trousers</td>
</tr>
<tr>
<td>1</td>
<td>hat</td>
</tr>
<tr>
<td>2</td>
<td>belt</td>
</tr>
<tr>
<td>2</td>
<td>shoes</td>
</tr>
</tbody>
</table>
</div>
<p>I want to generate a table with all the unique pairs in the same session_id (I want to be able to do this with SQL, or more preferably SQLAlchemy Python).</p>
<p><strong>Below is the example table I want to generate from the example table above:</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>session_id</th>
<th>item_a</th>
<th>item_b</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>t-shirt</td>
<td>trousers</td>
</tr>
<tr>
<td>1</td>
<td>t-shirt</td>
<td>hat</td>
</tr>
<tr>
<td>1</td>
<td>trousers</td>
<td>hat</td>
</tr>
<tr>
<td>2</td>
<td>belt</td>
<td>shoes</td>
</tr>
</tbody>
</table>
</div>
|
<python><sql><python-3.x><sqlalchemy>
|
2023-02-07 11:45:04
| 1
| 369
|
3awny
|
75,372,835
| 3,249,000
|
Poetry add dependency that uses cython
|
<p>I have a project which needs to depend on the latest commit of <a href="https://github.com/pysam-developers/pysam" rel="nofollow noreferrer">pysam</a>, because I'm working in python 3.11.</p>
<p>This means building the package from source, so I do the following:</p>
<p><code>poetry add git+https://github.com/pysam-developers/pysam</code></p>
<p>However, I get an error which I think boils down to poetry not including cython in the build environment:</p>
<pre><code>Unable to determine package info for path: /Users/agreen/Library/Caches/pypoetry/virtualenvs/rnacentral-pipeline-GU-1IkEM-py3.11/src/pysam
Fallback egg_info generation failed.
Command ['/var/folders/sg/3858brmd79z4rz781g0q__940000gp/T/tmpw8auvhsm/.venv/bin/python', 'setup.py', 'egg_info'] errored with the following return code 1, and output:
# pysam: no cython available - using pre-compiled C
Traceback (most recent call last):
File "/Users/agreen/Library/Caches/pypoetry/virtualenvs/rnacentral-pipeline-GU-1IkEM-py3.11/src/pysam/setup.py", line 345, in <module>
raise ValueError(
ValueError: no cython installed, but can not find pysam/libchtslib.c.Make sure that cython is installed when building from the repository
</code></pre>
<p>Cython is definitely installed, its in the <a href="https://gist.github.com/afg1/f77cc9e08f69a417a5dba49fc636b660" rel="nofollow noreferrer">pyproject.toml</a>, and I can call it from the poetry shell, or import it in a python started in the poetry virtualenv. However, If I use the python from the command poetry is running, then indeed cython is not available.</p>
<p>I think I'm missing some configuration of the build, or some extra option to <code>poetry add</code>. The documentation isn't particularly clear about this use of cython - as far as I can tell it's all about using cython in the package I'm writing, which is not quite what I want.</p>
|
<python><cython><python-packaging><python-poetry>
|
2023-02-07 11:38:57
| 1
| 2,182
|
Theolodus
|
75,372,764
| 6,871,867
|
Automate login to a website through Gmail using python selenium
|
<p>I am trying to automate login to <a href="https://secure.indeed.com/auth?hl=en_US&co=US&continue=https%3A%2F%2Fwww.indeed.com%2F&tmpl=desktop&service=my&from=gnav-util-homepage&jsContinue=https%3A%2F%2Fwww.indeed.com%2F&empContinue=https%3A%2F%2Faccount.indeed.com%2Fmyaccess&_ga=2.36143904.1242603427.1673200412-1007460264.1673200412" rel="nofollow noreferrer">Indeed</a> using login option through gmail. However, I am getting this error:</p>
<blockquote>
<p>Couldn't sign you in. This browser or app may not be secure</p>
</blockquote>
<p><a href="https://i.sstatic.net/rjyMI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/rjyMI.png" alt="enter image description here" /></a></p>
<p><a href="https://i.sstatic.net/eSeFe.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/eSeFe.png" alt="enter image description here" /></a></p>
<p>Here is the codebase using <strong>Firefox/Chrome driver</strong></p>
<pre><code>login_url='https://secure.indeed.com/auth?hl=en_US&co=US&continue=https%3A%2F%2Fwww.indeed.com%2F&tmpl=desktop&service=my&from=gnav-util-homepage&jsContinue=https%3A%2F%2Fwww.indeed.com%2F&empContinue=https%3A%2F%2Faccount.indeed.com%2Fmyaccess&_ga=2.36143904.1242603427.1673200412-1007460264.1673200412'
driver = webdriver.Firefox(options=options, capabilities=caps, service=serv)
# driver = uc.Chrome()
# driver.delete_all_cookies()
driver.get(login_url)
time.sleep(4)
window_before = driver.window_handles[0]
google = driver.find_element(By.XPATH,'//*[@id="login-google-button"]')
google.click()
time.sleep(4)
window_after = driver.window_handles[1]
driver.switch_to.window(window_after)
emailBox = driver.find_element(By.XPATH,"//input[@type='email']")
emailBox.send_keys('email@gmail.com')
emailBox.send_keys(Keys.ENTER)
time.sleep(7)
driver.get_screenshot_as_file("screenshot.png")
# passwordBox = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH,"//input[@type='password']")))
passwordBox = driver.find_element(By.XPATH,"//input[@type='password']")
passwordBox.send_keys('password')
passwordBox.send_keys(Keys.ENTER)
time.sleep(7)
driver.switch_to.window(window_before)
</code></pre>
<p>I found <code>undetected_chromedriver</code> solves the issue, however on using <code>undetected_chromedriver</code>, it is not able to find the <code>Continue with Google button</code> and gives a <code>NoSuchElementException</code> error. Here is the codebase for it:</p>
<pre><code>login_url='https://secure.indeed.com/auth?hl=en_US&co=US&continue=https%3A%2F%2Fwww.indeed.com%2F&tmpl=desktop&service=my&from=gnav-util-homepage&jsContinue=https%3A%2F%2Fwww.indeed.com%2F&empContinue=https%3A%2F%2Faccount.indeed.com%2Fmyaccess&_ga=2.36143904.1242603427.1673200412-1007460264.1673200412'
driver = uc.Chrome()
# driver.delete_all_cookies()
wait = WebDriverWait(driver, 5)
test = driver.get(login_url)
time.sleep(4)
window_before = driver.window_handles[0]
try:
driver.find_element(By.XPATH, '//*[@id="login-google-button"]').click()
except NoSuchElementException:
print("No Such Element Exception")
</code></pre>
<p>I have checked all the answers but none are helping. Can anyone help? Thanks</p>
|
<python><selenium><selenium-webdriver>
|
2023-02-07 11:31:36
| 1
| 462
|
Gopal Chitalia
|
75,372,758
| 6,068,731
|
Matplotlib fill area between contour lines where one contour line is made of two disjoint curves
|
<p>I have a function <code>f</code> and I would like to color-fill between two contours.
One contour is shown in blue in the figure on the left. The contour consists in two <strong>disjoint</strong> curves. Another contour is shown in green in the middle figure, and consists in a single curve. Both contours are shown together in the final image on the right.
<a href="https://i.sstatic.net/AwaoO.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AwaoO.png" alt="enter image description here" /></a></p>
<p>How can I fill in between these two contours (generated using <code>ax.contour()</code>) when one contour is made of two disjoin curves?</p>
<h1>Minimal Working Example</h1>
<p>The following code creates the function of interest, generates a grid of values, and then plots and stores the contours.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
from numpy import apply_along_axis, meshgrid, arange, vstack
import matplotlib.pyplot as plt
# Function whose level-sets we are interested in
f = lambda x: x[1]**2 + 3*(x[0]**2)*(x[0]**2 - 1)
f_broadcasted = lambda x: apply_along_axis(f, 1, x)
# Generate grid of (x, y, z) values to plot contour
xlims, ylims = [-2, 2], [-2, 2]
x, y = meshgrid(arange(*xlims, 0.005), arange(*ylims, 0.005))
xys = vstack((x.flatten(), y.flatten())).T
z = f_broadcasted(xys).reshape(x.shape)
# Plot contours
fig, ax = plt.subplots()
contours = ax.contour(x, y, z, levels=[-0.02, 0.02], colors=['forestgreen', 'royalblue'])
plt.show()
</code></pre>
<p>The output of this is basically similar to the right-most figure above. I tried using</p>
<pre class="lang-py prettyprint-override"><code>ax.fill_between(*contours[1][0].T, contours[0][1])
</code></pre>
<p>but the problem is that they have different sizes.</p>
<p>Basically my desired output could be achieved (in an ugly way) by plotting MANY contours</p>
<pre class="lang-py prettyprint-override"><code>fig, ax = plt.subplots()
contours = ax.contour(x, y, z, levels=np.linspace(-0.02, 0.02, num=1000), colors='black', linestyles='-')
plt.show()
</code></pre>
<p>but the problem is that this takes quite a while and the final product is not particularly neat.
<a href="https://i.sstatic.net/hEwXfm.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/hEwXfm.png" alt="enter image description here" /></a></p>
|
<python><numpy><matplotlib>
|
2023-02-07 11:31:08
| 1
| 728
|
Physics_Student
|
75,372,522
| 16,622,985
|
Stateful DoFn with Side Input - DirectRunner issue?
|
<p>I have a stateful DoFn with a <code>beam.pvalue.AsSingleton</code> side input. When I was trying to write a test for this DoFn, I've noticed a strange behavior: Sometimes the execution fails with an <code>ValueError</code> stating that the stateful DoFn requires a key-value pair as input, i.e.</p>
<pre><code>Traceback (most recent call last):
File "/opt/playground/backend/executable_files/afa71397-d19b-4088-8d4b-85d16735631e/afa71397-d19b-4088-8d4b-85d16735631e.py", line 38, in <module>
dot = pipeline_graph.PipelineGraph(pipeline).get_dot()
File "/usr/local/lib/python3.7/site-packages/apache_beam/runners/interactive/display/pipeline_graph.py", line 78, in __init__
pipeline, pipeline._options)
File "/usr/local/lib/python3.7/site-packages/apache_beam/runners/interactive/pipeline_instrument.py", line 72, in __init__
pipeline.to_runner_api(), pipeline.runner, options)
File "/usr/local/lib/python3.7/site-packages/apache_beam/pipeline.py", line 913, in to_runner_api
root_transform_id = context.transforms.get_id(self._root_transform())
File "/usr/local/lib/python3.7/site-packages/apache_beam/runners/pipeline_context.py", line 104, in get_id
self._id_to_proto[id] = obj.to_runner_api(self._pipeline_context)
File "/usr/local/lib/python3.7/site-packages/apache_beam/pipeline.py", line 1304, in to_runner_api
for part in self.parts
File "/usr/local/lib/python3.7/site-packages/apache_beam/pipeline.py", line 1304, in <listcomp>
for part in self.parts
File "/usr/local/lib/python3.7/site-packages/apache_beam/runners/pipeline_context.py", line 104, in get_id
self._id_to_proto[id] = obj.to_runner_api(self._pipeline_context)
File "/usr/local/lib/python3.7/site-packages/apache_beam/pipeline.py", line 1291, in to_runner_api
transform_spec = transform_to_runner_api(self.transform, context)
File "/usr/local/lib/python3.7/site-packages/apache_beam/pipeline.py", line 1286, in transform_to_runner_api
named_inputs=self.named_inputs())
File "/usr/local/lib/python3.7/site-packages/apache_beam/transforms/ptransform.py", line 742, in to_runner_api
urn, typed_param = self.to_runner_api_parameter(context, **extra_kwargs) # type: ignore[call-arg]
File "/usr/local/lib/python3.7/site-packages/apache_beam/transforms/core.py", line 1429, in to_runner_api_parameter
extra_kwargs.get('named_inputs', None))
File "/usr/local/lib/python3.7/site-packages/apache_beam/transforms/core.py", line 1393, in _get_key_and_window_coder
'key-value pairs.' % self)
ValueError: Input elements to the transform <ParDo(PTransform) label=[ParDo(StatefulWithSideInput)] side_inputs=[AsSingleton(PCollection[side/Map(decode).None])]> with stateful DoFn must be key-value pairs.
</code></pre>
<p>which is quite confusing, since I clearly provide a key-value input - only my side input has no key-value pair. The actual logic within the DoFn seems to be irrelevant, since this MWE causes the same issue</p>
<pre><code>import apache_beam as beam
from apache_beam.transforms.userstate import ReadModifyWriteStateSpec
from apache_beam.coders import StrUtf8Coder
class StatefulWithSideInput(beam.DoFn):
MYSTATE = ReadModifyWriteStateSpec('my_state', StrUtf8Coder())
def process(self,
element=beam.DoFn.ElementParam,
side=beam.DoFn.SideInputParam,
state=beam.DoFn.StateParam(MYSTATE)):
yield element[1]
with beam.Pipeline() as pipeline:
side_input = (
pipeline
| "side" >> beam.Create(['test'])
)
main = (
pipeline
| "main" >> beam.Create([('1', 2)])
)
(
main
| beam.ParDo(StatefulWithSideInput(), beam.pvalue.AsSingleton(side_input))
| beam.Map(print)
)
</code></pre>
<p>Most of the time the code works without any errors and returns the expected result <code>2</code>, but sporadically I get the <code>ValueError</code>. My actual DoFn is more complex (e.g., uses the side input and the state variable) and runs perfectly fine on Dataflow (no errors there). The first time I've encountered this issue is when I was trying to write a test for this DoFn.</p>
<p>Is this a DirectRunner issue/bug? Do I do something wrong when providing input for <code>StatefulWithSideInput</code>? But then again, why it is most of the time working?</p>
|
<python><google-cloud-dataflow><apache-beam>
|
2023-02-07 11:10:39
| 1
| 1,176
|
CaptainNabla
|
75,372,344
| 15,488,129
|
list of dictionaries to pd dataframe with a single row
|
<p>I have a list of dictionaries and I'm trying to create a pd.DataFrame with a single row where the key of the dictionary is a column and the value of the dictionary is its row.</p>
<p>Here is a sample:</p>
<pre><code>list_of_dicts = [{'key1': 'value1'}, {'key2':'value2'}]
</code></pre>
<p>Output DataFrame should look like:</p>
<pre><code>key1 | key2
value1 | value2
</code></pre>
<p>I've already tried:</p>
<p><code>pd.DataFrame(list_of_dicts)</code>, but I get something like this:</p>
<pre><code>key 1 | key2
value1 | NaN
NaN | value2
</code></pre>
<p>I've already tried:</p>
<pre><code>df = pd.DataFrame()
for e in list_of_dicts:
for k, v in e.items():
df[k] = k
</code></pre>
<p>But it creates an empty DataFrame with dictionary keys as column but with no value.
Could you help?</p>
<p>Thanks</p>
|
<python><pandas><dictionary>
|
2023-02-07 10:52:54
| 3
| 321
|
Girolamo
|
75,372,319
| 12,206,537
|
How to solve "ImportError: DLL load failed while importing `something`: The filename or extension is too long." while pip installing in a long path
|
<p>When I am trying to pip install some packages for a python project in a directory with a long path name an error pops up. It has more to do with Windows than Python as it is a DLL file load error.</p>
<pre><code> File "C:\wgyikhefghwefuyhedg\ausyfgyhfhbsdguifhlygsfkugysfsdfukysdgfksd\jsgkasdfhkghksduyfgsajkfgusadufgfkyhsudgfkusdyfbsfgsudkfgsduyfgasdku\qwertyuiop\sierghdsyfgh\iaseufbhsaldgj\qasderf\.venv\lib\site-packages\charset_normalizer\cd.py", line 9, in <module>
from .md import is_suspiciously_successive_range
ImportError: DLL load failed while importing md__mypyc: The filename or extension is too long.
</code></pre>
<p>The path given here is abstract, but it is important that the path is very long.</p>
<p>I did try <a href="https://docs.python.org/3/using/windows.html#removing-the-max-path-limitation" rel="nofollow noreferrer">this</a> and still the issue persists. Yes, I did restart my machine.</p>
<p>The import works fine when running pip install on a shorter path.</p>
<p>Trying to install some packages for a python project in a directory with long path.</p>
<p>Expected to install fine without errors. Throwing path too long error instead.</p>
|
<python><windows><pip>
|
2023-02-07 10:51:33
| 0
| 301
|
Sharath Cherian Thomas
|
75,372,064
| 7,766,024
|
How can I "broadcast" negative sampling using NumPy?
|
<p>I'm currently trying to perform negative sampling where I have an array of integers and a certain number of positive sample integers contained within this range. My current algorithm is as follows:</p>
<pre><code>total = 50000
positive_samples = np.random.choice(np.arange(total), size=(30000,), replace=False)
def get_negative_samples(positive_samples, num_negatives=100):
negative_samples = []
for positive_sample in positive_samples:
candidates = np.concatenate((np.arange(positive_sample), np.arange(positive_sample + 1, total)))
sampled = np.random.choice(candidates, size=(num_negatives,), replace=False)
negative_samples.append(sampled)
return negative_samples
</code></pre>
<p>This code is slow because it uses a for loop and creates rather large candidate lists. I'm wondering if it would be possible to achieve something where I have the list of positive samples and I would be able to efficiently get the negative sample candidates <em>and</em> perform negative sampling.</p>
|
<python><numpy>
|
2023-02-07 10:29:23
| 1
| 3,460
|
Sean
|
75,372,032
| 330,867
|
In Python, what is the difference between `async for x in async_iterator` and `for x in await async_iterator`?
|
<p>The subject contains the whole idea. I came accross code sample where it shows something like:</p>
<pre class="lang-py prettyprint-override"><code>async for item in getItems():
await item.process()
</code></pre>
<p>And others where the code is:</p>
<pre class="lang-py prettyprint-override"><code>for item in await getItems():
await item.process()
</code></pre>
<p>Is there a notable difference in these two approaches?</p>
|
<python><python-3.x><asynchronous><python-asyncio>
|
2023-02-07 10:26:26
| 2
| 40,087
|
Cyril N.
|
75,372,008
| 15,479,269
|
Python scraper won't complete
|
<p>I am using this code to scrape emails from Google search results. However, it only scrapes the first 10 results, despite having 100 search results loaded.</p>
<p>Ideally, I would like for it to scrape all search results.</p>
<p>Is there a reason for this?</p>
<pre><code>from selenium import webdriver
import time
import re
import pandas as pd
PATH = 'C:\Program Files (x86)\chromedriver.exe'
l = list()
o = {}
target_url = "https://www.google.com/search?q=solicitors+wales+%27email%27+%40&rlz=1C1CHBD_en-GBIT1013IT1013&sxsrf=AJOqlzWC1oRbVtWcmcIgC4-3ZnGkQ8sP_A%3A1675764565222&ei=VSPiY6WeDYyXrwStyaTwAQ&ved=0ahUKEwjlnIy9lYP9AhWMy4sKHa0kCR4Q4dUDCA8&uact=5&oq=solicitors+wales+%27email%27+%40&gs_lcp=Cgxnd3Mtd2l6LXNlcnAQAzIFCAAQogQyBwgAEB4QogQyBQgAEKIESgQIQRgASgQIRhgAUABYAGD4AmgAcAF4AIABc4gBc5IBAzAuMZgBAKABAcABAQ&sclient=gws-wiz-serp"
driver = webdriver.Chrome(PATH)
driver.get(target_url)
email_pattern = r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,4}"
html = driver.page_source
emails = re.findall(email_pattern, html)
time.sleep(10)
df = pd.DataFrame(emails, columns=['Email Addresses'])
df.to_excel('email_addresses_.xlsx', index=False)
#print(emails)
driver.close()
</code></pre>
|
<python><pandas><selenium-webdriver><web-scraping>
|
2023-02-07 10:23:09
| 3
| 703
|
someone
|
75,372,002
| 10,071,473
|
Release redis lock if process die
|
<p>I'm using redis distributed locks to make sure some celery tasks don't run concurrently. For managing locks with redis I'm using the python <a href="https://pypi.org/project/redis/" rel="nofollow noreferrer">redis</a> library version <strong>4.0.0</strong> (which specifies that any deadlock problems should be handled by the programmer).</p>
<p>Since I would like to avoid using the <strong>timeout</strong> parameter for the lock, since the task execution time is very variable, I would like to know if there is a way to verify that the active lock is actually owned by a process, and that it has not been blocked due to a sudden crash of the application and its failure to <strong>release</strong>.</p>
<pre><code>@shared_task(
name='test_task',
queue="test"
)
def test(value):
lock_acquired = False
try:
lock = redis_cli.lock('test_lock', sleep=1)
lock_acquired = lock.acquire(blocking=False)
if lock_acquired:
print(f"HELLO FROM: {value}")
sleep(15)
else:
print(f"LOCKED")
except Exception as e:
print(str(e))
finally:
if lock_acquired:
lock.release()
</code></pre>
<p>Taking the piece of code above, if the application were to unexpectedly crash during the <strong>sleep(15)</strong>, the lock would still be locked at the next execution, even though the process that acquired it no longer exists. How can I prevent this situation?</p>
<p><strong>python version</strong>: 3.6.8</p>
<p><strong>redis server version</strong>: Redis server v=4.0.9 sha=00000000:0 malloc=jemalloc-3.6.0 bits=64 build=9435c3c2879311f3</p>
<p><strong>celery</strong>==5.1.1</p>
|
<python><redis><concurrency><celery><locking>
|
2023-02-07 10:22:41
| 1
| 2,022
|
Matteo Pasini
|
75,371,946
| 2,439,278
|
Unable to install R 4.1.3 in fastapi Docker image
|
<p>I'm using a dockerfile which uses tiangolo/uvicorn-gunicorn-fastapi:python3.8-slim-2021-06-09 as base image and installs the required linux package and also installs r-recommended and r-base. Earlier below dockerfile works fine. But when I tried to update the image with tiangolo/uvicorn-gunicorn-fastapi:python3.8-slim-2023-01-09 as base image, unable to install the r-recommended and r-base with version 4.1.2-1~bustercran.0.</p>
<p><strong>Dockerfile :</strong></p>
<pre><code># Download IspR from IspR project pipeline and extract the folder and rename it as r-scripts. Place the r-scripts directory in backend root directory.
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.8-slim-2023-01-09
COPY key_gnupg.gpg /app/key_gnupg.gpg
COPY packages.txt /app/packages.txt
RUN echo "Acquire::Check-Valid-Until \"false\";\nAcquire::Check-Date \"false\";" | cat > /etc/apt/apt.conf.d/10no--check-valid-until
RUN apt-get update && apt-get install -y gnupg2=2.2.27-2+deb11u2 && \
echo "deb http://cloud.r-project.org/bin/linux/debian buster-cran40/" >> /etc/apt/sources.list.d/cran.list && \
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys B8F25A8A73EACF41 && \
apt-get update
RUN apt-get install --no-install-recommends -y $(cat /app/packages.txt) && \
rm -rf /var/lib/apt/lists/* && \
apt-get purge --auto-remove && \
apt-get clean
COPY . /app
WORKDIR /app/r-scripts
RUN R -e "install.packages('remotes')"
RUN renv_version=`cat renv.lock | grep -A3 "renv" | grep -e "Version" | cut -d ':' -f2 | sed "s/\"//g" | sed "s/\,//g"|awk '{$1=$1};1'` && \
R -e "remotes::install_github('rstudio/renv@${renv_version}')" && \
rm -rf /app
CMD ["/bin/bash"]
</code></pre>
<p><strong>packages.txt</strong></p>
<pre><code>git=1:2.20.1-2+deb10u3
pkg-config=0.29-6
liblapack-dev=3.8.0-2
gfortran=4:8.3.0-1
libxml2=2.9.4+dfsg1-7+deb10u3
libxml2-dev=2.9.4+dfsg1-7+deb10u3
libssl-dev=1.1.1n-0+deb10u1
libcurl4-openssl-dev=7.64.0-4+deb10u2
libnlopt-dev=2.4.2+dfsg-8+b1
libpcre2-8-0=10.32-5
build-essential=12.6
r-recommended=4.1.2-1~bustercran.0
r-base=4.1.2-1~bustercran.0
curl=7.64.0-4+deb10u2
postgresql=11+200+deb10u4
libpq-dev=11.14-0+deb10u1
libblas-dev=3.8.0-2
libgomp1=8.3.0-6
zlib1g-dev=1:1.2.11.dfsg-1
zlib1g=1:1.2.11.dfsg-1
</code></pre>
<p><em>Error MEssage :</em></p>
<pre><code>E: Version '4.1.2-1~bustercran.0' for 'r-base-core' was not found
</code></pre>
<p>How to install the 4.1.2 version of r-base using this Dockerfile?</p>
|
<python><r><docker>
|
2023-02-07 10:18:03
| 0
| 1,264
|
user2439278
|
75,371,811
| 82,511
|
ActiveMQ Stomp python client NACK consumes message
|
<p>I'm using ActiveMQ classic v5.16.3 and experimenting with NACK. My expectation is that if the client sends a NACK then the message will remain on the queue and be available for another client. My code is below. I set a prefetch of 1, and ack mode of client-individual.</p>
<p>If I omit the conn.nack() call then I see my print statements, and the message remains on the queue - hence I believe that ActiveMQ is looking for an ACK or NACK.</p>
<p>When I include the conn.nack() call then I again see my print statements, and the message is removed from the queue.</p>
<p>Is this expected behaviour? I think a client should be able to reject malformed messages by NACK-ing and that eventually ActiveMQ should put them to a dead letter queue.</p>
<pre><code>import time
import sys
import stomp
class MyListener(stomp.ConnectionListener):
def on_error(self, frame):
print('received an error "%s"' % frame.body)
def on_message(self, frame):
# experiment with and without the following line
conn.nack(id=frame.headers['message-id'], subscription=frame.headers["subscription"])
print('received a message "%s"' % frame.body)
print('headers "%s"' % frame.headers)
print('Connecting ...')
conn = stomp.Connection()
conn.set_listener('', MyListener())
conn.connect('admin', 'admin', wait=True)
print('Connected')
conn.subscribe(destination='/queue/audit', id=1, ack='client-individual', headers={'activemq.prefetchSize': 1})
</code></pre>
|
<python><activemq-classic><stomp>
|
2023-02-07 10:06:42
| 1
| 56,147
|
djna
|
75,371,780
| 7,357,166
|
pop method for Django queryset?
|
<p>I am having a data model where the model contains a members field to relate to objects of the same type. the idea is that each objects can also be a group of objects. Groups can contain groups etc.</p>
<pre><code>class MyObject(CommonModel):
name = models.CharField(max_length=255, unique=False, null=True, blank=True)
members = models.ManyToManyField("self", blank=True, symmetrical=False)
</code></pre>
<p>For a search with Django-filters I need to perform a recursive search to get all items, but also all parent group items. So I wrote this little helper function that take a query set from a previous search(by name for example) and gives back a queryset that contains all items where one of the items in the querste is in a member.</p>
<pre><code>def recursive_objects_member_filter(queryset):
"""Takes a queryset and retruns a queryset of all parent objects"""
query_set_result = []
while queryset:
query_item = queryset.pop()
query_set_result.append(query_item)
members_queryset = MyObject.objects.filter(members=query_item).exclude(id =
query_item.id
)
for member in members_queryset:
queryset.append(member)
return query_set_result
</code></pre>
<p>My problem is that there does not seem to be a function to remove an item from a queryset like pop().</p>
|
<python><django><django-rest-framework><django-filters>
|
2023-02-07 10:04:45
| 2
| 422
|
Empusas
|
75,371,726
| 16,405,935
|
How to read all tables with read_html
|
<p>I'm trying to extract a table from link but I can not do it. This is how table show on web:</p>
<p><a href="https://i.sstatic.net/iSRvL.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/iSRvL.png" alt="enter image description here" /></a></p>
<p>I used below code to read html:</p>
<pre><code>import requests
import pandas as pd
url = 'https://spib.wooribank.com/pib/Dream?withyou=ENENG0358'
df = pd.read_html(url)[1:4]
df
</code></pre>
<p>And here is the Output:</p>
<pre><code>[ Currency Buy Sell
0 USD 1283.06 1238.94
1 JPY 973.64 940.16
2 EUR 1379.70 1326.40,
Currency Send Receive
0 USD 1273.20 1248.80
1 JPY 966.18 947.62
2 EUR 1366.58 1339.52,
Currency Buy Sell
0 USD 1276.13 1248.80
1 JPY 968.38 947.62
2 EUR 1373.34 1339.52]
</code></pre>
<p>I tried to using f12 to find table class and use <code>attrs</code> to extract bu it raised error that <code>No tables found</code>.</p>
<pre><code>url = 'https://spib.wooribank.com/pib/Dream?withyou=ENENG0358'
df = pd.read_html(url,attrs={"class":"tbl-type-1 txt-c mb20 ui-set-tbl-type"})
</code></pre>
<p>So please help me to find the way to extract the data. Another question that is there anyway to extract data after filtering (Reported date).</p>
<p>Thank you.</p>
|
<python><html><pandas><web-scraping>
|
2023-02-07 10:00:47
| 1
| 1,793
|
hoa tran
|
75,371,648
| 16,027,663
|
Compare Datetime Columns in Dataframe with Criteria
|
<p>In a dataframe with two datetime columns is it possible to retun only rows where ATime is no more than 1 minute before BTime? Note it should also return rows where ATime is greater than BTime.</p>
<p>Original:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Atime</th>
<th>BTime</th>
</tr>
</thead>
<tbody>
<tr>
<td>06/01/2017 19:58:01</td>
<td>06/01/2017 20:00:00</td>
</tr>
<tr>
<td>06/01/2017 19:59:01</td>
<td>06/01/2017 20:00:00</td>
</tr>
<tr>
<td>06/01/2017 20:00:01</td>
<td>06/01/2017 20:00:00</td>
</tr>
</tbody>
</table>
</div>
<p>Result:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Atime</th>
<th>BTime</th>
</tr>
</thead>
<tbody>
<tr>
<td>06/01/2017 19:59:01</td>
<td>06/01/2017 20:00:00</td>
</tr>
<tr>
<td>06/01/2017 20:00:01</td>
<td>06/01/2017 20:00:00</td>
</tr>
</tbody>
</table>
</div>
|
<python><pandas>
|
2023-02-07 09:55:48
| 1
| 541
|
Andy
|
75,371,594
| 10,737,147
|
Populating NumPy array with most performance
|
<p>I want to populate a matrix by function <code>f()</code> which consumes arrays <code>a</code>, <code>b</code>, <code>c</code> and <code>d</code>:</p>
<p><a href="https://i.sstatic.net/dAkY9.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/dAkY9.png" alt="enter image description here" /></a></p>
<p>A nested loop is possible but I'm looking for a faster way. I tried <code>np.fromfunction</code> with no luck. Function f has a conditional so the solution should preferably support conditionals. Example function:</p>
<pre><code>def f(a,b,c,c):
return a+b+c+d if a==b else a*b*c*d
</code></pre>
<p>How <code>np.fromfunction</code> failed:</p>
<pre><code>>>> a = np.array([1,2,3,4,5])
>>> b = np.array([10,20,30])
>>> def f(i,j): return a[i] * b[j]
>>> np.fromfunction(f, (3,5))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Anaconda3\lib\site-packages\numpy\core\numeric.py", line 1853, in fromfunction
return function(*args, **kwargs)
File "<stdin>", line 1, in fun
IndexError: arrays used as indices must be of integer (or boolean) type
</code></pre>
|
<python><arrays><numpy><matrix>
|
2023-02-07 09:51:35
| 2
| 437
|
XYZ
|
75,371,577
| 3,592,342
|
Infill image gaps after Morph Open opencv
|
<p>I have an input signature for which I want to remove the gridlines of same color.
<a href="https://i.sstatic.net/FJYO6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/FJYO6.png" alt="enter image description here" /></a></p>
<p>So far I am using this <a href="https://stackoverflow.com/a/58002605/3592342">python code</a> to do that</p>
<pre><code>import cv2
import numpy as np
## Load image and make B&W version
image = cv2.imread('Downloads/image.png')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
# Remove horizontal
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (50,1))
detected_lines = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
cnts = cv2.findContours(detected_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
cv2.drawContours(thresh, [c], -1, (0,0,0), 2)
cv2.imwrite('Downloads/out.png', thresh)
</code></pre>
<p>Which takes me to the following image.</p>
<p><a href="https://i.sstatic.net/Odey8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Odey8.png" alt="enter image description here" /></a></p>
<p>Now I am trying to infill the gaps introduced, I tried using a vertical kernel and morph close but that infills the other spaces in images a lot.</p>
<p>Any ideas on how I can achieve the said infilling using a more sophisticated operation and get the infill done without tampering with the existing signature much.</p>
|
<python><opencv><image-processing><computer-vision>
|
2023-02-07 09:50:26
| 0
| 949
|
anonR
|
75,371,273
| 16,665,831
|
Snapchat Marketing API Does Not Return for List Values Requests
|
<p>I am trying to build a pipeline on <a href="https://marketingapi.snapchat.com/docs/#organizations" rel="nofollow noreferrer">Snapchat Marketing API</a> to fetch campaign insight data under the ad account but when I want to run the following python script, It returns the response only with country dimension (do not return os dimension) and only impression metric from the fields list (do not return spend, swipes, total_installs metrics). I think the problem is because of the list values, it takes only the first ones but, I could not solve it.</p>
<pre><code>def post_snapchat_campaign_data(adAccount_id, access_token, granularity, breakdown, report_dimension, start_time, end_time, fields):
url = "https://adsapi.snapchat.com/v1/adaccounts/{}/stats".format(adAccount_id)
params = {
"granularity": granularity,
"breakdown": breakdown,
"report_dimension": report_dimension,
"start_time": start_time,
"end_time": end_time,
"fields": fields
}
headers = {'Authorization': access_token}
response = requests.request("GET", url, headers = headers, params=params)
return response
def get_snapchat_campaign_data(adAccount_id, access_token):
response = post_snapchat_campaign_data(
adAccount_id = adAccount_id,
access_token = access_token,
granularity = "DAY",
breakdown = "campaign",
report_dimension = ["country", "os"],
start_time = "2022-02-02",
end_time = "2022-02-03",
fields = ["impressions", "spend", "swipes", "total_installs"]
)
return response.json()
</code></pre>
|
<python><json><python-requests><snapchat>
|
2023-02-07 09:25:54
| 1
| 309
|
Ugur Selim Ozen
|
75,371,271
| 4,996,021
|
Compute on all other values except the current row using a window function in Polars?
|
<p>For each row, I'm trying to compute the standard deviation for the other values in a group excluding the row's value. A way to think about it is "what would the standard deviation for the group be if this row's value was removed". An example may be easier to parse:</p>
<pre class="lang-py prettyprint-override"><code>import polars as pl
df = pl.DataFrame(
{
"answer": ["yes","yes","yes","yes","maybe","maybe","maybe"],
"value": [5,10,7,8,6,9,10],
}
)
</code></pre>
<p>I would want to add a column that would have the first row be std([10,7,8]) = 1.527525</p>
<pre><code>┌────────┬───────┐
│ answer ┆ value │
│ --- ┆ --- │
│ str ┆ i64 │
╞════════╪═══════╡
│ yes ┆ 5 │ # std([10, 7, 8])
│ yes ┆ 10 │ # std([5, 7, 8])
│ yes ┆ 7 │
│ yes ┆ 8 │
│ maybe ┆ 6 │ # std([9, 10])
│ maybe ┆ 9 │ # std([6, 10])
│ maybe ┆ 10 │
└────────┴───────┘
</code></pre>
<p>I tried to hack something together and ended up with code that is horrible to read and also has a bug that I don't know how to work around:</p>
<pre class="lang-py prettyprint-override"><code>df.with_columns(
(
(pl.col("value").sum().over(pl.col("answer")) - pl.col("value"))
/ (pl.col("value").count().over(pl.col("answer")) - 1)
).alias("average_other")
).with_columns(
(
(
(
(pl.col("value") - pl.col("average_other")).pow(2).sum().over(pl.col("answer"))
- (pl.col("value") - pl.col("average_other")).pow(2)
)
/ (pl.col("value").count().over(pl.col("answer")) - 1)
).sqrt()
).alias("std_dev_other")
)
</code></pre>
<p>I'm not sure I would recommend parsing that, but I'll point out at least one thing that is wrong:</p>
<pre class="lang-py prettyprint-override"><code>pl.col("value") - pl.col("average_other")).pow(2).sum().over(pl.col("answer"))
</code></pre>
<p>I want to be comparing "value" in each row to "average_other" from this row then squaring and summing over the window but instead I am comparing "value" in each row to "average_other" in each row.</p>
<p>Essentially I'm looking for a Polars equivalent of the <a href="https://duckdb.org/docs/stable/sql/functions/window_functions.html#exclude-clause" rel="nofollow noreferrer">EXCLUDE CURRENT ROW</a> clause from SQL.</p>
<pre class="lang-py prettyprint-override"><code>import duckdb
duckdb.sql("""
from df
select
*,
result: stddev(value) over (
partition by answer
rows between unbounded preceding and unbounded following
exclude current row
)
""").pl()
</code></pre>
<pre><code>shape: (7, 3)
┌────────┬───────┬──────────┐
│ answer ┆ value ┆ result │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ f64 │
╞════════╪═══════╪══════════╡
│ yes ┆ 5 ┆ 1.527525 │
│ yes ┆ 10 ┆ 1.527525 │
│ yes ┆ 7 ┆ 2.516611 │
│ yes ┆ 8 ┆ 2.516611 │
│ maybe ┆ 6 ┆ 0.707107 │
│ maybe ┆ 9 ┆ 2.828427 │
│ maybe ┆ 10 ┆ 2.12132 │
└────────┴───────┴──────────┘
</code></pre>
|
<python><dataframe><window-functions><python-polars>
|
2023-02-07 09:25:44
| 3
| 610
|
pwb2103
|
75,371,133
| 14,125,436
|
How to add dropout layers automatically to a neural network in pytorch
|
<p>I have a neural network in <code>pytorch</code> and make each layer automatically via the following structure:</p>
<pre><code>class FCN(nn.Module):
##Neural Network
def __init__(self,layers):
super().__init__() #call __init__ from parent class
self.activation = nn.Tanh()
self.loss_function = nn.MSELoss(reduction ='mean')
'Initialise neural network as a list using nn.Modulelist'
self.linears = nn.ModuleList([nn.Linear(layers[i], layers[i+1]) for i in range(len(layers)-1)])
self.iter = 0
'Xavier Normal Initialization'
for i in range(len(layers)-1):
nn.init.xavier_normal_(self.linears[i].weight.data, gain=1.0)
nn.init.zeros_(self.linears[i].bias.data)
'foward pass'
def forward(self, x):
if torch.is_tensor(x) != True:
x = torch.from_numpy(x)
a = x.float()
for i in range(len(layers)-2):
z = self.linears[i](a)
a = self.activation(z)
a = self.linears[-1](a)
return a
</code></pre>
<p>The following code also makes the network for me:</p>
<pre><code>layers = np.array([2, 50, 50, 1])
model = FCN(layers)
</code></pre>
<p>Now, I am wondering how I can automatically add <code>dropout</code> layers to the network. I tried the following change in the network structure but it only gives me one dropout layer at the end:</p>
<pre><code>self.linears = nn.ModuleList([nn.Linear(layers[i], layers[i+1]) for i in range(len(layers)-1) + nn.Dropout(p=0.5)]
</code></pre>
<p>I very much appreciate any help in this regard.</p>
|
<python><deep-learning><pytorch><neural-network><dropout>
|
2023-02-07 09:14:45
| 2
| 1,081
|
Link_tester
|
75,371,106
| 13,803,549
|
Close Discord message on button click
|
<p>I have a select menu with a submit button. When submit is clicked I want to close the current message, submit the data and then open a new select menu but I am having trouble figuring out how to have the message close.</p>
<p>How can I have the current menu and button close when the submit button is clicked?</p>
<p>Thanks in advance for your help.</p>
|
<python><discord><discord.py>
|
2023-02-07 09:13:14
| 1
| 526
|
Ryan Thomas
|
75,370,815
| 3,842,788
|
Pylint: Specifying exception names in the overgeneral-exceptions option without module name is deprecated
|
<blockquote>
<p>pylint: Command line or configuration file:1: UserWarning: Specifying
exception names in the overgeneral-exceptions option without module
name is deprecated and support for it will be removed in pylint 3.0.
Use fully qualified name (maybe 'builtins.BaseException' ?) instead.</p>
</blockquote>
<p>Getting PyLint error.
I dont have any Except clause in my file and yet I see this error.</p>
|
<python><pylint>
|
2023-02-07 08:41:32
| 2
| 6,957
|
Aseem
|
75,370,436
| 8,971,938
|
Keras CategoryEncoding layer with time sequences
|
<p>For a LSTM, I create time sequences by means of <code>tensorflow.keras.utils.timeseries_dataset_from_array()</code>. For some of the features, I would like to do one-hot encoding by means of Keras preprocessing layers.</p>
<p>I have the following code:</p>
<pre><code>n_timesteps = 20
n_categorical_features = 1
from tensorflow.keras.layers import Input, IntegerLookup, CategoryEncoding
cat_inp = keras.layers.Input(shape=(n_timesteps, n_categorical_features), name = "categorical_input")
index = IntegerLookup()
index.adapt(X["br"])
encoder = CategoryEncoding(num_tokens=index.vocabulary_size(), output_mode = "one_hot")(cat_inp)
</code></pre>
<p>However, the last line gives me the error <code>ValueError: Exception encountered when calling layer "category_encoding_22" (type CategoryEncoding). When output_mode is not </code>'int'<code>, maximum supported output rank is 2. Received output_mode one_hot and input shape (None, 20, 1), which would result in output rank 3.</code> The problem seems to be that CategoryEncoding does not support the shape of my input tensor (None, n_timesteps, n_categorical_features).</p>
<p>How can I one-hot encode the input tensor produced by <code>timeseries_dataset_from_array()</code>?</p>
|
<python><keras><encoding><one-hot-encoding>
|
2023-02-07 08:05:39
| 1
| 597
|
Requin
|
75,370,330
| 12,435,792
|
TypeError: 'return_type' is an invalid keyword argument for split()
|
<p>I have a df with start and end time columns. Since these columns might have gibberish values, I have put in try and except blocks. I'm trying to pad the times to make them consistent and then finally save them as pandas datetime.time values.
Here's the code:</p>
<pre><code> for i in range(df.shape[0]):
try:
df.loc[i,'start time'] = pd.to_datetime(df.loc[i,'start time'].split(':', expand=True)
.apply(lambda col: col.str.zfill(2))
.fillna('00')
.agg(':'.join, axis=1)).dt.time
except:
pass
try:
df.loc[i,'end time'] = pd.to_datetime(df.loc[i,'end time'].str.split(':', expand=True)
.apply(lambda col: col.str.zfill(2))
.fillna('00')
.agg(':'.join, axis=1)).dt.time
except:
pass
</code></pre>
<p>But this piece of code gives an error:
<strong>TypeError: 'expand' is an invalid keyword argument for split()</strong></p>
<p>What am I missing here?</p>
|
<python><pandas><dataframe><split>
|
2023-02-07 07:52:37
| 1
| 331
|
Soumya Pandey
|
75,370,203
| 9,748,823
|
Pandas: Filter DataFrame by two conditions
|
<p>How do you filter a DataFrame if two conditions must apply in connection with not separately?
I tried to do this with a left outer join but I was wondering if there was a simpler approach:</p>
<pre class="lang-py prettyprint-override"><code>dataset = pd.DataFrame(
{
"count": [2, 1, 1, 2, 1],
"name": ["foo", None, "foo", None, "bar"],
}
)
to_be_excluded = dataset.loc[(dataset["name"] == "foo") & (dataset["count"] == 1)]
pd.merge(
dataset, to_be_excluded, on=["name", "count"], how="outer", indicator=True
).query('_merge=="left_only"').iloc[:, 0:2]
</code></pre>
<p>Expected:</p>
<pre><code>count name
2 foo
1 None
2 None
1 bar
</code></pre>
|
<python><pandas>
|
2023-02-07 07:40:48
| 2
| 381
|
Blob
|
75,370,020
| 9,668,481
|
Is there any way to use regular expression in NO_PROXY environment variable?
|
<p>I want to bypass proxy for domains like:</p>
<pre><code>http://server-1:5000
http://server-2:5000
</code></pre>
<p><code>NO_PROXY=server-1, server-2</code></p>
<p>server-1 and server-2 are basically services attached to kube pods, so they can change dynamically during runtime.</p>
<p>I want to bypass proxy for any domains in this format. For example, at any point it can even reach to <code>server-124</code>.</p>
<p>It would have been easier if domain name was in this format : <code>subdomain.domain.com</code>
like <code>1.server.com</code> , <code>2.server.com</code>.</p>
<p>I believe, <code>NO_PROXY=.server.com</code> would have worked in this case.</p>
<p>But my current scenario is a little different. So, can it be done ?</p>
|
<python><kubernetes><python-requests><proxy>
|
2023-02-07 07:22:36
| 2
| 846
|
Saurav Pathak
|
75,369,745
| 496,837
|
How to scrape the extract number of Likes of a tweet via selenium
|
<p>I need to scrape the number 21,633. It is the hover text when I move the mouse to <code>21.6K Likes</code>. Please have a look at the below image.</p>
<p><a href="https://i.sstatic.net/C3dod.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/C3dod.png" alt="enter image description here" /></a></p>
<p>I successfully move the mouse to <code>21.6K Likes</code></p>
<pre><code>href_text = driver.find_element_by_xpath('//a[contains(@href,"' + '/TwitterDev/status/1621026986784337922/likes' + '")]')
hov = ActionChains(driver).move_to_element(href_text)
hov.perform()
</code></pre>
<p>The hover text <code>21,633</code> show up on browser as in the image, however, I could not find it in html source code.
How can I scrape hover text content <code>21,633</code> using selenium/beautifulsoup4?</p>
<p>Thanks.</p>
|
<python><selenium><beautifulsoup>
|
2023-02-07 06:49:00
| 1
| 4,030
|
John
|
75,369,743
| 3,713,236
|
How to remove 1 element in a list without Python returning "None"?
|
<p>All the other posts out there currently address the "why" but not the "how".</p>
<p>I have a list created from a dataframe's index called <code>df.index.to_list()</code>. Its contents are:</p>
<pre><code>['ScreenPorch',
'BsmtFinSF2',
'EnclosedPorch',
'LotArea',
'MasVnrArea',
'2ndFlrSF',
'1stFlrSF',
'GarageArea',
'WoodDeckSF',
'GrLivArea',
'OpenPorchSF',
'SalePrice',
'Id',
'LotFrontage',
'YearRemodAdd',
'BsmtFinSF1',
'YearBuilt',
'GarageYrBlt',
'BsmtUnfSF',
'TotalBsmtSF']
</code></pre>
<p>I would like to remove <code>SalePrice</code> from this list. However, if I do <code>print(df.index.to_list().remove('SalePrice'))</code>, Python returns <code>None</code> .</p>
<p><strong>How</strong> would I return the list without the element <code>SalePrice</code>?</p>
|
<python><list>
|
2023-02-07 06:48:34
| 1
| 9,075
|
Katsu
|
75,369,695
| 16,124,033
|
How do I let Python know that these two words are the same?
|
<p>I have a <code>.csv</code> file. Here is an example:</p>
<p>Table format:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>A</th>
<th>AA</th>
</tr>
</thead>
<tbody>
<tr>
<td>BB</td>
<td>B</td>
</tr>
<tr>
<td>C</td>
<td>CC</td>
</tr>
<tr>
<td>D D</td>
<td>D DD</td>
</tr>
</tbody>
</table>
</div>
<p>Text format:</p>
<pre><code>A,AA
BB,B
C,CC
D D,D DD
</code></pre>
<p>I want Python to know that <code>A</code> is equal to <code>AA</code>, <code>BB</code> is equal to <code>B</code>, and <code>C</code> is equal to <code>CC</code>. Also, the fourth example has spaces.</p>
<p>It can also be reversed, such as checking whether <code>AA</code> is equal to <code>A</code>.</p>
<p>What I'm working on is a search engine. A word may be written in two ways, so I need to do this.</p>
<p>For example, I have a boolean variable that checks if the search result is <code>A</code> and it returns <code>AA</code>, then it is <code>True</code>. Of course, returning <code>A</code> is also <code>True</code>.</p>
<p>My code:</p>
<pre class="lang-py prettyprint-override"><code>query = … // "AA"
result_list = … // ["A"]
sorted_list = [element for element in result_list if element.find(query) != -1]
</code></pre>
<p>Feel free to leave a comment if you need more information.</p>
<p>How do I let Python know that these two words are the same?</p>
|
<python>
|
2023-02-07 06:42:16
| 5
| 4,650
|
My Car
|
75,369,610
| 8,971,938
|
Keras timeseries_dataset_from_array with multiple column types?
|
<p>For a LSTM, I would like to use <code>tensorflow.keras.utils.timeseries_dataset_from_array()</code> to create sequences of training data samples. My training data contains multiple data types (numerical, categorical) which I would like to preprocess by means of Keras' preprocessing layers within the neural network.
However, it seems to me that <code>timeseries_dataset_from_array()</code> is not compatible with columns with different data types, although the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/utils/timeseries_dataset_from_array" rel="nofollow noreferrer">documentation</a> does not tell this:</p>
<pre><code>X = pd.DataFrame({
"categorical": ["a", "b", "c"],
"numerical": [1, 2, 3]
})
y = np.array([1,2,3])
n_timesteps = 1
batch_size = 1
input_dataset = timeseries_dataset_from_array(
X, y, sequence_length=n_timesteps, sequence_stride=1, batch_size=20
)
</code></pre>
<p>This results in the following error: <code>ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type int).</code></p>
<p>So, can you only use data of the same type with timeseries_dataset_from_array()? And if so, what can I do if I want to create training data sequences of multiple data types?</p>
|
<python><keras><types><time-series><generator>
|
2023-02-07 06:30:57
| 1
| 597
|
Requin
|
75,369,517
| 1,991,502
|
Can you directly alter the value of a non-list argument passed to a function?
|
<p>This snippet of python code</p>
<pre><code>def changeValue(x):
x = 2*x
a = [1]
changeValue(a[0])
print(a[0])
</code></pre>
<p>Will print the result "1" when I would like it to print the result "2". Can this be done by only altering the function and no other part of the code? I know there are solutions like</p>
<pre><code>def changeValue(x):
x[0] = 2*x[0]
a = [1]
changeValue(a)
</code></pre>
<p>or</p>
<pre><code>def changeValue(x):
return 2*x
a = [1]
a[0] = changeValue(a[0])
</code></pre>
<p>I am wondering if the argument passed as-is can be treated as a pointer in some sense.</p>
<p>[edit] - Just found a relevant question <a href="https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference">here</a> so this is likely a duplicate that can be closed.</p>
|
<python><function>
|
2023-02-07 06:16:01
| 1
| 749
|
DJames
|
75,369,462
| 11,023,647
|
How to disable syslogger when running tests in GitLab pipeline?
|
<p>I have defined tests running in GitLab cicd pipeline. I also have <code>syslog-ng</code> set up for logging. The whole app is runnning with <code>docker-compose</code>. I have defined my syslogger like this:</p>
<pre><code>import logging
from logging.handlers import SysLogHandler
def get_logger(name):
syslog = SysLogHandler(address=("syslog-ng-container", 514))
logger = logging.getLogger(name)
logger.setLevel("DEBUG")
logger.addHandler(syslog)
return logger
</code></pre>
<p>This works perfectly when running the app but when running tests I don't have the <code>syslog-ng-container</code> running and tests fail when trying to import the logger. I was wondering how could I disable setting the syslogger when running tests? I was thinking I could set up some variable e.g.</p>
<pre><code>if TEST is not True:
syslog = SysLogHandler(address=("syslog-ng-container", 514))
logger.addHandler(syslog)
</code></pre>
<p>Can I set this variable to be <code>True</code> in my <code>.gitlab-ci.yml</code> -file or do I need to specify the <code>TEST = True</code> separately in every test file I have?</p>
|
<python><gitlab-ci><syslog-ng>
|
2023-02-07 06:08:49
| 1
| 379
|
lr_optim
|
75,369,456
| 3,169,868
|
Get unique values and column names from a data frame
|
<p>I have a data frame with the following columns</p>
<pre><code>col1 col2 col3
a b b
c d e
e a b
</code></pre>
<p>I need to make a new data frame with the unique values and corresponding column names (keep set(list) of column names where value occurs in multiple columns). So output would be:</p>
<pre><code>name col_name
a [col1, col2]
b [col2, col3]
c [col1]
d [col2]
e [col1, col3]
</code></pre>
<p>How can I construct this from the given data frame?</p>
|
<python><pandas><dataframe>
|
2023-02-07 06:08:09
| 1
| 1,432
|
S_S
|
75,369,151
| 1,530,405
|
How to use an async timer
|
<p>I have a Python Server running on Win10, communicating with an Android App (written in JavaScript) as a Client, using Sockets.</p>
<p>While the App is in the foreground everything works OK. Once the App is sent to the background (depending on available memory in the mobile), communication stops, and the Server hangs waiting for a reply from the Client.</p>
<p>I could find no way to keep the Android App if the foreground, and I do not have the source code.</p>
<p>The only solution I could think of is to have an Async timer, which after (say 60 seconds) signals the Server to terminate the App, and re-open the Server awaiting for the App to re-connect.</p>
<p>Here is my PSEUDO code:</p>
<pre><code>OpenSocket() # waits for Client to connect
while True:
send(message) # to Client
start async.timer # sleep for 60 seconds
timer != finished:
reset timer
rec = receive.message() # do processing
else:
send(TerminatingMessage)
OpenSocket()
</code></pre>
<p>I would appreciate any help to code the above !</p>
|
<python><android><asynchronous>
|
2023-02-07 05:14:27
| 1
| 455
|
user1530405
|
75,369,045
| 1,900,384
|
If a timestamp is anchored in UTC, why isn't Python's `fromtimestamp` timezone-aware?
|
<p><strong>To my knowledge:</strong>
Python's <code>datetime</code> can be "naive" (if no timezone-info is available) or "timezone-aware". In contrast, a timestamp is well-defined to be anchored in UTC, i.e. a timestamp <code>0</code> corresponds to <code>1970-01-01 00:00:00+00:00</code> (no matter of your location).</p>
<p><strong>Question:</strong> Why does <code>datetime.fromtimestamp()</code> return a naive <code>datetime</code> object though it has a well-defined input?</p>
<p><strong>MWE</strong></p>
<pre class="lang-py prettyprint-override"><code>from datetime import datetime, timezone
timestamp = 0
# output: "1970-01-01 00:00:00+00:00", i.e. providing the timezone information,
# the resulting datetime is timezone-aware and accurate
print(datetime.fromtimestamp(timestamp, tz=timezone.utc))
# output: "1970-01-01 01:00:00" (for me running it in CET+0100 timezone), i.e.
# the interpretation is aware of my local time shift, but the resulting datetime
# is naive though it could be timezone-aware and thus not well-defined anymore
#
# I would have wished for/expected: "1970-01-01 01:00:00+01:00"
print(datetime.fromtimestamp(timestamp))
</code></pre>
<p><strong>Why do I care?</strong>
The point is that we loose information in a dangerous way, i.e. we switch from a well-defined object to an object that is only well-defined if we know the timezone of the PC it has been read in. Though it could do better, imo. The way it is implemented, it is easy to mess things up without recognizing it.</p>
<p>But maybe I got the whole concept wrong :) That is why I am asking...</p>
|
<python><datetime><timestamp><timezone>
|
2023-02-07 04:53:21
| 0
| 2,201
|
matheburg
|
75,369,034
| 3,793,935
|
None Exception rasied in try except block
|
<p>I use a simple function:</p>
<pre><code>def is_float(value):
try:
float(value) #float(value if value else "")
return True
except ValueError:
return False
</code></pre>
<p>to check if an value is float or not.
Now, even though the check is in an try except block, this error is raised if the value is None:</p>
<pre><code>2023-02-06 09:47:27,021 app - ERROR:Exception ....
TypeError: float() argument must be a string or a number, not 'NoneType'.
</code></pre>
<p>Can someone explain why?
If you want to try it yourself, just execute the function with a None value and it will throw.</p>
|
<python><python-3.x>
|
2023-02-07 04:50:53
| 2
| 499
|
user3793935
|
75,368,963
| 1,361,802
|
Call overridden base class method without triggering the base class decorator
|
<p>I have a base class like</p>
<pre><code>class BaseTest:
@setup_test(param='foo')
def test_something():
do stuff
</code></pre>
<p>I now want to override the param to the decorator</p>
<pre><code>class NewTest:
@setup_test(param='different value')
def test_something():
super().test_something()
</code></pre>
<p>The trouble is when I call <code>super().test_something()</code> it will call <code>BaseTest.test_something</code> wrapped with <code>@setup_test(param='foo')</code> which does some bootstrapping that will overwrite what was done in <code>@setup_test(param='different value')</code>.</p>
<p>I need to directly call the undecorated <code>BaseTest.test_something</code></p>
|
<python><inheritance><decorator><python-decorators>
|
2023-02-07 04:32:50
| 1
| 8,643
|
wonton
|
75,368,945
| 13,316,831
|
VSCode requires me to re-select my python interpreter each time it starts
|
<p>[edited!]
Everytime I start Microsoft Visual Code, I get the following alert:</p>
<p><a href="https://i.sstatic.net/11uA1.png" rel="noreferrer"><img src="https://i.sstatic.net/11uA1.png" alt="enter image description here" /></a></p>
<p>This behavior started a few days ago (after a windows's update). I can select the python interpreter and after that, everything works just fine. From within vscode, I can open a terminal in my virtual environment and I can launch the debugger for django.</p>
<p><a href="https://i.sstatic.net/tjgYX.png" rel="noreferrer"><img src="https://i.sstatic.net/tjgYX.png" alt="enter image description here" /></a></p>
<p>The problem is that once I quit vscode, it forgets. Next time I start it up, I have to repeat the process. I have to do it every time.</p>
<p>My environment is:</p>
<p>Windows 11
wsl2
Ubuntu 22.04
pyenv (python 3.9.15 selected)
poetry</p>
<p>I've tried the following:</p>
<ol>
<li>Researched issue.</li>
<li>Tried Python: Clear Cache</li>
<li>Rollback of Python extension to version 2021-02. Restored to latest.</li>
</ol>
<p>I'm out of ideas at this point. Is this a configuration issue? Any other ideas on how I can resolve this? This may be an extension issue, but I want to make sure I'm not doing something incorrect with visual code.</p>
|
<python><visual-studio-code>
|
2023-02-07 04:24:56
| 1
| 567
|
Mark Ryan
|
75,368,928
| 1,096,949
|
unable to install mkl mkl-service using conda in docker
|
<p>I have docker file like below:</p>
<pre><code>FROM continuumio/miniconda3
RUN conda update -n base -c defaults conda
RUN conda create -c conda-forge -n pymc3_env pymc3 numpy theano-pymc mkl mkl-service
COPY ./src /app
WORKDIR /app
CMD ["conda", "run", "-n", "pymc3_env", "python", "ma.py"]
</code></pre>
<p>I get the following error:</p>
<pre><code>------
> [3/5] RUN conda create -c conda-forge -n pymc3_env pymc3 numpy theano-pymc mkl mkl-service:
#0 0.400 Collecting package metadata (current_repodata.json): ...working... done
#0 9.148 Solving environment: ...working... failed with repodata from current_repodata.json, will retry with next repodata source.
#0 9.149 Collecting package metadata (repodata.json): ...working... done
#0 45.81 Solving environment: ...working... failed
#0 45.82
#0 45.82 PackagesNotFoundError: The following packages are not available from current channels:
#0 45.82
#0 45.82 - mkl-service
#0 45.82 - mkl
#0 45.82
#0 45.82 Current channels:
#0 45.82
#0 45.82 - https://conda.anaconda.org/conda-forge/linux-aarch64
#0 45.82 - https://conda.anaconda.org/conda-forge/noarch
#0 45.82 - https://repo.anaconda.com/pkgs/main/linux-aarch64
#0 45.82 - https://repo.anaconda.com/pkgs/main/noarch
#0 45.82 - https://repo.anaconda.com/pkgs/r/linux-aarch64
#0 45.82 - https://repo.anaconda.com/pkgs/r/noarch
#0 45.82
#0 45.82 To search for alternate channels that may provide the conda package you're
#0 45.82 looking for, navigate to
#0 45.82
#0 45.82 https://anaconda.org
#0 45.82
#0 45.82 and use the search bar at the top of the page.
#0 45.82
#0 45.82
------
failed to solve: executor failed running [/bin/sh -c conda create -c conda-forge -n pymc3_env pymc3 numpy theano-pymc mkl mkl-service]: exit code: 1
</code></pre>
<p>Can anybody help me to understand why conda could not find <code>mkl</code> and <code>mkl-service</code> in <code>conda-forge</code> channel and what do I need to resolve this?</p>
<p>I am using macos as a host, if it is any concern.</p>
<p>Thanks in advance for any help.</p>
|
<python><linux><docker><anaconda><conda>
|
2023-02-07 04:20:39
| 1
| 655
|
MD. Jahidul Islam
|
75,368,912
| 13,176,726
|
Fixing a NoReverseMatch in a Django Project for Registration
|
<p>Hi I keep getting NoReverseMatch at /users/register/
however I am have followed the step by step for fixing this error:</p>
<p>Here is the urls.py</p>
<pre><code>app_name = 'tac'
urlpatterns = [
path('terms-and-conditions/', TermsAndConditionsView.as_view(), namespace='terms_and_conditions'),
path('user-agreement/', UserAgreementView.as_view(), namespace='user_agreement'),
]
</code></pre>
<p>Here is the register.html that is causing the error:</p>
<pre><code><label class="form-check-label" for="terms_and_conditions">I agree to the <a href="{% url 'tac:terms_and_conditions' %}">terms and conditions</a>
</label>
</code></pre>
<p>Here is the traceback error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\User\Desktop\Project\users\views.py", line 34, in register
return render(request, 'users/register.html', {'form': form})
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\shortcuts.py", line 24, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\backends\django.py", line 62, in render
return self.template.render(context)
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 175, in render
return self._render(context)
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 167, in _render
return self.nodelist.render(context)
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 966, in render_annotated
return self.render(context)
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\defaulttags.py", line 472, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\urls\base.py", line 82, in reverse
raise NoReverseMatch("%s is not a registered namespace" % key)
django.urls.exceptions.NoReverseMatch: 'tac' is not a registered namespace
[06/Feb/2023 23:11:00] "GET /users/register/ HTTP/1.1" 500 126759
</code></pre>
<p>here is the main urls.py</p>
<pre><code> path('tac/', include('tac.urls'), ),
</code></pre>
<p>it is also added in the settings INSTALLED_APPS</p>
<p>My question:
How can I fix this error and why is it appearing?</p>
<p>Thanks</p>
|
<python><django>
|
2023-02-07 04:15:35
| 1
| 982
|
A_K
|
75,368,897
| 17,696,880
|
How to place within a list the elements captured by capture groups within a string?
|
<pre><code>import re
input_text = "((PERS) Tomás), ((PERS) Kyara Gomez) y ((PERS) Camila) fueron a ((VERB) caminar) y ((VERB) saltar) ((PL_ADVB) en la montaña)(2023_-_02_-_05(00:00 am))((PL_ADVB) ((NOUN)en el parque amplio y naranja) por el otoño)"
#Initialize empty sub-lists
list_of_persons, list_of_actions_or_verbs, list_of_where_happens, list_of_when_happens = [], [], [], []
#patterns with capture groups:
capture_pattern_persons = r"\(\(PERS\)" + r'((?:[\w,;.]\s*)+)' + r"\)"
capture_pattern_actions_or_verbs = r"\(\(VERB\)" + r'((?:[\w,;.]\s*)+)' + r"\)"
capture_pattern_about_where_happens = r"\(\(PL_ADVB\)" + r'((?:[\w,;.()]\s*)+)' + r"\)"
capture_pattern_about_when_happens = r"\((\d*_-_\d{2}_-_\d{2}\s*\(\d{2}:\d{2}\s*(?:am|pm)\))\)"
#stock order reference --> [ ["(PERS) )"], ["(VERB) )"], ["(YYYY_-_MM_-_DD hh:mm am or pm)"], ["(PL_ADVB) )"] ]
info_list = [ [], [], [], [] ] # Initialize the empty list of list
#adds the elements captured with the patterns in each of the lists contained in the main list
#I add the lists that should already be complete to the main list
info_list.append(list_of_persons)
info_list.append(list_of_actions_or_verbs)
info_list.append(list_of_where_happens)
info_list.append(list_of_when_happens)
print(repr(info_list)) #print the output main list with the elements in the lists
</code></pre>
<p><code>capture_pattern_persons</code> captures the elements of the first sub-list</p>
<p><code>capture_pattern_actions_or_verbs</code> captures the elements of the first sub-list</p>
<p><code>capture_pattern_about_where_happens</code> captures the elements of the first sub-list</p>
<p><code>capture_pattern_about_when_happens</code> captures the elements of the first sub-list</p>
<p>After adding all the elements, the list should look like this when you print it to control it</p>
<pre><code>[ ["Tomás", "Kyara Gomez", "Camila"], ["caminar", "saltar"], ["2023_-_02_-_05(00:00 am)"], ["en la montaña", "((NOUN)en el parque amplio y naranja) por el otoño"] ]
</code></pre>
|
<python><python-3.x><regex><list><regex-group>
|
2023-02-07 04:12:18
| 1
| 875
|
Matt095
|
75,368,892
| 3,763,616
|
How to make a new date column off of a integer representation using python polars?
|
<p>I have a python polars dataframe that is quite large where Pandas runs into memory errors. I want to use python polars but am running into an issue of taking a integer representation of date to make two new columns: PeriodDate, and LagDate. I can do this on a sample in Pandas using the following:</p>
<pre><code>df['PeriodDate'] = pd.to_datetime(df['IntegerDate'],format='%Y%m')
df['LaggedDate'] = df['PeriodDate'] - pd.DateOffset(months=1)
</code></pre>
<p>I have tried to do the following:</p>
<pre><code>df.with_columns(
pl.col('IntegerDate').str.strptime(pl.Datetime,"%Y%m")
)
SchemaError: Series of dtype: Int64 != Utf8.
</code></pre>
<p>For reference the 'IntegerDate' column is of the format: 202005, 202006, ...etc</p>
<p>I haven't been able to find good examples of how to do this in polars so any help would be greatly appreciated.</p>
<p>Thanks!</p>
|
<python><pandas><python-polars>
|
2023-02-07 04:11:07
| 1
| 489
|
Drthm1456
|
75,368,713
| 18,096,205
|
[Selenium]I want to save all images from my pinterest boards
|
<p>I would like to save all images from a pinterest board. I am having trouble writing the process to go back to the board and go to the next image after downloading the image, and I would appreciate it if you could help me out.</p>
<p>Board example:<a href="https://www.pinterest.jp/aku_ma/%E3%82%A2%E3%83%8B%E3%83%A1%E3%82%A2%E3%82%A4%E3%82%B3%E3%83%B3/" rel="nofollow noreferrer">https://www.pinterest.jp/aku_ma/%E3%82%A2%E3%83%8B%E3%83%A1%E3%82%A2%E3%82%A4%E3%82%B3%E3%83%B3/</a></p>
<ol>
<li>Login</li>
<li>Access the board ←I have done this.</li>
<li>Access the page of the image in the board</li>
<li>Press the download button and save to the specified path</li>
<li>Return to the board and access the page for the next image</li>
</ol>
<h3>ボードにアクセスするまでのコード</h3>
<pre><code>import os
import selenium
import time
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
url ='https://www.pinterest.jp/aku_ma/%E3%82%A2%E3%83%8B%E3%83%A1%E3%82%A2%E3%82%A4%E3%82%B3%E3%83%B3/'
profilefolder = '--user-data-dir=' + '/Users/t/Library/Application Support/Google/Chrome/Default'
emailAdress = 'xxxx@gmail.com'
passwordNumber='xxxx'
foldername="/Users/t/Desktop/koreanLikeImages"
speed = 1
options = Options()
# options.add_argument('--headless')
DRIVER_PATH = "./chromedriver" # My ChromeDrivers Path
driver = webdriver.Chrome(options=options)
driver.get(url)
loginButton = driver.find_element(By.CSS_SELECTOR, "div[data-test-id='login-button']")
loginButton.click()#Push at login button
time.sleep(1)
#Enter ID,Pass
email = driver.find_element(By.ID,"email")
email.send_keys(emailAdress)
password = driver.find_element(By.ID,"password")
password.send_keys(passwordNumber)
# Push The Red Login Button
redLoginButton = driver.find_element(By.CLASS_NAME, "SignupButton")
redLoginButton.click()
time.sleep(3)
driver.get(url)
</code></pre>
|
<python><selenium><selenium-webdriver><web-scraping>
|
2023-02-07 03:34:38
| 1
| 349
|
Tdayo
|
75,368,589
| 4,755,567
|
pySpark check Dataframe contains in another Dataframe
|
<p>Assume I have two Dataframes:</p>
<p>DF1: DATA1, DATA1, DATA2, DATA2</p>
<p>DF2: DATA2</p>
<p>I want to exclude all existence of data in DF2 while keeping duplicates in DF1, what should I do?</p>
<p>Expected result: DATA1, DATA1</p>
|
<python><apache-spark><pyspark>
|
2023-02-07 03:07:00
| 2
| 549
|
TommyQu
|
75,368,573
| 5,617,371
|
How to determine the operating system of google compute engine is linux or windows?
|
<p>I use python sdk of gcp to get compute engine list and I want to judge the the operating system of google compute engine is linux or windows, but there is no any operating system informatioin in all fields of compute engine.</p>
<pre><code>import sys
import json
from google.oauth2 import service_account
from google.cloud import compute_v1
class VM:
def __init__(self, cred_json_path):
self.cred_json_path = cred_json_path
self.credentials = self.create_credentials()
self.page_size = 500
def create_credentials(self):
return service_account.Credentials.from_service_account_file(self.cred_json_path)
def list_instance(self):
compute_client = compute_v1.InstancesClient(credentials=self.credentials)
results = []
for _, instances in compute_client.aggregated_list(request={"project": self.credentials.project_id, "max_results": self.page_size}):
for instance in instances.instances:
# TODO
# I want to judge the operating system information for every instance is linux or windows here.
results.append(instance)
return results
def show(self):
instance_list = self.list_instance()
for instance in instance_list:
print(json.dumps(instance))
def main(cred_json_path):
vm = VM(cred_json_path)
vm.show()
if __name__ == '__main__':
main(sys.argv[1])
</code></pre>
<p>Is there any solution? Thanks.</p>
|
<python><google-cloud-platform>
|
2023-02-07 03:02:21
| 1
| 1,215
|
leo
|
75,368,552
| 2,893,585
|
How can I clean this string and leave only text (Python)
|
<p>I have the following string in python:</p>
<pre><code>"\n[[[\"guns\",0,[143,362,396,357],{\"zf\":33,\"zl\":8,\"zp\":{\"gs_ss\":\"1\"}}],[\"china chinese spy balloon\",0,[143,362,396,357],{\"zf\":33,\"zl\":8,\"zp\":{\"gs_ss\":\"1\"}}],[\"aris hampers grand rapids\",0,[143,362,396,357],{\"zf\":33,\"zl\":8,\"zp\":{\"gs_ss\":\"1\"}}],[\"mountain lion p 22\",0,[143,362,396,357],{\"zf\":33,\"zl\":8,\"zp\":{\"gs_ss\":\"1\"}}],[\"real estate housing market\",0,[143,362,396,357],{\"zf\":33,\"zl\":8,\"zp\":{\"gs_ss\":\"1\"}}],[\"hunter biden\",46,[143,362,396,357],{\"lm\":[],\"zf\":33,\"zh\":\"Hunter Biden\",\"zi\":\"American attorney\",\"zl\":8,\"zp\":{\"gs_ssp\":\"eJzj4tLP1TcwycrOK88xYPTiySjNK0ktUkjKTEnNAwBulQip\"},\"zs\":\"https://encrypted-tbn0.gstatic.com/images?q\\u003dtbn:ANd9GcQaO4eyFc6sDCa7A26Y_9g71clgC0Ot11Elt0KxAFiQo0Ey7Tp69FWxS8o\\u0026s\\u003d10\"}],[\"maui firefighter tre evans dumaran\",0,[143,362,396,357],{\"zf\":33,\"zl\":8,\"zp\":{\"gs_ss\":\"1\"}}],[\"pope francis benedict\",0,[143,362,396,357],{\"zf\":33,\"zl\":8,\"zp\":{\"gs_ss\":\"1\"}}],[\"coast guard rescue stolen boat\",0,[143,362,396,357],{\"zf\":33,\"zl\":8,\"zp\":{\"gs_ss\":\"1\"}}],[\"lauren boebert\",46,[143,362,396,357],{\"lm\":[],\"zf\":33,\"zh\":\"Lauren Boebert\",\"zi\":\"United States Representative\",\"zl\":8,\"zp\":{\"gs_ssp\":\"eJzj4tVP1zc0zDIqMzCrMCswYPTiy0ksLUrNU0jKT01KLSoBAJDsCeg\"},\"zs\":\"https://encrypted-tbn0.gstatic.com/images?q\\u003dtbn:ANd9GcS1qLJyZQJkVxsOTuP4gnADPLG5oBWe0LWSFClElzhcVrwVCfnNa_s64Zs\\u0026s\\u003d10\"}]],{\"ag\":{\"a\":{\"8\":[\"Trending searches\"]}}}"
</code></pre>
<p>how can I clean it using python so that it only outputs the text:</p>
<p>"guns",
"china chinese spy balloon",
"aris hampers grand rapids",
"mountain lion p 22",
....</p>
|
<python>
|
2023-02-07 02:58:11
| 1
| 438
|
Sundios
|
75,368,490
| 8,571,154
|
Keras LSTM None value output shape
|
<p>this is my data <code>X_train</code> prepared for LSTM of shape (7000, 2, 200)</p>
<pre><code>[[[0.500858 0. 0.5074856 ... 1. 0.4911533 0. ]
[0.4897923 0. 0.48860878 ... 0. 0.49446714 1. ]]
[[0.52411383 0. 0.52482396 ... 0. 0.48860878 1. ]
[0.4899698 0. 0.48819458 ... 1. 0.4968341 1. ]]
...
[[0.6124623 1. 0.6118705 ... 1. 0.6328777 0. ]
[0.6320492 0. 0.63512635 ... 1. 0.6960175 0. ]]
[[0.6118113 1. 0.6126989 ... 0. 0.63512635 1. ]
[0.63530385 1. 0.63595474 ... 1. 0.69808865 0. ]]]
</code></pre>
<p>I create my sequential model</p>
<pre><code>model = Sequential()
model.add(LSTM(units = 50, activation = 'relu', input_shape = (X_train.shape[1], 200)))
model.add(Dropout(0.2))
model.add(Dense(1, activation = 'linear'))
model.compile(loss = 'mean_squared_error', optimizer = 'adam')
</code></pre>
<p>Then I fit my model:</p>
<pre><code>history = model.fit(
X_train,
Y_train,
epochs = 20,
batch_size = 200,
validation_data = (X_test, Y_test),
verbose = 1,
shuffle = False,
)
model.summary()
</code></pre>
<p>And at the end I can see something like this:</p>
<pre><code> Layer (type) Output Shape Param #
=================================================================
lstm_16 (LSTM) (None, 2, 50) 50200
dropout_10 (Dropout) (None, 2, 50) 0
dense_10 (Dense) (None, 2, 1) 51
</code></pre>
<p>Why does it say that output shape have a <code>None</code> value as a first element? Is it a problem? Or it should be like this? What does it change and how can I change it?</p>
<p>I will appreciate any help, thanks!</p>
|
<python><tensorflow><keras><lstm>
|
2023-02-07 02:45:45
| 1
| 893
|
Adrian Kurzeja
|
75,368,450
| 112,871
|
Bin and aggregate with `seaborn.objects`
|
<p>Is there a way to both bin and aggregate (with some other function than <code>count</code>) in <code>seaborn.objects</code>? I'd like to compute the mean per bin and right now I'm using the following:</p>
<pre class="lang-py prettyprint-override"><code>import seaborn.objects as so
import pandas as pd
import seaborn as sns
df = sns.load_dataset("penguins")
df2 = (
df.groupby(pd.cut(df["bill_length_mm"], bins=30))[["bill_depth_mm"]]
.mean()
)
df2["bill_length_mm"] = [x.mid for x in df2.index]
p = so.Plot(df2, x="bill_length_mm", y="bill_depth_mm").add(so.Bars())
p
</code></pre>
|
<python><plot><seaborn><visualization><seaborn-objects>
|
2023-02-07 02:35:55
| 1
| 27,660
|
nicolaskruchten
|
75,368,373
| 5,383,071
|
How to integrate a progress bar in a pandas iterrows for loop
|
<p>I acknowledge that using iterrows in pandas is bad practice, but this is what I'm dealing with from previous projects leftovers...</p>
<p>I am using a for loop like so to iterate through a pandas data frame for some data manipulation (on mobile so forgive my poor formatting) -</p>
<pre><code>for index, row in df_temp.iterrows
# do stuff
</code></pre>
<p>I've since wanted to wrap a progress bar feature around this loop to track its progress (given the amount of data it consumes). I have found something like tqdm but its use case is rather simplified, is there a neat way to restructure my for loop so that a progress bar feature can be slotted in?</p>
<p>Tried simply taking a counter of the loop and keeping track of that during each iteration, but that seems counter-intuitive..</p>
|
<python><pandas><dataframe><for-loop><progress-bar>
|
2023-02-07 02:15:29
| 2
| 656
|
2Xchampion
|
75,368,170
| 12,695,210
|
float32 vs. float64 python checking equality
|
<p>In the below code, checking equality between float64 fails due to binary representation issue, as I would expect. However, I don't understand why float32 as no problem with this. My understanding is that it should be susceptable to the same binary representation issues, and has precision much lower than 0.0003. Why do the below equality checks pass for float32?</p>
<pre><code>import numpy as np
x = np.float64(0.0003) # 0.003
y = np.float64(0.0001 * 3) # 0.00030000000000000003
assert x == y # fail
x = x.astype(np.float32) # 0.0003
y = y.astype(np.float32) # 0.0003
assert x == y # okay
x = np.float32(0.0003) # 0.003
y = np.float32(0.0001 * 3) # 0.003
assert x == y # okay
</code></pre>
|
<python><binary><precision>
|
2023-02-07 01:30:40
| 2
| 695
|
Joseph
|
75,368,099
| 14,109,040
|
Finding an element and clicking on it to navigate to another webpage using selenium
|
<p>I'm trying to use selenium to open up this webpage (<a href="https://app.powerbi.com/view?r=eyJrIjoiMzE2ZDIyN2YtODY1Yy00ZGY0LWE4YTktNDcxOTcwYWQyMjM5IiwidCI6IjcyMmVhMGJlLTNlMWMtNGIxMS1hZDZmLTk0MDFkNjg1NmUyNCJ9" rel="nofollow noreferrer">https://app.powerbi.com/view?r=eyJrIjoiMzE2ZDIyN2YtODY1Yy00ZGY0LWE4YTktNDcxOTcwYWQyMjM5IiwidCI6IjcyMmVhMGJlLTNlMWMtNGIxMS1hZDZmLTk0MDFkNjg1NmUyNCJ9</a>) and click on the Tram icon to navigate to the web page I want to scrape.</p>
<p>This is what I've tried up to now</p>
<pre><code>from selenium import webdriver
driver=webdriver.Chrome()
driver.get("https://app.powerbi.com/view?r=eyJrIjoiMzE2ZDIyN2YtODY1Yy00ZGY0LWE4YTktNDcxOTcwYWQyMjM5IiwidCI6IjcyMmVhMGJlLTNlMWMtNGIxMS1hZDZmLTk0MDFkNjg1NmUyNCJ9")
driver.maximize_window()
x=driver.find_element("class name", "imageBackground")
print(x)
#driver.find_element("class name", "imageBackground").click()
</code></pre>
<p>However, the element returns none. I'm not sure how to find the element and click the div to navigate to the next page as well.</p>
|
<python><selenium><web-scraping>
|
2023-02-07 01:17:44
| 1
| 712
|
z star
|
75,367,832
| 744,351
|
How can I get a Containerized Jupyter Notebook to run code within Azure ML
|
<p>I'm not an expert in Azure ML but I'll give as much detail as I can or understand. The task I've been given is probably overkill for Azure Machine Learning, but I have a Jupyter Notebook that I have parameterized with Papermill. There is NO training needed. It reads data from varying sources, processes it with parameters, generates and output. I want to pass it parameters to produce said output. It works manually in a Compute Instance. Now I need to get it working in Azure ML in an automated fashion.</p>
<p>My plan is to create a custom docker image, store it in ACR, and then when ready to deploy: create an AML Envrionment, a Component, and an AML Pipeline that will call the component which will in turn all the executing script within the AML Environment container the custom container image.</p>
<p>I successfully created an AML docker image using a pre-build AML docker image. I can create a container for AML but those are usually for models and deployments which usually use pre-built docker images that AML have hooks into. So... is it possible to containerize my Jupyter Notebook into a docker container which can then be called from an AML pipeline? Do I even need to use the pre-build docker images? Do I even need the component and just call the container service directly from the AML pipeline?</p>
<p>The end user wants to schedule multiple jobs to pass varying arguments.</p>
<p>This is my Dockerfile:</p>
<pre><code>FROM mcr.microsoft.com/azureml/minimal-ubuntu20.04-py38-cpu-inference:latest
ENV LANG=C.UTF-8 LC_ALL=C.UTF-8
ENV DEBIAN_FRONTEND=noninteractive
ENV CONDA_ENV_DIR=/opt/miniconda/envs
# Switch to root to install apt packages
USER root:root
RUN apt-get update -y && apt-get install -y --no-install-recommends \
build-essential \
curl \
gnupg \
gnupg1 \
gnupg2 \
python3-dev \
python3-pip \
python3-setuptools \
tzdata \
curl \
&& rm -rf /var/lib/apt/lists/* \
&& ln -s /usr/bin/python3 /usr/local/bin/python \
&& pip3 install --upgrade pip
USER dockeruser
# Install python dependencies
COPY Docker-environment.yml /tmp/conda.yaml
RUN conda env create -n userenv -f /tmp/conda.yaml
#&& \
# export SERVER_VERSION=$(pip show azureml-inference-server-http | grep Version | sed -e 's/.*: //') && \
# $CONDA_ENV_DIR/userenv/bin/pip install azureml-inference-server-http==$SERVER_VERSION
# Update environment variables
ENV AML_APP_ROOT=/app
ENV AZUREML_ENTRY_SCRIPT=run_papermill.py
ENV AZUREML_CONDA_ENVIRONMENT_PATH="$CONDA_ENV_DIR/userenv"
ENV PATH="$AZUREML_CONDA_ENVIRONMENT_PATH/bin:$PATH"
ENV LD_LIBRARY_PATH="$AZUREML_CONDA_ENVIRONMENT_PATH/lib:$LD_LIBRARY_PATH"
# Copy code
COPY src $AML_APP_ROOT
ENV WORKER_TIMEOUT=300
</code></pre>
<p><a href="https://i.sstatic.net/vU2AP.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/vU2AP.png" alt="Picture of Src folder" /></a></p>
<p>"main.ipynb" Jupyter Notebook runs just fine on its own. "papermill.ipynb" Jupyter Notebook is a simple wrapper that has parameters to pass to the main jupyter notebook file. And "run_papermill.py" is another wrapper that actually needs to be called with parameters.</p>
|
<python><azure><docker><jupyter-notebook><azure-machine-learning-service>
|
2023-02-07 00:19:19
| 1
| 1,791
|
Antebios
|
75,367,828
| 4,700,367
|
RuntimeError: reentrant call inside <_io.BufferedWriter name='<stdout>'>
|
<p>I'm writing a program which starts one thread to generate "work" and add it to a queue every N seconds. Then, I have a thread pool which processes items in the queue.</p>
<p>The program below works perfectly fine, until I comment out/delete line #97 (<code>time.sleep(0.5)</code> in the main function). Once I do that, it generates a RuntimeError which attempting to gracefully stop the program (by sending a SIGINT or SIGTERM to the main process). It even works fine with an extremely small sleep like 0.1s, but has an issue with none at all.</p>
<p>I tried researching "reentrancy" but it went a bit over my head unfortunately.</p>
<p>Can anyone help me to understand this?</p>
<p><strong>Code:</strong></p>
<pre class="lang-py prettyprint-override"><code>import random
import signal
import threading
import time
from concurrent.futures import Future, ThreadPoolExecutor
from datetime import datetime
from queue import Empty, Queue, SimpleQueue
from typing import Any
class UniqueQueue:
"""
A thread safe queue which can only ever contain unique items.
"""
def __init__(self) -> None:
self._q = Queue()
self._items = []
self._l = threading.Lock()
def get(self, block: bool = False, timeout: float | None = None) -> Any:
with self._l:
try:
item = self._q.get(block=block, timeout=timeout)
except Empty:
raise
else:
self._items.pop(0)
return item
def put(self, item: Any, block: bool = False, timeout: float | None = None) -> None:
with self._l:
if item in self._items:
return None
self._items.append(item)
self._q.put(item, block=block, timeout=timeout)
def size(self) -> int:
return self._q.qsize()
def empty(self) -> bool:
return self._q.empty()
def stop_app(sig_num, sig_frame) -> None:
# global stop_app_event
print("Signal received to stop the app")
stop_app_event.set()
def work_generator(q: UniqueQueue) -> None:
last_execution = time.time()
is_first_execution = True
while not stop_app_event.is_set():
elapsed_seconds = int(time.time() - last_execution)
if elapsed_seconds <= 10 and not is_first_execution:
time.sleep(0.5)
continue
last_execution = time.time()
is_first_execution = False
print("Generating work...")
for _ in range(100):
q.put({"n": random.randint(0, 500)})
def print_work(w) -> None:
print(f"{datetime.now()}: {w}")
def main():
# Create a work queue
work_queue = UniqueQueue()
# Create a thread to generate the work and add to the queue
t = threading.Thread(target=work_generator, args=(work_queue,))
t.start()
# Create a thread pool, get work from the queue, and submit to the pool for processing
pool = ThreadPoolExecutor(max_workers=20)
futures: list[Future] = []
while True:
print("Processing work...")
if stop_app_event.is_set():
print("stop_app_event is set:", stop_app_event.is_set())
for future in futures:
future.cancel()
break
print("Queue Size:", work_queue.size())
try:
while not work_queue.empty():
work = work_queue.get()
future = pool.submit(print_work, work)
futures.append(future)
except Empty:
pass
time.sleep(0.5)
print("Stopping the work generator thread...")
t.join(timeout=10)
print("Work generator stopped")
print("Stopping the thread pool...")
pool.shutdown(wait=True)
print("Thread pool stopped")
if __name__ == "__main__":
stop_app_event = threading.Event()
signal.signal(signalnum=signal.SIGINT, handler=stop_app)
signal.signal(signalnum=signal.SIGTERM, handler=stop_app)
main()
</code></pre>
|
<python><python-3.x><python-multithreading>
|
2023-02-07 00:18:54
| 1
| 438
|
Sam Wood
|
75,367,823
| 12,044,155
|
ValueError: Shapes (None,) and (None, 150, 150, 6) are incompatible
|
<p>I am building an image classification model using Keras, SGD, and Softmax activation. The training dataset consists of RGB images with dimensions of 512x384.</p>
<p>To do so, I have followed Keras "Getting Started" guide. However, when I tried to train the model, I got the error mentioned in the title. This is my code so far:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import tensorflow as tf
from tensorflow import keras
FOLDER_PATH = 'dataset'
dataset = keras.utils.image_dataset_from_directory(
FOLDER_PATH,
batch_size=64,
image_size=(512, 384)
)
# None x None x 3 -> Arbitrarily sized images with 3 channels
inputs = keras.Input(shape=(None, None, 3))
x = CenterCrop(height=150, width=150)(inputs)
x = Rescaling(scale= 1.0 / 255)(x)
outputs = layers.Dense(6, activation="softmax")(x)
model = keras.Model(inputs=inputs, outputs=outputs)
model.compile(
optimizer=keras.optimizers.SGD(learning_rate=0.01),
loss=keras.losses.CategoricalCrossentropy()
)
model.fit(dataset, epochs=3)
</code></pre>
<p>This is the model's summary:</p>
<pre><code>Model: "model_6"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_8 (InputLayer) [(None, None, None, 3)] 0
center_crop_7 (CenterCrop) (None, 150, 150, 3) 0
rescaling_7 (Rescaling) (None, 150, 150, 3) 0
dense_7 (Dense) (None, 150, 150, 6) 24
=================================================================
Total params: 24
Trainable params: 24
Non-trainable params: 0
_________________________________________________________________
</code></pre>
<p>I have also checked the shape of my data:</p>
<pre class="lang-py prettyprint-override"><code>for data, labels in dataset:
print(data.shape) # (64, 512, 384, 3)
print(data.dtype) # <dtype: 'float32'>
print(labels.shape) # (64,)
print(labels.dtype) # <dtype: 'int32'>
</code></pre>
<p>So, how can I fix this? I wonder if I have made some mistake in the data preprocessing pipeline, or if the data I am using is somehow incompatible with the SGD optimizer.</p>
|
<python><tensorflow><machine-learning><keras>
|
2023-02-07 00:18:05
| 1
| 2,692
|
Allan Juan
|
75,367,781
| 881,150
|
Get Blob Storage version enabled setting using Python SDK
|
<p>when running the azure CLI command:</p>
<pre><code>az storage account blob-service-properties show --account-name sa36730 --resource-group rg-exercise1
</code></pre>
<p>The output json contains the filed <code>isVersioningEnabled</code>.
I am trying to get this field using python sdk.</p>
<p>I wrote this code but the output doesnt contain the version enabled information.</p>
<pre><code>def blob_service_properties():
connection_string = "<connection string>"
# Instantiate a BlobServiceClient using a connection string
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
properties = blob_service_client.get_service_properties()
pprint.pprint(properties)
# [END get_blob_service_properties]
</code></pre>
<p>My output looks like:</p>
<pre><code>{'analytics_logging': <azure.storage.blob._models.BlobAnalyticsLogging object at 0x7ff0f8b7c340>,
'cors': [<azure.storage.blob._models.CorsRule object at 0x7ff1088b61c0>],
'delete_retention_policy': <azure.storage.blob._models.RetentionPolicy object at 0x7ff0f8b9b1c0>,
'hour_metrics': <azure.storage.blob._models.Metrics object at 0x7ff0f8b9b700>,
'minute_metrics': <azure.storage.blob._models.Metrics object at 0x7ff0f8b9b3d0>,
'static_website': <azure.storage.blob._models.StaticWebsite object at 0x7ff0f8ba5c10>,
'target_version': None}
</code></pre>
<p>Is there a way to get the versioning information using Python SDK for storage blob?</p>
|
<python><azure>
|
2023-02-07 00:07:54
| 2
| 1,114
|
abhinav singh
|
75,367,749
| 6,202,327
|
Scipy/numpy how to compute function as vector?
|
<p>I am trying to use <code>solve_bvp</code> from scipy. To that effect I need to create the RHS function, which on paper I ahve as</p>
<p><code>(1+y^2) / 2(1-x)</code></p>
<p>I am not sure how to define the function that takes the vecotrs as inputs and rewrite it for my case.</p>
<p>I.e. I am trying to rewrite the function <code>fun_measles</code> <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_bvp.html" rel="nofollow noreferrer">in this tutorial</a> into my function.</p>
<pre><code>mu = 0.02
l = 0.0279
eta = 0.01
def fun_measles(x, y):
beta = 1575 * (1 + np.cos(2 * np.pi * x))
return np.vstack((
mu - beta * y[0] * y[2],
beta * y[0] * y[2] - y[1] / l,
y[1] / l - y[2] / eta
))
</code></pre>
|
<python><numpy><math><scipy><differential-equations>
|
2023-02-07 00:01:22
| 2
| 9,951
|
Makogan
|
75,367,671
| 3,533,030
|
StableBaselines3 / steps vs. total_timesteps vs. number of times environment is solved during training
|
<p><code>model.learn(total_timesteps=20)</code> takes much longer than I expected, so I'm trying to understand if I should:</p>
<ol>
<li>Be frugal with time steps</li>
<li>Speed up my environment <code>env.step(action)</code></li>
<li>Train even more time steps</li>
</ol>
<hr />
<p>Consider a simple environment:</p>
<ul>
<li>There are (x3) steps until <code>done=True</code></li>
</ul>
<p>I expected <code>model.learn(total_timesteps=20)</code> to take either:</p>
<ol>
<li>20 x 3 steps = 20 iterations (equiv. to 20 episodes)</li>
<li>20 total steps (or perhaps 18 or 21 steps) = (x6) or (x7) episodes</li>
</ol>
<hr />
<p>This is a similar question and has no answer: <a href="https://stackoverflow.com/questions/72265349/stable-baselines3-package-model-learn-function-how-do-total-timesteps-and-n">Stackoverflow question A</a>.</p>
<p>This answer (<a href="https://stackoverflow.com/questions/56700948/understanding-the-total-timesteps-parameter-in-stable-baselines-models">Stackoverflow question B</a>) implies that this is truly the total number of steps for all iterations of the <code>env</code>. If this is the case, in my example above, it should run (x18) steps or (x6) times before halting. However, it takes far longer than that to complete (I have timed it!). <strong>Why is this the case?</strong></p>
<ul>
<li>What is the right interpretation of <code>total_timesteps</code>?</li>
<li>Where is the documentation that describes this in detail (not here... <a href="https://stable-baselines3.readthedocs.io/en/master/modules/ppo.html" rel="nofollow noreferrer">link</a>)?</li>
</ul>
<hr />
<p>Example: inspired by Nicholas Renotte's tutorial <a href="https://www.youtube.com/redirect?event=video_description&redir_token=QUFFLUhqazRodnhxVXZGR1pGT1BJeld6akVWdEgzNlhTUXxBQ3Jtc0tsQk40c25lZzEtT2g1OTV6N09xbHU3MGRkR1czU2dwdFZ4TmdsVW1vSnpVNTNqV2UzSDlZdmI2bHJpYWJubFRwYVJESWhqVjJjLVhLQV9kM0JaeF8yNFIxcWxDd3pBcVpFRU5jcTVYb1hiTzJtY1hhZw&q=https%3A%2F%2Fgithub.com%2Fnicknochnack%2FReinforcementLearningCourse&v=Mut_u40Sqz4" rel="nofollow noreferrer">Project 3 - Custom Environment</a></p>
<p>In the example below, note that:</p>
<ol>
<li>Each environment can only execute precisely (x3) steps</li>
<li>The time required to run <code>episodes</code> is very, very small</li>
<li>The <code>total_timesteps</code> is the same as the number of loops of the <code>episodes</code></li>
<li>The summary of <code>iterations</code> and <code>time_elapsed</code> seem unrelated to the <code>total_timesteps</code></li>
</ol>
<p><strong>Environment Class</strong></p>
<pre><code>class ShowerEnv(Env):
listTemperatureKnob = (10, 30, 50)
shower_length = 3
def __init__(self):
self.action_space = Discrete(3)
self.observation_space = Box(low=np.array([0], dtype=np.float32), high=np.array([100], dtype=np.float32))
self.reset()
def step(self, action):
temperatureShowerHead = self.listTemperatureKnob[action]
self.state = temperatureShowerHead
self.shower_length -= 1
if self.state > 27 and self.state < 33:
reward =1
else:
reward = -1
if self.shower_length <= 0:
done = True
else:
done = False
# Apply temperature noise
#self.state += random.randint(-1,1)
# Set placeholder for info
info = {"temperatureShower":temperatureShowerHead}
obs = np.array([self.state], dtype=np.float32)
# Return step information
return obs, reward, done, info
def render(self):
pass
def reset(self):
self.state = self.listTemperatureKnob[0]
self.shower_length = 3
obs = np.array([self.state], dtype=np.float32)
return obs
env = ShowerEnv()
check_env(env, warn=True)
</code></pre>
<p><strong>Run (x5) Episodes</strong></p>
<pre><code>timeStart = time.time()
episodes = 5
for episode in range(1, episodes+1):
state = env.reset()
done = False
score = 0
while not done:
env.render()
action = env.action_space.sample()
n_state, reward, done, info = env.step(action)
score+=reward
print('Episode:{} Score:{}'.format(episode, score))
env.close()
timeEnd = time.time()
print("Elapsed Time: " + str(timeEnd- timeStart))
</code></pre>
<p><em>Time Elapsed: 0.000999</em></p>
<p><strong>Execute a <code>model</code> training</strong></p>
<pre><code>log_path = os.path.join('Training', 'Logs')
model = PPO("MlpPolicy", env, verbose=1, tensorboard_log=log_path)
timeStart = time.time()
model.learn(total_timesteps=5)
timeEnd = time.time()
print("Elapsed Time: " + str(timeEnd- timeStart))
</code></pre>
<p><strong>Output</strong></p>
<pre><code>Using cpu device
Wrapping the env with a `Monitor` wrapper
Wrapping the env in a DummyVecEnv.
Logging to Training\Logs\PPO_7
---------------------------------
| rollout/ | |
| ep_len_mean | 3 |
| ep_rew_mean | -1.14 |
| time/ | |
| fps | 1496 |
| iterations | 1 |
| time_elapsed | 1 |
| total_timesteps | 2048 |
---------------------------------
</code></pre>
<p><em>Time elapsed: 2.6916</em></p>
|
<python><reinforcement-learning><stable-baselines>
|
2023-02-06 23:43:20
| 1
| 449
|
user3533030
|
75,367,625
| 14,414,944
|
python-polars: is there an established way to construct a DataFrame with a custom Iterable?
|
<p>I'm trying out <code>polars</code> for the first time. I'm interested in using the lib to improve a developer API that (ironically) uses a Redis Cluster as its primary data layer. I'd like to implement something like <code>hybrid-streaming</code> for a custom <code>Iterable</code> over collections in the Redis Cluster. I do not know if this functionality is already roughly supported or not.</p>
<p>We currently abstract over Redis with something like the below for collection structures.</p>
<pre class="lang-py prettyprint-override"><code>def _keys(self)->Iterable[Tuple[K, bytes]]:
model_state_key = self.get_model_state_hash()
start = 0
while rkeys := self.store.zrange(model_state_key, start, start + self.buffer):
for rkey in rkeys:
yield (self.model_unhash(rkey), rkey) # unhash if supported by subclass
start += self.buffer
</code></pre>
<p>I'm aware that I can construct a <code>polars.DataFrame</code> with a <code>Sequence</code> and likewise implement a <code>Sequence</code> from my <code>Iterable</code>.</p>
<p>What I'm unsure of is whether this <code>Sequence</code> or the elements therein get read into memory all at once when <code>polars</code> constructs a <code>polars.DataFrame</code>. Will my <code>Iterable</code>'s members be kept out of program memory? Is there something related to the <code>hybrid-streaming</code> feature that will help me avoid this?</p>
|
<python><python-polars>
|
2023-02-06 23:36:04
| 0
| 1,011
|
lmonninger
|
75,367,602
| 7,984,318
|
How to convert a float date to days and hours
|
<p>I have a Dataframe ,you can have it ,by runnnig:</p>
<pre><code>import pandas as pd
from io import StringIO
df = """
case_id duration_time other_column
3456 1 random value 1
7891 3 ddd
1245 0 fdf
9073 null 111
"""
df= pd.read_csv(StringIO(df.strip()), sep='\s\s+', engine='python')
</code></pre>
<p>Now I first drop the null rows by using dropna function, then calculate the average value of the left duration_time as average_duration:</p>
<pre><code>average_duration=df.duration_time.duration_time.dropna.mean()
</code></pre>
<p>The output is average_duration:</p>
<pre><code>1.3333333333333333
</code></pre>
<p>My question is how can I convert the result to something similar as:</p>
<pre><code>average_duration = '1 day,8 hours'
</code></pre>
<p>Since 1.33 days is 1 day and 7.92 hours</p>
|
<python><pandas><dataframe><python-datetime>
|
2023-02-06 23:32:23
| 2
| 4,094
|
William
|
75,367,550
| 2,153,636
|
Appropriate python project setup for accessing paths relative to the project root folder out of a module in src
|
<p>Example project structure:</p>
<pre><code>|-setup.toml
|-README.md
|-tests/...
|-data/...
|-src/
|-package1
|-package2
|-module1.py
|-package3
|-subpackage4
|-module2.py
</code></pre>
<p>In reality, I have many more folders and files scattered around them and I need to be able to access <code>$ROOT/data/...</code> from most of them. Ideally, I wouldn't have to update numerous strings across the project every time I decide to move the file from one folder to another.</p>
<p>I can think of a number of solutions but none of them seem clean.</p>
<p>For example, I could <code>pip install -e</code> the package and have a module at the top level (just under <code>src/</code>) which would <code>import os</code> so I would just need to add <code>../data/</code> on top of that root. Then, I would import this module in all the other <code>py</code> files throughout the directory structure.</p>
<p>I think it would do the job but it feels very clumsy, surely there is a better way?</p>
<p>Looked through lots of documentation for setuptools, poetry etc. but none of the tutorials cover this trivial scenario. They are mostly concerned with dependencies and publishing to <code>PyPi</code>.</p>
<p>Is this still the way to do this in 2023?
<a href="https://stackoverflow.com/questions/25389095/python-get-path-of-root-project-structure">Python - Get path of root project structure</a></p>
|
<python><setuptools><python-packaging><python-poetry>
|
2023-02-06 23:22:43
| 0
| 3,316
|
rudolfovic
|
75,367,473
| 3,371,941
|
Comparing rows from a Pandas DataFrame depending on certain attribute
|
<p>The task is to compare two production lines A and B with respect to a performance indicator called OEE.
I suspect that there is an impact by the article and line, so I want to compare only articles that have been produced at least once on both lines (here: hammer, drill, pliers, widget).
This may later enable to tell if certain articles perform better on one of both lines.</p>
<p>I have managed by iterarion to mark only articles that have run on both lines at least once.
But I wonder: is there not a more elegant way to do it?</p>
<p>Interation is not considered the best way as I found out here:
<a href="https://www.stackoverflow.com/">https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas/55557758#55557758</a></p>
<p>But perhaps the DataFrame can be modified in a simpler way?</p>
<p><a href="https://i.sstatic.net/uzLsj.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/uzLsj.png" alt="table" /></a></p>
<ul>
<li>Python 3.9.7</li>
<li>IPython 7.29.0</li>
<li>Pandas 1.3.4</li>
</ul>
<p><strong>What I did - but it feels "clumsy":</strong></p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# create test data
data = {"batch": [100, 101, 102, 103, 104, 105, 106, 107, 108, 109],
"production line": ["A", "A", "B", "A", "B", "B", "A", "B", "B", "B"],
"article": ["hammer", "drill", "hammer", "pliers", "pliers", "pliers", "hammer", "hammer", "hammer", "widget"],
"OEE": np.random.rand(10)}
df = pd.DataFrame(data, columns = ["batch", "production line", "article","OEE"])
# add a helper column
df["comparable"] = False
# check for each line if the article exists on the other line
for i in range (len(df)):
production_line = df.loc[i, "production line"]
article = df.loc[i, "article"]
k = i
while k < len(df):
if production_line != df.loc[k, "production line"] and article == df.loc[k, "article"]:
df.loc[i, "comparable"] = True
df.loc[k, "comparable"] = True
k +=1
# create reduced dataset
reduced = df[df["comparable"] == True]
sns.stripplot(x= reduced["production line"], y=reduced.OEE, data=reduced, size=16, alpha=.2, jitter=True, edgecolor="none")
</code></pre>
<p><a href="https://i.sstatic.net/n2ECQ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/n2ECQ.png" alt="enter image description here" /></a></p>
|
<python><pandas><dataframe><iteration>
|
2023-02-06 23:09:34
| 2
| 349
|
RogerWilco77
|
75,367,378
| 562,769
|
Is it possible to shrink botocore within site-packages?
|
<p>I've just seen that my web applications docker image is enormous. A 600-MB reason is the packages I install for it. The biggest single offender is botocore with 77.7 MB.</p>
<p>Apparently this is known behavior: <a href="https://github.com/boto/botocore/issues/1629" rel="noreferrer">https://github.com/boto/botocore/issues/1629</a></p>
<p>Is it possible to redue that size?</p>
<h2>Analysis</h2>
<ul>
<li>The <code>tar.gz</code> distribution is just 10.8 MB: <a href="https://pypi.org/project/botocore/#files" rel="noreferrer">https://pypi.org/project/botocore/#files</a></li>
<li>75MB are in <a href="https://github.com/boto/botocore/tree/develop/botocore/data" rel="noreferrer">the <code>data</code> directory</a></li>
<li>For every single AWS service, there seem to be <a href="https://github.com/boto/botocore/tree/develop/botocore/data/ec2" rel="noreferrer">multiple folders</a> (some kind of versioning?) and <a href="https://github.com/boto/botocore/blob/develop/botocore/data/ec2/2014-09-01/service-2.json" rel="noreferrer">a <code>service-2.json</code></a></li>
<li>The <code>service-2.json</code> files probably use most of the space. They are not minified and they contain a lot of information that seems not to be necessary for running a production system (e.g. <code>description</code>).</li>
</ul>
<p>Is there a way to either completely avoid botocore or in any other way reduce botocores size for the Docker image? (I'm only using S3)</p>
|
<python><amazon-web-services><docker><botocore>
|
2023-02-06 22:54:31
| 1
| 138,373
|
Martin Thoma
|
75,367,291
| 4,042,278
|
How can I use alpha with seaborn.pointplot?
|
<p>I guess it's changed recently since I saw several code which use alpha with pointplot (<a href="https://stackoverflow.com/questions/70688084/pointplot-and-scatterplot-in-one-figure-but-x-axis-is-shifting">Pointplot and Scatterplot in one figure but X axis is shifting</a> or <a href="https://stackoverflow.com/questions/56300170/is-there-a-way-to-set-transparency-alpha-level-in-a-seaborn-pointplot">Is there a way to set transparency/alpha level in a seaborn pointplot?</a>) but when I use it it raise an error:</p>
<pre><code>data = [{'method': 'end-to-end', 'k': 1, 'time': 181.0, 'auc': 69.76}, {'method': 'end-to-end', 'k': 2, 'time': 193.0, 'auc': 71.12}, {'method': 'end-to-end', 'k': 3, 'time': 256.0, 'auc': 71.84}, {'method': 'end-to-end', 'k': 4, 'time': 302.0, 'auc': 71.87}, {'method': 'end-to-end', 'k': 5, 'time': 365.0, 'auc': 71.89}, {'method': 'end-to-end', 'k': 8, 'time': 602.0, 'auc': 71.87}, {'method': 'end-to-end', 'k': 10, 'time': 743.0, 'auc': 71.84}, {'method': 'first', 'k': 1, 'time': 82.0, 'auc': 69.01}, {'method': 'first', 'k': 2, 'time': 105.0, 'auc': 69.45}, {'method': 'first', 'k': 3, 'time': 171.0, 'auc': 70.11}, {'method': 'first', 'k': 4, 'time': 224.0, 'auc': 70.36}, {'method': 'first', 'k': 5, 'time': 279.0, 'auc': 70.74}, {'method': 'first', 'k': 8, 'time': 517.0, 'auc': 70.81}, {'method': 'first', 'k': 10, 'time': 654.0, 'auc': 70.98}]
data = pd.DataFrame(data)
ax = sns.pointplot(x='time', y='auc', data=data, hue='method',
alpha=.1)
</code></pre>
<p><code>TypeError: pointplot() got an unexpected keyword argument 'alpha'</code></p>
<p>Is there any other way?</p>
|
<python><matplotlib><seaborn>
|
2023-02-06 22:38:46
| 0
| 1,390
|
parvij
|
75,367,137
| 20,358
|
How to find and replace values between specific characters in a string?
|
<p>I am trying to find the most efficient way natural to Python, to find all instances of a string within another string surrounded by a <code>$$</code> sign and replace it with another value in another variable.</p>
<p>The string in question is like this <code>"$$firstOccurance$$ some other words here then $$secondOccurance$$"</code></p>
<p>My solution below is not working, I think because it's not able to differentiate between the first time it finds the <code>$$</code> sign and the second time it finds it again. This results in nothing getting printed. There can be many occurrences of strings between the <code>$$</code> value.</p>
<pre><code>the_long_string = "$$firstOccurance$$ some other words here then $$secondOccurance$$"
replacement_value = "someNewString"
print(the_long_string[the_long_string.index('$$')+len('$$'):the_long_string.index('$$')])
</code></pre>
<p>What would be the way to correct and fix what I have done so far?
The end result has to look like this <code>someNewString some other words here then someNewString</code>, where there is no <code>$$</code> sign left.</p>
|
<python>
|
2023-02-06 22:15:12
| 2
| 14,834
|
user20358
|
75,367,132
| 17,724,172
|
Writing to a text file, last entry is missing
|
<p>This code calls no errors, but my text file is not getting betty and her grade. It's only getting the first three out of the four combinations. What am I doing wrong? Thanks!</p>
<pre><code>students = ['fred','wilma','barney','betty']
grades = [100,75,80,90]
for i in range(4):
file = open("grades3.txt", "a")
entry = students[i] + "-" + str(grades[i]) + '\n'
file.write(entry)
file.close
</code></pre>
|
<python><file><text>
|
2023-02-06 22:14:50
| 3
| 418
|
gerald
|
75,367,078
| 2,989,642
|
beautifulsoup to get both link and link text inside an HTML table
|
<p>I am dealing with HTML table data consisting of two fields: First, a field that holds a hyperlinked text string, and second, one that holds a date string. I need the two to be extracted and remain associated.</p>
<p>I am catching the rows in the following fashion (found from another SO question):</p>
<pre><code>pg = s.get(url).text # s = requests Session object
soup = BeautifulSoup(pg, 'html.parser')
files = [[
[td for td in tr.find_all('td')]
for tr in table.find_all('tr')]
for table in soup.find_all('table')]
</code></pre>
<p>iterating over <code>files[0]</code> yields rows that have dynamic classes because the HTML was published from Microsoft Excel. So I can't depend on class names. But the location of elements are stable. The rows look like this:</p>
<pre><code>[<td class="excel auto tag" height="16" style="height:12.0pt;border-top:none"><a href="subfolder/north_america-latest.shp.zip"><span style='font-size:9.0pt;font-family:"Courier New", monospace;mso-font-charset:0'>north_america-latest.shp.zip</span></a></td>, <td class="another auto tag" style="border-top:none;border-left:none">2023-01-01</td>]
</code></pre>
<p>Broken up, for easier reading:</p>
<pre><code>[
<td class="excel auto tag" height="16" style="height:12.0pt;border-top:none">
<a href="subfolder/north_america-latest.shp.zip">
<span style='font-size:9.0pt;font-family:"Courier New", monospace;mso-font-charset:0'>
north_america-latest.shp.zip
</span>
</a>
</td>,
<td class="another auto tag" style="border-top:none;border-left:none">
2023-01-01
</td>
]
</code></pre>
<p>Using the <code>.get_text()</code> method with <code>td</code> I can get the string literal of the link, as well as the date in one go, but once I have the <code>td</code> object, how do I go about obtaining the following three elements?</p>
<pre><code>"subfolder/north_america-latest.shp.zip" # the link
"north_america-latest.shp.zip" # the name
"2023-01-01" # the date
</code></pre>
|
<python><beautifulsoup>
|
2023-02-06 22:08:00
| 1
| 549
|
auslander
|
75,367,068
| 7,429,447
|
DeprecationWarning: headless property is deprecated, instead use add_argument('--headless') or add_argument('--headless=new') on Selenium 4.8.0 Python
|
<p>I am trying to execute a basic program using <em><strong>Selenium 4.8.0</strong></em> Python clients in <em><strong>headless</strong></em> mode:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
options = Options()
options.headless = True
s = Service('C:\\BrowserDrivers\\chromedriver.exe')
driver = webdriver.Chrome(service=s, options=options)
driver.get('https://www.google.com/')
driver.quit()
</code></pre>
<p>With the following configuration:</p>
<ul>
<li>Selenium 4.8.0 Python</li>
<li>Chrome _Version 109.0.5414.120 (Official Build) (64-bit)</li>
<li>ChromeDriver 109.0.5414.25</li>
</ul>
<p>Though the program gets executed successfully there seems to a DeprecationWarning as:</p>
<pre><code>DeprecationWarning: headless property is deprecated, instead use add_argument('--headless') or add_argument('--headless=new')
</code></pre>
<p>Can anyone explain the DeprecationWarning and the required changes?</p>
|
<python><selenium><selenium-webdriver><selenium-chromedriver><headless>
|
2023-02-06 22:06:47
| 2
| 194,394
|
undetected Selenium
|
75,367,027
| 19,916,174
|
perf_counter()-start giving weird result
|
<p>I was building my own version of the timeit function, which returns the amount of time it takes to run a function <code>n</code> times. However, when I ran it with a sample input, I received the following output, which doesn't seem right, as it ran very quickly.</p>
<pre><code>9.400071576237679e-06
</code></pre>
<p>My code:</p>
<pre><code>from time import perf_counter
from typing import Callable
class MyTimeit:
def __init__(self):
pass
def timeit(self, function: Callable, *parameters, num: int=10000):
if not parameters:
start = perf_counter()
for _ in range(num):
function()
return perf_counter()-start
else:
start = perf_counter()
for _ in range(num):
function(*parameters)
return perf_counter()-start
print(MyTimeit().timeit(lambda x: x<12, 10, n=100))
</code></pre>
<p>Why is it giving me this result? Is it a flaw in my programming logic, or am I missing something else?</p>
|
<python><function><time><timeit>
|
2023-02-06 22:01:05
| 1
| 344
|
Jason Grace
|
75,366,985
| 2,100,039
|
Create a Pandas Dataframe Date Column to Day of Year
|
<p>I know this should be easy but for some reason, I cannot get the result that I need. I have data that looks like this where 'raw_time' is read into a df in the date format yyyy-mm-dd hh:mm:ss.
It looks like this:</p>
<p>dfdates =</p>
<pre><code>1429029 1992-01-03 02:00:00
1429030 1992-01-03 01:00:00
1429031 1992-01-03 00:00:00
1429032 1992-01-02 23:00:00
1429033 1992-01-02 22:00:00
1429034 1992-01-02 21:00:00
1429035 1992-01-02 20:00:00
1429036 1992-01-02 19:00:00
1429037 1992-01-02 18:00:00
1429038 1992-01-02 17:00:00
1429039 1992-01-02 16:00:00
1429040 1992-01-02 15:00:00
1429041 1992-01-02 14:00:00
1429042 1992-01-02 13:00:00
1429043 1992-01-02 12:00:00
1429044 1992-01-02 11:00:00
</code></pre>
<p>I just need to convert each row to day of year. So the result in a new df would look like:</p>
<p>df_doy:</p>
<pre><code>index day_of_year
1429029 3
1429030 3
1429031 3
1429032 2
1429033 2
1429034 2
1429035 2
1429036 2
1429037 2
1429038 2
1429039 2
1429040 2
1429041 2
1429042 2
1429043 2
1429044 2
</code></pre>
<p>thank you,</p>
|
<python><pandas><datetime><days>
|
2023-02-06 21:56:27
| 3
| 1,366
|
user2100039
|
75,366,974
| 8,354,766
|
OpenCV Mat cpp operation only on condition
|
<p>Having a hard time figuring out how to do this python operation in c++ without looping.</p>
<p>The goal is to perform an operation only on a part of the cv::Mat that meets a condition.</p>
<p>In this case, scaling values of the image that were originally between -5 and 5..</p>
<pre><code>image[-5<image<5] = image[-5<image<5]*2+1
</code></pre>
|
<python><c++><opencv><matrix><indexing>
|
2023-02-06 21:55:11
| 1
| 488
|
Alberto MQ
|
75,366,940
| 2,999,349
|
How to get OpenAI/baselines to work on MacOS Monterey, M1 Pro?
|
<p>I've been struggling for days trying to get any repo implementing PPO running on my Macbook, so I was wondering what's the trick? I'm currently trying to get the OpenAI/Baselines repo to work, carefully following their README, and after having solved various undocumented issues ( different tensorflow pkg sources, missing tensorflow-macos fork in setup script, deprecated numpy functionalities, hardcoded gcc pkg version that is incompatible with MacOS, etc etc ) I'm now stuck at this error:</p>
<blockquote>
<p><strong>gym.error.DependencyNotInstalled:
dlopen(<...>/venv/lib/python3.10/site-packages/mujoco_py/generated/cymj_2.1.2.14_310_macextensionbuilder_310.so,
0x0002): symbol not found in flat namespace '_mj_Euler'</strong>.<br />
(HINT: you
need to install mujoco_py, and also perform the setup instructions
here: <a href="https://github.com/openai/mujoco-py/." rel="nofollow noreferrer">https://github.com/openai/mujoco-py/.</a>)</p>
</blockquote>
<p>I already installed mujoco_py, and I have no idea what is wrong here as I don't understand the error and couldn't really find anything about this that works.</p>
<p>If anyone has any insights into this or knows an "easy" way to get the OpenAI/baselines repo working on MacOS Monterey (with M1 Pro Chip), or even any repo implementing PPO in Python for that matter, I'd very much appreciate it!</p>
<p>P.S. For reference, this is my pip freeze:</p>
<pre><code>absl-py==1.4.0
astunparse==1.6.3
atari-py==0.2.9
attrs==22.2.0
cachetools==5.3.0
certifi==2022.12.7
cffi==1.15.1
charset-normalizer==3.0.1
click==8.1.3
cloudpickle==1.2.2
Cython==0.29.33
dill==0.3.6
exceptiongroup==1.1.0
fasteners==0.18
flatbuffers==23.1.21
future==0.18.3
gast==0.4.0
glfw==2.5.6
google-auth==2.16.0
google-auth-oauthlib==0.4.6
google-pasta==0.2.0
grpcio==1.51.1
gym==0.13.1
h5py==3.8.0
idna==3.4
imageio==2.25.0
iniconfig==2.0.0
joblib==1.2.0
keras==2.11.0
libclang==15.0.6.1
Markdown==3.4.1
MarkupSafe==2.1.2
mujoco==2.3.1.post1
mujoco-py==2.1.2.14
numpy==1.23.5
oauthlib==3.2.2
opencv-python==4.7.0.68
opt-einsum==3.3.0
packaging==23.0
Pillow==9.4.0
pluggy==1.0.0
progressbar2==4.2.0
protobuf==3.19.4
pyasn1==0.4.8
pyasn1-modules==0.2.8
pycparser==2.21
pyglet==1.3.2
PyOpenGL==3.1.6
pytest==7.2.1
python-utils==3.4.5
requests==2.28.2
requests-oauthlib==1.3.1
rsa==4.9
scipy==1.10.0
six==1.16.0
tensorboard==2.11.2
tensorboard-data-server==0.6.1
tensorboard-plugin-wit==1.8.1
tensorflow-estimator==2.11.0
tensorflow-macos==2.11.0
tensorflow-metal==0.7.0
termcolor==2.2.0
tomli==2.0.1
tqdm==4.64.1
typing_extensions==4.4.0
urllib3==1.26.14
Werkzeug==2.2.2
wrapt==1.14.1
</code></pre>
|
<python><macos><openai-api>
|
2023-02-06 21:50:29
| 0
| 879
|
user2999349
|
75,366,936
| 1,258,509
|
Django Rest Framework - How to use url parameters in API requests to exclude fields in response
|
<p>Let's say I have an API that returns some simple list of objects at the <code>/users</code> endpoint</p>
<pre><code>{
"count": 42,
"results": [
{
"name": "David",
"age": 30,
"location": "Alaska"
},
...
]
}
</code></pre>
<p>I would like to have an optional parameter (boolean) that changes the output by removing a field.</p>
<p>So <code>/users?abridged=True</code> would return the same objects, but omit a field. If the field is not there, it defaults to False</p>
<pre><code>{
"count": 42,
"results": [
{
"name": "David",
"age": 30,
},
...
]
}
</code></pre>
<p>I suppose I could create two serializers, one for the full version and one abridged, but I'm not sure how I could use a url parameter to select which serializer to use. Is there a better way to do this?</p>
|
<python><django><django-rest-framework>
|
2023-02-06 21:50:09
| 1
| 1,467
|
Brian C
|
75,366,866
| 9,758,352
|
Converting fields inside a Serializer in django
|
<p>I have a project where one model, called <code>Request</code>, has two fields (<code>source</code>, <code>dest</code>) that contain two <code>id</code>s which are not known to the user. However, each one is connected to another model <code>User</code>, who let's say that they have one field, <code>username</code>, which <em>is</em> known to the user.</p>
<p>Now, I want to make a serializer that can take <code>username</code>s, and convert them into <code>id</code>s. (The opposite was simple to achieve, I just modified the <code>to_representation</code> method.) The problem is that when I send <code>{'source': 'john', 'dest': 'jim'}</code> the serializer does not take these data as valid. This was expected behavior, as it expected <code>id</code>s and got strings (<code>username</code>s). However, even when I overridden the <code>validate_source</code>, <code>validate_dest</code> and <code>validate</code> methods to actually check that the <code>username</code>s exist (instead of the <code>id</code>s), I am still getting errors that the serializer expected <code>id</code> but got string.</p>
<ol>
<li>Are the <code>validate</code>, <code>validate_<field></code> methods the wrong ones to override in this case?</li>
<li>Should I just convert the <code>username</code>s into <code>id</code>s inside my view?</li>
<li>is it pythonic and good practice, django-wise, to receive some fields from the user and change them inside the serializer (as I change <code>username</code> into <code>id</code>)?</li>
</ol>
<p>Current Serializer:</p>
<pre class="lang-py prettyprint-override"><code>class RequestSerializer(serializers.ModelSerializer):
class Meta:
model = Request
fields = '__all__'
def validate_source(self, value):
username = value.get('username')
if username is None:
raise serializers.ValidationError('`user` field is required ')
return value
def validate_dest(self, value):
username = value.get('username')
if username is None:
raise serializers.ValidationError('`user` field is required ')
return value
def validate(self, attrs):
self.validate_source(attrs['source'])
self.validate_dest(attrs['dest'])
return attrs
def to_representation(self, instance):
# do things
pass
</code></pre>
<p>Please notice that this is not the whole functionality of my serializer. To convert from an <code>id</code> to a <code>username</code> I have to check the data of another Model, So I cannot use a SlugRelatedField.</p>
<p>Also, username is not the only item returned by the serializer. It also returns a <code>'class'</code> field, depending on which group the the user has joined. The user may join more than one group, and each user-group combination has its own <code>id</code>. In the same way, when deserializing the data, I will need to read (1) the username, and then (2) the group, and find the correct id.</p>
<p>Thank you.</p>
|
<python><django><django-rest-framework><django-serializer>
|
2023-02-06 21:42:15
| 1
| 457
|
BillTheKid
|
75,366,764
| 11,380,243
|
Finding the index of the element, for each column in a dataframe, that is the closest to a given defined number and plot in a heatmap
|
<p>I am basically loading a dataframe from a .csv file in which as the index, I have the motion amplitude values and in the column names, I have the motion frequency values. Filling the column and rows I have the velocity values correspondent to the motion of each frequency and amplitude. What I am planning to achieve is, for each column, to find the closest index and column values to a given number, in this case, let's say it is <em><strong>6</strong></em>, and then plot these values in a heatmap.</p>
<p>I made a dummy example below:</p>
<pre><code>import pandas as pd
import seaborn as sns
# Creating a dummy dataframe for the examples
c1 = [6, 3, 2, 3, 8, 2]
c2 = [1, 5.2, 2, 7, 3, 4]
c3 = [3, 5, 6.1, 3, 4, 5.7]
c4 = [5, 8, 1, 6.2, 3, 4]
c5 = [1, 2, 5, 5, 6.3, 7]
c6 = [1, 3, 5.5, 1, 7, 6.1]
df = pd.DataFrame([c1, c2, c3, c4, c5, c6]).T
# Setting the values for the index and the columns
index = pd.Index(['0.1', '0.2', '0.3', '0.4', '0.5', '0.6'])
df = df.set_index(index)
df.columns = ['1', '2', '3', '4', '5', '6']
# Plotting the heat map
plt.figure()
ax = sns.heatmap(df)
plt.ylabel('Amplitude [m]')
plt.xlabel('Frequency [Hz]')
plt.show()
</code></pre>
<p>The plot that I want to achieve is the one in the picture below. The yellow line would mark the closest values in each column to the number 6. So, besides the heatmap, I would have to also plot the index and values for each column, in which the number is the closest to 6.</p>
<p><a href="https://i.sstatic.net/lODWw.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/lODWw.png" alt="" /></a></p>
|
<python><pandas><dataframe><heatmap>
|
2023-02-06 21:29:22
| 2
| 438
|
Marc Schwambach
|
75,366,567
| 1,497,199
|
How do I use a custom pip.conf in a docker image?
|
<p>How can I configure a Docker container to use a custom pip.conf file?</p>
<p>This does not (seem to) work for me:</p>
<pre><code>from python:3.9
COPY pip.conf ~/.config/pip/pip.conf
</code></pre>
<p>where <code>pip.conf</code> is a copy of the pip configuration that points to a proprietary package repository.</p>
|
<python><docker><pip>
|
2023-02-06 21:04:48
| 1
| 8,229
|
Dave
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.