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,788,229
| 14,094,778
|
Python: Selenium cann't finde the btn on pop-up window
|
<p>I'm trying to click the btn "select all cookies" on cookies terms pop-up window.
I'v tried:</p>
<pre><code>div=driver.find_element(By.XPATH,'//*[@id="js_cookie-settings-modal"]/div[2]/div/div[3]/div')
driver.implicitly_wait(4)
button=div.find_element(By.XPATH,'//*[@id="selectAll"]')
driver.implicitly_wait(4)
button.click()
</code></pre>
<p>Error:</p>
<pre><code> raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable
(Session info: chrome=111.0.5563.64)
</code></pre>
<p>Option2:</p>
<pre><code>WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="selectAll"]'))).click()
driver.implicitly_wait(50)
</code></pre>
<p>Error:</p>
<pre><code> raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:
</code></pre>
<p>URL:<a href="https://www.eversports.de/" rel="nofollow noreferrer">https://www.eversports.de/</a></p>
|
<python><python-3.x><selenium-webdriver><xpath><webdriverwait>
|
2023-03-20 08:58:00
| 2
| 693
|
ahm5
|
75,787,865
| 19,325,656
|
Extract text from column between two delimiters
|
<p>Hi all i have pandas columns that are looking like this</p>
<pre><code>**<https://stackoverflow.com/> Stackoverflow runs the world --website --q 3** - <@123456789> (today)
</code></pre>
<p>How can I parse each column to get something like this</p>
<pre><code><https://stackoverflow.com/> Stackoverflow runs the world --website --q 3
</code></pre>
<p><strong>or in a perfect world</strong></p>
<pre><code>https://stackoverflow.com/ Stackoverflow runs the world
</code></pre>
<p>most of the time text after each <strong>--</strong> is different or sometimes there is only one <strong>--</strong></p>
|
<python><pandas><dataframe>
|
2023-03-20 08:18:26
| 1
| 471
|
rafaelHTML
|
75,787,845
| 880,783
|
How to get the code of just a lambda argument?
|
<p>In the following example code, <code>inspect.getsource(lambda_argument)</code> seems to include the source code of the function call surrounding the definition of the lambda. How can I prevent that?</p>
<pre class="lang-py prettyprint-override"><code>import inspect
def fun_of_lambda(lambda_argument):
print(inspect.getsource(lambda_argument))
fun_of_lambda(lambda x, y, z: x + y + z)
</code></pre>
<p>Output:</p>
<pre><code>fun_of_lambda(lambda x, y, z: x + y + z)
</code></pre>
<p><em>Previous version of the question:</em></p>
<pre class="lang-py prettyprint-override"><code>import inspect
def decorator_with_lambda(lambda_argument):
def decorator(inner_fun):
print("Printing lambda_argument ...")
print(inspect.getsource(lambda_argument))
return inner_fun
return decorator
@decorator_with_lambda(lambda: True)
def function() -> None:
pass # This should not be printed as part of lambda_argument!
function()
</code></pre>
<p>Output:</p>
<pre><code>Printing lambda_argument ...
@decorator_with_lambda(lambda: True)
def function() -> None:
pass # This should not be printed as part of lambda_argument!
</code></pre>
<p>Update: <code>dill.source</code> seems to have the same issue, and I have reported <a href="https://github.com/uqfoundation/dill/issues/583" rel="nofollow noreferrer">https://github.com/uqfoundation/dill/issues/583</a>.</p>
|
<python><lambda><code-inspection>
|
2023-03-20 08:15:28
| 1
| 6,279
|
bers
|
75,787,663
| 18,221,164
|
Dictionary entry to file fails
|
<p>I am having a requirement of downloading certain libraries from the repository. I use the get method from Requests module to achieve that. However, on every run of the code, the libraries are fetched over and over again. So we plan to optimise it in the following way:</p>
<p>For all the libraries downloaded, we create a dictionary entry on a text file as follows:</p>
<pre><code>download_libs()
add_entry_to_text_file(name,version, directory)
</code></pre>
<p>The <code>add_entry_to_text_file(name,version, directory) </code> is defined as below:</p>
<pre><code> details = {'name': name,
'asked_version': version}
with open(directory + '\\filename.txt', 'a') as f:
for key, value in details.items():
f.write('%s:%s\t' % (key, value))
f.write('\n')
</code></pre>
<p>After the first run, the txt file looks like below:</p>
<pre><code>name:lib1 asked_version:11.12
name:lib2 asked_version:11.12
name:lib3 asked_version:11.14
name:lib4 asked_version:11.13
name:lib5 asked_version:11.15
</code></pre>
<p>Now, I run into a scenario of updating maybe lib4 to a new version of 11.20
I run the file again, and the library is added as a new entry to the text file.</p>
<pre><code>name:lib1 asked_version:11.12
name:lib2 asked_version:11.12
name:lib3 asked_version:11.14
name:lib4 asked_version:11.13
name:lib5 asked_version:11.15
name:lib4 asked_version:11.20
</code></pre>
<p>I was under the impression that since I am entering a dictionary into the file, the new value for the library would just get updated in the text file rather than creating a whole new entry.</p>
<p>Should it be the case that the additional logic needs to be added before writing to a file, and not expecting dictionary to do it by default?</p>
|
<python><python-3.x><dictionary>
|
2023-03-20 07:48:01
| 3
| 511
|
RCB
|
75,787,376
| 10,829,044
|
pandas groupby, split df and rename multiple sheets
|
<p>I have a dataframe like as below</p>
<pre><code>import numpy as np
import pandas as pd
from numpy.random import default_rng
rng = default_rng(100)
cdf = pd.DataFrame({'Id':[1,2,3,4,5],
'customer': rng.choice(list('ACD'),size=(5)),
'segment': rng.choice(list('PQRS'),size=(5)),
'manager': rng.choice(list('QWER'),size=(5)),
'dumma': rng.choice((1234),size=(5)),
'damma': rng.choice((1234),size=(5))
})
</code></pre>
<p>I would like to do the below</p>
<p>a) create an excel file output with multiple sheets (based on segment column) for each manager (based on manager column)</p>
<p>b) For segment values - <code>Q,P and S</code>, check whether column <code>dumma</code> value is greater than column <code>damma</code> value</p>
<p>c) Instead of <code>out.xlsx</code>, save each file using the <code>{manager}.xlsx</code> name (from manager column)</p>
<p>d) If there are no records for any specific segment (len=0), then we need not create sheet for that segment</p>
<p>So, I tried the below</p>
<pre><code>DPM_col = "manager"
SEG_col = "segment"
for i,j in dict.fromkeys(zip(cdf[DPM_col], cdf[SEG_col])).keys():
print("i is ", i)
print("j is ", j)
data_output = cdf.query(f"{DPM_col} == @i & {SEG_col} == @j")
writer = pd.ExcelWriter('out.xlsx', engine='xlsxwriter')
if len(data_output[data_output['segment'].isin(['Q','P','S'])])>0:
if len(data_output[data_output['dumma'] >= data_output['damma']])>0:
for seg, v in data_output.groupby(['segment']):
v.to_excel(writer, sheet_name=f"POS_decline_{seg}",index=False)
writer.save()
else:
for seg, v in data_output.groupby(['segment']):
v.to_excel(writer, sheet_name=f"silent_inactive_{seg}",index=False)
writer.save()
</code></pre>
<p>But it doesn't work. It only shows the value for <code>R</code> segment (which is in else clause)</p>
<p>I expect my output for each manager file to have multiple sheets like as below. If there are no records for any specific segment (len=0), then we need not create sheet for that segment</p>
<p><a href="https://i.sstatic.net/nlAQC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/nlAQC.png" alt="enter image description here" /></a></p>
|
<python><excel><pandas><dataframe><group-by>
|
2023-03-20 07:06:42
| 1
| 7,793
|
The Great
|
75,787,164
| 2,149,425
|
Expected type 'Iterable[SupportsLessThan | Any]' (matched generic type 'Iterable[SupportsLessThanT]'), got 'object' instead
|
<p>The two following blocks of code should be equivalent:</p>
<h4>Block 1</h4>
<pre><code>array_1 = [[12, 15], [10, 1], [5, 13]]
print(array_1)
""" output:
[[12, 15], [10, 1], [5, 13]]
"""
print(sorted(array_1))
""" output:
[[5, 13], [10, 1], [12, 15]]
"""
</code></pre>
<hr />
<h4>Block 2</h4>
<pre><code>import numpy as np
np_array_1 = np.array([[12, 15], [10, 1], [5, 13]])
print(np_array_1)
""" output:
[[12 15]
[10 1]
[ 5 13]]
"""
array_1 = np_array_1.tolist()
print(array_1)
""" output:
[[12, 15], [10, 1], [5, 13]]
"""
print(sorted(array_1))
""" output:
[[5, 13], [10, 1], [12, 15]]
"""
</code></pre>
<hr />
<h4>But, in PyCharm, if I use:</h4>
<pre><code>sorted(np_array_1.tolist()) # SEE BLOCK 2
</code></pre>
<p>I receive this only <em><strong>warning</strong></em>, but apparently without any issue:</p>
<pre><code>Expected type 'Iterable[SupportsLessThan | Any]' (matched generic type 'Iterable[SupportsLessThanT]'), got 'object' instead
</code></pre>
<p>I would like to get clean code, thank you.</p>
|
<python><python-3.x><numpy><sorting><pycharm>
|
2023-03-20 06:30:28
| 1
| 1,673
|
Riccardo Volpe
|
75,787,160
| 11,518,165
|
how to store complete script content to a variable and execute later
|
<p>I have a script.py we execute and inside this python script we need to read the content of a scripts and execute in another server</p>
<p>We have few shell scripts and one of the sample shell script "execution_count.ksh" as below.</p>
<p>We have these scripts available in one server. Is there a way we can store the complete content of the script into a variable and use that variable as execution in other different server.</p>
<p>I tried with "with open" clause and passed "datainfo" as a command but its was getting failed</p>
<pre><code>with open('script.sh', 'r') as file:
datainfo = file.read()
command="ssh user@192.168.1.101 "+ datainfo
os.system(command)
exec 10<&0
exec < $1
# remember the name of the input file
in=$1
# init
file="current_line.txt"
let count=0
# this while loop iterates over all lines of the file
while read LINE
do
# increase line counter
((count++))
# write current line to a tmp file with name $file (not needed for counting)
echo $LINE > $file
# this checks the return code of echo (not needed for writing; just for demo)
if [ $? -ne 0 ]
then echo "Error in writing to file ${file}; check its permissions!"
fi
done
echo "Number of lines: $count"
echo "The last line of the file is: `cat ${file}`"
# Note: You can achieve the same by just using the tool wc like this
echo "Expected number of lines: `wc -l $in`"
# restore stdin from filedescriptor 10
# and close filedescriptor 10
exec 0<&10 10<&-
</code></pre>
|
<python><shell>
|
2023-03-20 06:30:02
| 0
| 541
|
Arya
|
75,786,903
| 8,064,104
|
Interpretation of IMU-Data for position tracking
|
<p>Is it possible to track the position of an object in a reference coordinate system with an INS? if yes what is the correct approach in doing that?</p>
|
<python><ros><imu>
|
2023-03-20 05:45:47
| 0
| 347
|
nikki
|
75,786,783
| 11,141,816
|
Use xml.etree.elementtree to process xml with xmlns="http://www.w3.org/2005/Atom"
|
<p>I'm trying to process the data extracted from the web. The decoded raw data was bytes of xml file. I had some old code that just magically worked. However, I'm not sure what they were doing since it's been a while.</p>
<pre><code>import urllib, urllib.request
url = 'http://export.arxiv.org/api/query?search_query=all:electron+OR+query?id_list=hep-th/9112001&start=0&max_results=2'
data = urllib.request.urlopen(url)
</code></pre>
<p>which could be decoded with</p>
<pre><code>data.read().decode('utf-8')
</code></pre>
<p>which had a file of the form</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<link href="http://arxiv.org/api/query?search_query%3Dall%3Aelectron%20OR%20query%3Fid_list%3Dhep-th%2F9112001%26id_list%3D%26start%3D0%26max_results%3D2" rel="self" type="application/atom+xml"/>
<title type="html">ArXiv Query: search_query=all:electron OR query?id_list=hep-th/9112001&amp;id_list=&amp;start=0&amp;max_results=2</title>
<id>http://arxiv.org/api/hNIXPXLfJXds3VmSJQ2mnDpmElY</id>
<updated>2023-03-20T00:00:00-04:00</updated>
<opensearch:totalResults xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">194139</opensearch:totalResults>
<opensearch:startIndex xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">0</opensearch:startIndex>
<opensearch:itemsPerPage xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">2</opensearch:itemsPerPage>
<entry>
<id>http://arxiv.org/abs/cond-mat/0102536v1</id>
<updated>2001-02-28T20:12:09Z</updated>
<published>2001-02-28T20:12:09Z</published>
<title>Impact of Electron-Electron Cusp on Configuration Interaction Energies</title>
<summary> The effect of the electron-electron cusp on the convergence of configuration
interaction (CI) wave functions is examined. By analogy with the
pseudopotential approach for electron-ion interactions, an effective
electron-electron interaction is developed which closely reproduces the
scattering of the Coulomb interaction but is smooth and finite at zero
electron-electron separation. The exact many-electron wave function for this
smooth effective interaction has no cusp at zero electron-electron separation.
We perform CI and quantum Monte Carlo calculations for He and Be atoms, both
with the Coulomb electron-electron interaction and with the smooth effective
electron-electron interaction. We find that convergence of the CI expansion of
the wave function for the smooth electron-electron interaction is not
significantly improved compared with that for the divergent Coulomb interaction
for energy differences on the order of 1 mHartree. This shows that, contrary to
popular belief, description of the electron-electron cusp is not a limiting
factor, to within chemical accuracy, for CI calculations.
</summary>
<author>
<name>David Prendergast</name>
<arxiv:affiliation xmlns:arxiv="http://arxiv.org/schemas/atom">Department of Physics</arxiv:affiliation>
</author>
<author>
<name>M. Nolan</name>
<arxiv:affiliation xmlns:arxiv="http://arxiv.org/schemas/atom">NMRC, University College, Cork, Ireland</arxiv:affiliation>
</author>
<author>
<name>Claudia Filippi</name>
<arxiv:affiliation xmlns:arxiv="http://arxiv.org/schemas/atom">Department of Physics</arxiv:affiliation>
</author>
<author>
<name>Stephen Fahy</name>
<arxiv:affiliation xmlns:arxiv="http://arxiv.org/schemas/atom">Department of Physics</arxiv:affiliation>
</author>
<author>
<name>J. C. Greer</name>
<arxiv:affiliation xmlns:arxiv="http://arxiv.org/schemas/atom">NMRC, University College, Cork, Ireland</arxiv:affiliation>
</author>
<arxiv:doi xmlns:arxiv="http://arxiv.org/schemas/atom">10.1063/1.1383585</arxiv:doi>
<link title="doi" href="http://dx.doi.org/10.1063/1.1383585" rel="related"/>
<arxiv:comment xmlns:arxiv="http://arxiv.org/schemas/atom">11 pages, 6 figures, 3 tables, LaTeX209, submitted to The Journal of
Chemical Physics</arxiv:comment>
<arxiv:journal_ref xmlns:arxiv="http://arxiv.org/schemas/atom">J. Chem. Phys. 115, 1626 (2001)</arxiv:journal_ref>
<link href="http://arxiv.org/abs/cond-mat/0102536v1" rel="alternate" type="text/html"/>
<link title="pdf" href="http://arxiv.org/pdf/cond-mat/0102536v1" rel="related" type="application/pdf"/>
<arxiv:primary_category xmlns:arxiv="http://arxiv.org/schemas/atom" term="cond-mat.str-el" scheme="http://arxiv.org/schemas/atom"/>
<category term="cond-mat.str-el" scheme="http://arxiv.org/schemas/atom"/>
</entry>
<entry>
<id>http://arxiv.org/abs/astro-ph/0608371v1</id>
<updated>2006-08-17T14:05:46Z</updated>
<published>2006-08-17T14:05:46Z</published>
<title>Electron thermal conductivity owing to collisions between degenerate
electrons</title>
<summary> We calculate the thermal conductivity of electrons produced by
electron-electron Coulomb scattering in a strongly degenerate electron gas
taking into account the Landau damping of transverse plasmons. The Landau
damping strongly reduces this conductivity in the domain of ultrarelativistic
electrons at temperatures below the electron plasma temperature. In the inner
crust of a neutron star at temperatures T &lt; 1e7 K this thermal conductivity
completely dominates over the electron conductivity due to electron-ion
(electron-phonon) scattering and becomes competitive with the the electron
conductivity due to scattering of electrons by impurity ions.
</summary>
<author>
<name>P. S. Shternin</name>
<arxiv:affiliation xmlns:arxiv="http://arxiv.org/schemas/atom">Ioffe Physico-Technical Institute</arxiv:affiliation>
</author>
<author>
<name>D. G. Yakovlev</name>
<arxiv:affiliation xmlns:arxiv="http://arxiv.org/schemas/atom">Ioffe Physico-Technical Institute</arxiv:affiliation>
</author>
<arxiv:doi xmlns:arxiv="http://arxiv.org/schemas/atom">10.1103/PhysRevD.74.043004</arxiv:doi>
<link title="doi" href="http://dx.doi.org/10.1103/PhysRevD.74.043004" rel="related"/>
<arxiv:comment xmlns:arxiv="http://arxiv.org/schemas/atom">8 pages, 3 figures</arxiv:comment>
<arxiv:journal_ref xmlns:arxiv="http://arxiv.org/schemas/atom">Phys.Rev. D74 (2006) 043004</arxiv:journal_ref>
<link href="http://arxiv.org/abs/astro-ph/0608371v1" rel="alternate" type="text/html"/>
<link title="pdf" href="http://arxiv.org/pdf/astro-ph/0608371v1" rel="related" type="application/pdf"/>
<arxiv:primary_category xmlns:arxiv="http://arxiv.org/schemas/atom" term="astro-ph" scheme="http://arxiv.org/schemas/atom"/>
<category term="astro-ph" scheme="http://arxiv.org/schemas/atom"/>
</entry>
</feed>
</code></pre>
<p>From the web tutorial, the xml language is a tree structure data, with contents enclosed by</p>
<pre><code><a></a>
</code></pre>
<p>very similar to that of the html, which is why</p>
<pre><code>import xml.etree.ElementTree as ET
</code></pre>
<p>could be very useful. However, when I used the code from the python standard library</p>
<pre><code>#https://docs.python.org/3/library/xml.etree.elementtree.html
root=ET.fromstring(data.read().decode('utf-8'))
for child in root:
print(child.tag, child.attrib)
</code></pre>
<p>the returned result was not what desired:</p>
<pre><code>{http://www.w3.org/2005/Atom}link {'href': 'http://arxiv.org/api/query?search_query%3Dall%3Aelectron%20OR%20query%3Fid_list%3Dhep-th%2F9112001%26id_list%3D%26start%3D0%26max_results%3D100', 'rel': 'self', 'type': 'application/atom+xml'}
{http://www.w3.org/2005/Atom}title {'type': 'html'}
{http://www.w3.org/2005/Atom}id {}
{http://www.w3.org/2005/Atom}updated {}
{http://a9.com/-/spec/opensearch/1.1/}totalResults {}
{http://a9.com/-/spec/opensearch/1.1/}startIndex {}
{http://a9.com/-/spec/opensearch/1.1/}itemsPerPage {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
{http://www.w3.org/2005/Atom}entry {}
</code></pre>
<p>This was obviously wrong. I suspected this was because there's an extra line of code</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
</code></pre>
<p>in front of the body context</p>
<pre><code><feed xmlns="http://www.w3.org/2005/Atom">
</code></pre>
<p>from a bit of reading, this seemed to be the "namespaces", but I'm not sure how to use it.</p>
<p><strong>Could you explain what should I do so that I could search for the title of the article, and the summary of that article, please?</strong></p>
<p>For example,</p>
<pre><code><title>Impact of Electron-Electron Cusp on Configuration Interaction Energies</title>
<summary> The effect of the elec... </summary>
</code></pre>
<p>were obviously under the same node, how to identify and collect those nodes and attributes to two list</p>
<pre><code>[node1, node2, ..., nodeN] #This is to identify and label the <entry></entry>
[id, updated, tile,...,category]
</code></pre>
<p>such that some functions can be used to extract the context, i.e.</p>
<pre><code>ET.{somefunction}(node1,id)=http://arxiv.org/api/hNIXPXLfJXds3VmSJQ2mnDpmElY
</code></pre>
<p>Since the website use <code>http://www.w3.org/2005/Atom</code>, can this "namespace" provide some sort of convention or shortcut?</p>
|
<python><python-3.x><xml><elementtree><xml-namespaces>
|
2023-03-20 05:20:10
| 1
| 593
|
ShoutOutAndCalculate
|
75,786,744
| 19,327,879
|
Drop down value disappear closing when I click drop down to inspect, find xpath. How to find drop down value which collapse as soon as I click on it
|
<p>How to get drop down value or xpath in selenium when drop down is not of Select type.
How to find drop down value xpath of div type elements?
I am clicking on drop down value to find xpath and it is collapsing and hiding?
I am not able to find drop down values in dom html file.
#React #Dropdown values Xpath.
Dynamic Drop down Xpath Selenium
How to avoid drop down closing after i clicked the drop down, actually i want to read the drop down values</p>
<p>I am clicking on drop down value to find xpath and it is collapsing and hiding?
I am not able to find drop down values in dom html file.</p>
|
<python><selenium-webdriver><xpath><drop-down-menu><selenium-chromedriver>
|
2023-03-20 05:13:18
| 2
| 336
|
Sachin
|
75,786,740
| 15,412,256
|
heroku + github path error in the log - cannot find the file path
|
<p>I deployed my github master branch to heroku. One of my code tries to access a file in the <code>misc</code> directory under the same branch. However, the log on heroku shows that the file does not exist. Please see the screenshot as follows:</p>
<p><a href="https://i.sstatic.net/3k2wr.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/3k2wr.png" alt="enter image description here" /></a></p>
|
<python><github><heroku><discord><cloud>
|
2023-03-20 05:12:18
| 1
| 649
|
Kevin Li
|
75,786,699
| 1,106,951
|
How to find keys in second dictionary which has different value compare to first dictionary
|
<p>I can use <code>diff = set(dict2) - set(dict1)</code> to know that the <code>dict1</code> and <code>dict2</code> are not equal but what I need is to find which KEY in <code>dict2</code> has a different value than <code>dict1</code></p>
<pre><code> dict1 = {'c1': 'Iran', 'c2': 'India', 'c3': 'Iraq', 'c4': 'Qatar'}
dict2 = {'c1': 'Iran', 'c2': 'India', 'c3': 'Iraqs','c4': 'Qeter'}
diff = set(dict2) - set(dict1)
print(diff)
</code></pre>
<p>Basically what I want to get in return are <code>{'c3', 'c4'}</code></p>
|
<python>
|
2023-03-20 05:00:21
| 3
| 6,336
|
Behseini
|
75,786,601
| 12,931,358
|
How to convert TrainingArguments object into a json file?
|
<p>I want to convert an object of TrainingArguments into a json file and load json when training model because I think it didn't look better in main function and hard to check all parameters in TrainingArguments, for example,</p>
<pre><code>import json
import dataclasses
from transformers import TrainingArguments
class EnhancedJSONEncoder(json.JSONEncoder):
def default(self, obj):
if dataclasses.is_dataclass(obj):
return dataclasses.asdict(obj)
#return super().default(obj)
def save_json(json_path, file_args):
file_str = json.dumps(file_args, cls=EnhancedJSONEncoder)
file_json = json.loads(file_str)
with open(json_path, "w") as f:
json.dump(file_json, f, indent=4)
if __name__ == "__main__":
training_args = TrainingArguments(
output_dir = "train_model",
do_eval=True,
do_predict=False,
do_train=True,
eval_steps=20,
save_steps=-1,
per_device_eval_batch_size=8,
per_device_train_batch_size=4,
max_steps=1000,
learning_rate=7e-05,
evaluation_strategy="steps",
dataloader_num_workers=1,
)
training_args._n_gpu = 1
save_json("training_args.json",training_args)
</code></pre>
<p>Thus, firstly, I save <code>training_args</code> to a json file, if I want to use parameters in <code>training_args</code> I directly import from json file,
from types import SimpleNamespace</p>
<pre><code>with open("training_args.json", 'r') as f:
training_json = json.load(f)
training_args = SimpleNamespace(**training_json)
</code></pre>
<p>It can correctly show <code>training_args.output_dir</code>,<code>training_args.do_train</code></p>
<p>However, when I run</p>
<pre><code>trainer = transformers.Trainer(
model=model,
args=training_args,
train_dataset=train_dataset if training_args.do_train else None,
eval_dataset=eval_dataset if training_args.do_eval else None,
tokenizer=tokenizer,
data_collator=data_collator,
compute_metrics=compute_metrics,
)
</code></pre>
<p>it shows error, <code>'types.SimpleNamespace' object has no attribute 'get_process_log_level'</code></p>
<p>If I print TrainingArguments.get_process_log_level(), it shows</p>
<p><bound method TrainingArguments.get_process_log_level of TrainingArguments(
_n_gpu=1,
adafactor=False, #etc..
)</p>
|
<python><json><deep-learning><pytorch><huggingface-transformers>
|
2023-03-20 04:34:43
| 1
| 2,077
|
4daJKong
|
75,786,523
| 1,609,428
|
how to limit the display width in polars so that wide dataframes are printed in a legible way?
|
<p>Consider the following example</p>
<pre><code>pd.set_option('display.width', 50)
pl.DataFrame(data = np.random.randint(0,20, size = (10, 42)),
columns = list('abcdefghijklmnopqrstuvwxyz123456789ABCDEFG')).to_pandas()
</code></pre>
<p><a href="https://i.sstatic.net/Rxv9h.png" rel="noreferrer"><img src="https://i.sstatic.net/Rxv9h.png" alt="enter image description here" /></a></p>
<p>You can see how nicely the columns are formatted, breaking a line after column k so that the full dataframe is printed in chunks in the console. This was controlled by the pandas <code>width</code> argument above. I was not able to reproduce this behavior using <code>polars</code> and all the <code>format options</code>.</p>
<p>I have tried tweaking all possible settings:</p>
<pre><code>pl.Config.set_tbl_cols(10)
pl.Config.set_fmt_str_lengths(10)
pl.Config.set_tbl_width_chars(70)
pl.Config.set_tbl_rows(2)
pl.Config.set_tbl_formatting('NOTHING')
pl.Config.set_tbl_column_data_type_inline(True)
pl.Config.set_tbl_dataframe_shape_below(True)
</code></pre>
<p>See below:</p>
<p><a href="https://i.sstatic.net/lK7Za.png" rel="noreferrer"><img src="https://i.sstatic.net/lK7Za.png" alt="enter image description here" /></a></p>
<p>Any ideas? Thanks!</p>
|
<python><dataframe><python-polars>
|
2023-03-20 04:14:44
| 2
| 19,485
|
ℕʘʘḆḽḘ
|
75,786,481
| 15,010,256
|
Python - check if condition is met within a given timeout
|
<p>I've a script that 1. downloads & push binaries to internal registry (func_to_push_image) and
2. process messages from a section of messaging queue, to see if the push is successful by filtering the messages for a keyword 3. If the push is successful, monitor and process another section of messaging queue, to validate whether those two binaries are installed by looking at the install_status keyword.</p>
<p>Timeout for the push action is 2 mins, else fail the script immediately. Timeout for the install action is 1 min, else fail the script with timeout.</p>
<p>Messaging queue's output for the binaries installations looks like below.</p>
<pre><code>{
"location": "root",
"md5":"a3288ec45c8d159fbb656972eb4cdfg84jsfbsdf",
"fireEye":"v3",
"Binaries":[
A:{
"name":"HP-Protect",
"version": "v1.3",
"effect": "NIL",
"install_status":"On Going",
}
B:{
"name":"Covertur",
"version": "v1.0",
"effect": "NIL",
"install_status":"Installed"
}]
}
</code></pre>
<p>Redacted code:</p>
<pre><code>registry_timeout = 2
install_timeout = 1
Other variables holding server and partition details.
def get_info_from_messaging_queue(server, broker):
depending on the partition, returns the messages from the messaging queue.
def func_to_push_image():
logic to upload the artifact to the registry.
def func_to_check_status_of_installed_binaries(): #This function should Ideally check the status of both binaries has been "Completed"
status = False
install_status = get_info_from_messaging_queue(server, broker)
if install_status['Binaries'][A]['install_status'] == "Completed" and install_status['Binaries'][B]['install_status'] == "Completed":
status = True
return status
# to check if image is pushed within 2 minutes.
def timeout_verify_push_status():
start = datetime.now()
stop = start + timedelta(minutes=registry_timeout)
while True:
push_status = func_to_push_image()
if push_status:
break
start = datetime.now()
if start > stop_time:
print("Timed Out while pushing image to registry...")
break
# to check if installation is complete within a minute..
def timeout_verify_installation_status()():
start = datetime.now()
stop = start + timedelta(minutes=install_timeout)
while True:
install_status = func_to_check_status_of_installed_binaries()
if install_status:
break
start_time = datetime.now()
if start_time > stop_time:
print("Timeout while installtion of Binaries...")
break
if __name__ == '__main__':
timeout_verify_push_status()
timeout_verify_installation_status()
</code></pre>
<p>This gets the job done, it timeouts if the status is not Completed with in a minute, but it isn't efficient and I tried to handle the timeout condition using a single function but failed. How efficiently can it be handled ?</p>
|
<python><python-3.x>
|
2023-03-20 04:02:01
| 1
| 466
|
Chel MS
|
75,786,332
| 213,759
|
How to create a stub Python package for PyCharm?
|
<p>Let's say we have a builtin module <code>car</code>.</p>
<p>We have no autocomplete in PyCharm for it.</p>
<p>It has interface:</p>
<pre class="lang-py prettyprint-override"><code>def getState(id, optional_id = None):
pass
def log(value):
pass
</code></pre>
<p>So, end usage would be:</p>
<pre class="lang-py prettyprint-override"><code>import car
car.getState(5)
car.log('Test')
</code></pre>
<p>How to create a package and join it into PyCharm to make autocomplete work for a described interface?</p>
<p>If I created a package <code>car-stub</code> with <code>car.py</code> file, and installed it in the project, I will have to use code line <code>from car-stub import car</code>.</p>
<p>But how to make it in such a way it would not require code changes?<br> The system would provide autocomplete for <code>import car</code>.</p>
|
<python><python-3.x><interface><stub>
|
2023-03-20 03:20:37
| 1
| 3,127
|
Kirby
|
75,786,157
| 6,020,411
|
How to properly retrieve values/settings from a Python Tkinter radiobutton
|
<p>Dinking around with a Tkinter window sporting a pair of radio buttons:</p>
<pre><code>from tkinter import *
window = Tk()
window.title("Python Radio Buttons")
# Tkinter string variable
# able to store any string value
v = StringVar(window, "1")
def handle_click(event):
print(v.get())
for child in window.children.items():
if(type(child[1]) is Radiobutton):
print("It's a radio button")
# Dictionary to create multiple buttons
values = {"RadioButton 1" : "1",
"RadioButton 2" : "2"}
# Loop is used to create multiple Radiobuttons
# rather than creating each button separately
for (text, value) in values.items():
rb = Radiobutton(window, text = text, variable = v,
value = value)
rb.bind("<Button-1>", handle_click)
rb.pack(side = TOP, ipady = 5)
# Infinite loop can be terminated by
# keyboard or mouse interrupt
# or by any predefined function (destroy())
mainloop()
</code></pre>
<p>Problem 1 is when I click on a radio button, the v.get() returns the value from the other radio button so the click appears to be lagging. Where am I going wrong here?</p>
<p>Problem 2 is I thought I might iterate through all the radio buttons to see which one was checked, but I don't see any properties (like value or checked) I can poll to get that information. If I can't do that, I am back to problem 1. Any suggestions?</p>
<p>TIA</p>
|
<python><tkinter>
|
2023-03-20 02:31:34
| 3
| 753
|
ds_practicioner
|
75,786,066
| 10,616,752
|
Beautiful Soup can't find comment
|
<p>I am trying to use bs4 to scrape a page but key to my objective is finding a comment in the page.</p>
<p>I cannot make bs4 find it. Can you help. This is my code:</p>
<pre><code> # Parse the HTML content with BeautifulSoup
soup = BeautifulSoup(response.content, "html.parser")
# Find the first comment that starts with "<!-- a -->"
start_comment = soup.find(string=lambda text: isinstance(text, Comment) and "<!-- a -->" in text)
</code></pre>
<p>The comment is in the text of the html just like this is but my code is unable to find the comment for <!-- a -->:</p>
<pre><code><h4>Some Heading</h4>
<!-- a -->
</code></pre>
<p>Can anyone see why bs4 is just breezing on by this comment even though I am specifically searching for it please? Is there another operator I should be using here...</p>
|
<python><beautifulsoup>
|
2023-03-20 02:05:58
| 1
| 546
|
Scouse_Bob
|
75,785,945
| 1,424,739
|
how to get the least number of elements whose sum is greater than n?
|
<pre><code>a = ['a', 'bc', 'def', 'hijk']
n = 5
i = 0
l = 0
for x in a:
l += len(x)
if l > n:
break
i += 1
print(i) # get 2 meaning the 3rd element.
</code></pre>
<p>I use the above code to get the least number of elements whose total length is greater than n. It involves for-loop. I am not sure if for-loop is efficient. Is there any more efficient implementation than this?</p>
|
<python>
|
2023-03-20 01:30:31
| 1
| 14,083
|
user1424739
|
75,785,932
| 3,622,232
|
Python: How do I store a nonlocal variable's value in an inner function when it's created?
|
<p>If I have an outer function returning an inner function like so:</p>
<pre><code>def outer():
outer_var = 1
def inner():
return outer_var
outer_var = 2
return inner
</code></pre>
<p>Calling <code>outer()()</code> will return 2. However, I want the inner function to return the value outer_var had when the inner function was created, not when it was called.</p>
<p>The only solution I could come up with was:</p>
<pre><code>def outer():
outer_var = 1
def inner(inner_var=outer_var):
return inner_var
outer_var = 2
return inner
</code></pre>
<p>Calling <code>outer()()</code> will now return 1. Is there a better solution that doesn't need kwargs? I don't think it's necessary to mention that in my actual code outer_var will only be known at runtime.</p>
|
<python><function><scope><runtime>
|
2023-03-20 01:26:36
| 1
| 2,017
|
uzumaki
|
75,785,695
| 5,302,323
|
Coverting dates on the same pd column that are in different format (Excel float + dd/mm/yy) into Python dates
|
<p>I am really struggling to convert two different types of dates on the same pd dataframe into python dates.</p>
<p>This is the type of dates I have:</p>
<pre><code>1 44859
2 7/12/22
3 6/12/22
</code></pre>
<p>Here is the code I have tried so far but it still results in NaT for the Excel format dates (integers that represent the actual date).</p>
<pre><code>import pandas as pd
import xlrd
# define function to convert Excel float dates to Python dates using xlrd
def excel_to_date(excel_date):
return xlrd.xldate_as_datetime(excel_date, 0).date() # assuming 0-based indexing
# convert Excel float dates to Python dates using the defined function
df['date'] = df['date'].apply(lambda x: excel_to_date(x) if isinstance(x, float) else x)
# convert remaining dates to Python dates using to_datetime()
df['date'] = pd.to_datetime(df['date'], errors='coerce')
print(df)
</code></pre>
<p>Any help would be really appreciated!</p>
|
<python>
|
2023-03-20 00:04:04
| 0
| 365
|
Cla Rosie
|
75,785,663
| 15,900,832
|
mkdocs/mkdocstrings: add link back to GitHub source code
|
<p>I am making docs for my Python code with mkdocs and mkdocstrings.</p>
<p>I would like to have link from the docs to the source code (page and line number on github).</p>
<p>Is there a way to automatic add that with function/class syntax (e.g., '::: identifier')?</p>
<p>I am looking for something similar to 'SciPy' docs, where they have [source] button (right of function heading).
For an example: <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.poisson.html" rel="noreferrer">Poisson distribution</a></p>
|
<python><github><mkdocs><mkdocstrings>
|
2023-03-19 23:56:02
| 1
| 633
|
basil_man
|
75,785,588
| 8,272,788
|
MQTT messages going to broker but not client
|
<p>I have a project publishing MQTT messages from an ESP to a broker running on a Pi, and client running on the Pi. Messages are reliably getting from the ESP to the broker, as I can observe them using <code>mosquitto_sub</code>, however the client only receives them sporadically. I have tried setting QOS to 1 and 2, but it hasn't resolved. Wondering if anyone can help me spot the issue.</p>
<p>Here is the code on the ESP (micropython) - this is effectively working fine:</p>
<pre><code>from umqtt.simple import MQTTClient
broker_ip = "[IP]"
client_name = "[client]"
user = "[user]"
password = "[password]"
def connect_publish(broker, client, topic, message, user, password):
print("Creating client object...")
client = MQTTClient(client_id=client_name,
server=broker_ip,
user=user,
password=password,
keepalive=60)
print("Connecting to server...")
client.connect()
print("Publishing message")
client.publish(topic = topic, msg = str(message), qos = 1)
print("Published", message, "to", topic)
print("Disconecting from server")
client.disconnect()
[function to connect to wifi]
[initialize sensor]
while True:
if [sensor_trigger]:
connect_publish(broker = broker_ip,
client = client_name,
topic = b"sensor",
message = "on",
user = user,
password = password)
</code></pre>
<p>Code on the client - running on the Pi (python):</p>
<pre><code>#!/usr/bin/env python3
import paho.mqtt.client as paho
import time
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected with result code " + str(rc))
else:
print("Failed to subscribe, code:", rc)
client.subscribe("sensor", qos = 1)
def on_message(client, userdata, msg):
print(msg.topic+" "+ msg.payload.decode())
if msg.payload.decode() == "on":
if [some further conditions defined in variables below]:
[do something]
#Initialize the variables for MQTT
BROKER = '[IP]'
#uname and password for mqtt client stored on pi: /etc/mosquitto/passwd
uname = '[user]'
pwd = '[password]'
#Initialize all the paho functions
client = paho.Client('[name]')
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(password = pwd, username = uname)
client.connect(host = BROKER)
client.loop_start()
[initialize some more variables]
while True:
[update some variables]
time.sleep(0.1)
</code></pre>
<p>Essentially I reliably see the messages <code>mosquitto_sub</code> on the broker, but don't see the print statements (nor do i see the outcomes of the commands) in the <code>on_message</code> function running on the client - even with <code>qos = 1</code>. I tried 2, made no difference.</p>
|
<python><mqtt><paho><micropython>
|
2023-03-19 23:33:40
| 1
| 1,261
|
MorrisseyJ
|
75,785,409
| 15,176,150
|
What's the fastest way to append to a list with Numba?
|
<p>I'm creating some code that does a lot of list appends. It has to be performant so I'm using <a href="https://numba.pydata.org/" rel="nofollow noreferrer">Numba</a> to <code>@jit</code> compile it.</p>
<p>I've checked the <a href="https://numba.pydata.org/numba-doc/dev/reference/pysupported.html#list" rel="nofollow noreferrer">Numba documentation</a> on lists, but it doesn't give much information on the best way to append to them.</p>
<p>Should I use the <code>list1 + list2</code> notation, or should I used <code>list1.append(value)</code>?</p>
|
<python><list><append><numba><jit>
|
2023-03-19 22:50:43
| 1
| 1,146
|
Connor
|
75,785,259
| 15,209,311
|
Python "on_destroy" class method
|
<p>I am wondering if there is a way to call a method before the object is finally "destroyed" - like some sort of event.</p>
<p>I am using a class and a static method. Since it is not an instantiated object, I cannot use <code>del</code> and modify <code>__del__</code> on it.</p>
<p>Is the object garbage collected at all if not instantiated?</p>
<p>For example:</p>
<pre><code>class Test:
@staticmethod
def say_hello():
print("Hello")
def on_destroy(self):
print("Object was destroyed...")
Test.say_hello()
</code></pre>
<p>What I want to achieve is that the method <code>on_destroy</code> will fire after <code>say_hello</code> since I am using a static method.</p>
<p>I tried using <code>__del__</code> and it is not being called.</p>
<p>Thansk for the help.</p>
|
<python><python-3.x><class><oop><python-class>
|
2023-03-19 22:15:25
| 2
| 619
|
Niv
|
75,784,905
| 18,493,710
|
cannot upload audio files in Bale bot using python-bale-bot
|
<p>I intend to create a bot in a Telegram-like messenger called Bale that should send audio files. I am using <a href="https://github.com/python-bale-bot" rel="nofollow noreferrer">python-bale-bot</a> which is a wrapper for Bale Messenger API. When I try to open the mp3 file and read it and pass it to the method, I get an error that I did not find its solution anywhere.</p>
<p>Here is the code:</p>
<pre><code>"""keyboard handler"""
@client.listen(EventType.CALLBACK)
async def when_receive_callback(callback: CallbackQuery):
if callback.data == "audio":
audio_file = open("/path_to/audio_file.mp3","rb")
audio = audio_file.read()
await callback.message.reply_document(audio)
</code></pre>
<p>And when the users clicks on the keyboard button and the callback is sent, I get the following error:</p>
<pre><code>error on_callback Can not serialize value type: <class 'int'>
headers: {}
value: 800646076
</code></pre>
<p>Any ideas?</p>
|
<python><bale-messenger>
|
2023-03-19 21:02:05
| 1
| 418
|
okaeiz
|
75,784,875
| 5,246,226
|
Can another thread release a lock held by another thread in Python?
|
<p>I am trying to understand threading in Python via <a href="https://realpython.com/intro-to-python-threading/" rel="nofollow noreferrer">this website</a>. Here, it has the following code for a single producer/consumer-type problem:</p>
<pre><code>import random
SENTINEL = object()
def producer(pipeline):
"""Pretend we're getting a message from the network."""
for index in range(10):
message = random.randint(1, 101)
logging.info("Producer got message: %s", message)
pipeline.set_message(message, "Producer")
# Send a sentinel message to tell consumer we're done
pipeline.set_message(SENTINEL, "Producer")
def consumer(pipeline):
"""Pretend we're saving a number in the database."""
message = 0
while message is not SENTINEL:
message = pipeline.get_message("Consumer")
if message is not SENTINEL:
logging.info("Consumer storing message: %s", message)
if __name__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,
datefmt="%H:%M:%S")
# logging.getLogger().setLevel(logging.DEBUG)
pipeline = Pipeline()
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
executor.submit(producer, pipeline)
executor.submit(consumer, pipeline)
class Pipeline:
"""
Class to allow a single element pipeline between producer and consumer.
"""
def __init__(self):
self.message = 0
self.producer_lock = threading.Lock()
self.consumer_lock = threading.Lock()
self.consumer_lock.acquire()
def get_message(self, name):
logging.debug("%s:about to acquire getlock", name)
self.consumer_lock.acquire()
logging.debug("%s:have getlock", name)
message = self.message
logging.debug("%s:about to release setlock", name)
self.producer_lock.release()
logging.debug("%s:setlock released", name)
return message
def set_message(self, message, name):
logging.debug("%s:about to acquire setlock", name)
self.producer_lock.acquire()
logging.debug("%s:have setlock", name)
self.message = message
logging.debug("%s:about to release getlock", name)
self.consumer_lock.release()
logging.debug("%s:getlock released", name)
</code></pre>
<p>IIUC, the consumer lock is acquired and released in different threads (and the producer too). Is this possible? It feels like I'm missing something because then couldn't any thread release a lock held by another thread?</p>
|
<python><multithreading>
|
2023-03-19 20:56:27
| 1
| 759
|
Victor M
|
75,784,606
| 16,283,580
|
sqlalchemy: concat strings with + sign
|
<p>I try to concatenate 3 parts together into an SQL expression with <code>sqlalchemy</code>:</p>
<pre><code>func.date(cls.entry_date, '+' + cls.duration + ' year', '-1 day')
</code></pre>
<p>The SQL statement produced is:</p>
<pre><code>date("My_Table"."Entry date", '+' + "My_Table"."Durée" || ' year', '-1 day', '-1 day')
</code></pre>
<p>instead of</p>
<pre><code>date("My_Table"."Entry date", '+' || "My_Table"."Durée" || ' year', '-1 day', '-1 day')
</code></pre>
<p>The last sign <code>+</code> is correctly transformed to <code>||</code> (between "My_Table"."Durée" and ' year')</p>
<p>The first sign <code>+</code> is left as is in SQL statement (between '+' and "My_Table"."Durée")</p>
<p>I cannot figure out why.</p>
<p>I tried to change the string character<code>'+'</code> to some other character as I thought it could interfere with the concatenation <code>+</code> but it does not change anything.</p>
<p><strong>Edit</strong></p>
<p>I tried to use <code>func.concat('+', cls.duration, ' year')</code> but sqlite does not understand <code>concat</code>.</p>
<p>Of course I could use f-strings:</p>
<pre><code>func.date(cls.entry_date, f"""'+ "{cls.duration.name}" year'""", '-1 day')
</code></pre>
<p>but I cannot believe that there is not a smarter manner</p>
|
<python><sqlite><sqlalchemy>
|
2023-03-19 19:58:31
| 1
| 321
|
zigma12
|
75,784,544
| 11,280,068
|
Jinja convert chat.js charts to images when rendering template
|
<p>I have a question about javascript within Jinja2 before I start on my project, so I can understand if jinja is the right solution to use</p>
<ul>
<li><p>I want to create an html email template that will fill in some values for each user, and then send them the rendered template via email. I already have the email functionality set up</p>
</li>
<li><p>I want to include some charts from chart.js on the page, but because JS isn't allowed on emails I have to convert the charts to images before sending the email.</p>
</li>
</ul>
<h4>My question is, does jinja allow for this to happen when rendering the template? Can I make sure that the charts are converted to images when the template is rendered, and all JS is removed/inactive before sending the template?</h4>
|
<javascript><python><html><chart.js><jinja2>
|
2023-03-19 19:43:46
| 1
| 1,194
|
NFeruch - FreePalestine
|
75,784,491
| 158,801
|
How to read path variables / binding data in Python Azure BlobTrigger Function?
|
<p>How do I read {email} in Python Azure BlobTrigger function?</p>
<p>function.json</p>
<pre><code>{
"scriptFile": "__init__.py",
"bindings": [
{
"name": "myBlob",
"type": "blobTrigger",
"direction": "in",
"path": "folder1/{email}/{filename}",
"connection": "..."
}
]
}
</code></pre>
<p><strong>init</strong>.py</p>
<pre><code>import logging
import azure.functions as func
def main(myBlob: func.InputStream):
logging.info(f"Email: {??????}")
</code></pre>
|
<python><azure><azure-functions><azure-blob-storage>
|
2023-03-19 19:33:34
| 1
| 10,849
|
Mikeon
|
75,784,453
| 6,440,589
|
Evaluating a string as a numpy array
|
<p>My team is migrating from <strong>Clickhouse</strong> to <strong>Azure Data Explorer</strong> (ADX). We are currently experiencing difficulties to query our data from ADX: the queried values are correct, but the data are read as a <strong>string</strong> rather than as an array of <strong>floats</strong>.</p>
<p>Here is an example string:</p>
<p><code>mydummystring='[1.0,2.0,3.0][4.0,5.0,6.0][6.0,7.0,8.0]'</code></p>
<p>In order to convert this string to a numpy array, I found this workaround based on list comprehension (inspired by <a href="https://stackoverflow.com/a/70117942/6440589">this SO post</a>):</p>
<pre><code>import numpy as np
mynumpyarray = np.array([np.array(x) for x in eval('['+mydummystring.replace('][', '],[')+']')])
</code></pre>
<p>Is there a better (safer?) way to achieve this conversion? I know that it would be better to read the data correctly in the first place, but for now I am looking for a robust way to convert the output string to actual numbers.</p>
|
<python><list-comprehension><eval>
|
2023-03-19 19:25:42
| 3
| 4,770
|
Sheldon
|
75,784,338
| 5,644,961
|
How to make mypy like my protocols that work at runtime with runtime_checkable
|
<p>I defined a couple of protocols like so:</p>
<pre class="lang-py prettyprint-override"><code>import json
from typing import Any, Protocol, TypeVar, runtime_checkable
T_co = TypeVar('T_co', covariant=True)
T = TypeVar('T')
@runtime_checkable
class SupportsRead(Protocol[T_co]):
def read(self, __length: int = ...) -> T_co: ...
@runtime_checkable
class SupportsWrite(Protocol[T_co]):
def write(self, data: str | bytes): ...
@runtime_checkable
class SerializerToString(Protocol):
def dumps(self, value: Any, *argv, **kwargs) -> str: ...
def loads(self, value: str | bytes, *argv, **kwargs) -> Any: ...
@runtime_checkable
class SerializerToFile(Protocol):
def dump(self, value: Any, file: SupportsWrite[str | bytes], **kwargs) -> None: ...
def load(self, file: SupportsRead[str | bytes], **kwargs) -> Any: ...
@runtime_checkable
class Serializer(SerializerToString, SerializerToFile, Protocol):
pass
class MySerializer:
def dumps(self, value: Any) -> str:
return f"dumps {value}"
def loads(self, value: str) -> Any:
return f"loads {value}"
var1: SerializerToFile = json
var2: SerializerToString = json
var3: Serializer = json
var4: SerializerToString = MySerializer()
assert isinstance(var1, SerializerToFile)
assert isinstance(var2, SerializerToString)
assert isinstance(var3, Serializer)
assert isinstance(var4, SerializerToString)
print("everything ok")
</code></pre>
<p>It runs without error, but mypy marks all the assigments to <code>var1</code>-<code>var4</code> with errors like so:</p>
<pre><code>test11.py:42: error: Incompatible types in assignment (expression has type Module, variable has type "SerializerToFile") [assignment]
test11.py:42: note: Following member(s) of "Module json" have conflicts:
test11.py:42: note: Expected:
test11.py:42: note: def dump(value: Any, file: SupportsWrite[Union[str, bytes]], **kwargs: Any) -> None
test11.py:42: note: Got:
test11.py:42: note: def dump(obj: Any, fp: SupportsWrite[str], *, skipkeys: bool = ..., ensure_ascii: bool = ..., check_circular: bool = ..., allow_nan: bool = ..., cls: Optional[Type[JSONEncoder]] = ..., indent: Union[None, int, str] = ..., separators: Optional[Tuple[str, str]] = ..., default: Optional[Callable[[Any], Any]] = ..., sort_keys: bool = ..., **kwds: Any) -> None
test11.py:42: note: Expected:
test11.py:42: note: def load(file: SupportsRead[Union[str, bytes]], **kwargs: Any) -> Any
test11.py:42: note: Got:
test11.py:42: note: def load(fp: SupportsRead[Union[str, bytes]], *, cls: Optional[Type[JSONDecoder]] = ..., object_hook: Optional[Callable[[Dict[Any, Any]], Any]] = ..., parse_float: Optional[Callable[[str], Any]] = ..., parse_int: Optional[Callable[[str], Any]] = ..., parse_constant: Optional[Callable[[str], Any]] = ..., object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., **kwds: Any) -> Any
test11.py:43: error: Incompatible types in assignment (expression has type Module, variable has type "SerializerToString") [assignment]
test11.py:43: note: Following member(s) of "Module json" have conflicts:
test11.py:43: note: Expected:
test11.py:43: note: def dumps(value: Any, *argv: Any, **kwargs: Any) -> str
test11.py:43: note: Got:
test11.py:43: note: def dumps(obj: Any, *, skipkeys: bool = ..., ensure_ascii: bool = ..., check_circular: bool = ..., allow_nan: bool = ..., cls: Optional[Type[JSONEncoder]] = ..., indent: Union[None, int, str] = ..., separators: Optional[Tuple[str, str]] = ..., default: Optional[Callable[[Any], Any]] = ..., sort_keys: bool = ..., **kwds: Any) -> str
test11.py:43: note: Expected:
test11.py:43: note: def loads(value: Union[str, bytes], *argv: Any, **kwargs: Any) -> Any
test11.py:43: note: Got:
test11.py:43: note: def loads(s: Union[str, bytes, bytearray], *, cls: Optional[Type[JSONDecoder]] = ..., object_hook: Optional[Callable[[Dict[Any, Any]], Any]] = ..., parse_float: Optional[Callable[[str], Any]] = ..., parse_int: Optional[Callable[[str], Any]] = ..., parse_constant: Optional[Callable[[str], Any]] = ..., object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., **kwds: Any) -> Any
test11.py:44: error: Incompatible types in assignment (expression has type Module, variable has type "Serializer") [assignment]
test11.py:44: note: Following member(s) of "Module json" have conflicts:
test11.py:44: note: Expected:
test11.py:44: note: def dump(value: Any, file: SupportsWrite[Union[str, bytes]], **kwargs: Any) -> None
test11.py:44: note: Got:
test11.py:44: note: def dump(obj: Any, fp: SupportsWrite[str], *, skipkeys: bool = ..., ensure_ascii: bool = ..., check_circular: bool = ..., allow_nan: bool = ..., cls: Optional[Type[JSONEncoder]] = ..., indent: Union[None, int, str] = ..., separators: Optional[Tuple[str, str]] = ..., default: Optional[Callable[[Any], Any]] = ..., sort_keys: bool = ..., **kwds: Any) -> None
test11.py:44: note: Expected:
test11.py:44: note: def dumps(value: Any, *argv: Any, **kwargs: Any) -> str
test11.py:44: note: Got:
test11.py:44: note: def dumps(obj: Any, *, skipkeys: bool = ..., ensure_ascii: bool = ..., check_circular: bool = ..., allow_nan: bool = ..., cls: Optional[Type[JSONEncoder]] = ..., indent: Union[None, int, str] = ..., separators: Optional[Tuple[str, str]] = ..., default: Optional[Callable[[Any], Any]] = ..., sort_keys: bool = ..., **kwds: Any) -> str
test11.py:44: note: <2 more conflict(s) not shown>
test11.py:45: error: Incompatible types in assignment (expression has type "MySerializer", variable has type "SerializerToString") [assignment]
test11.py:45: note: Following member(s) of "MySerializer" have conflicts:
test11.py:45: note: Expected:
test11.py:45: note: def dumps(self, value: Any, *argv: Any, **kwargs: Any) -> str
test11.py:45: note: Got:
test11.py:45: note: def dumps(self, value: Any) -> str
test11.py:45: note: Expected:
test11.py:45: note: def loads(self, value: Union[str, bytes], *argv: Any, **kwargs: Any) -> Any
test11.py:45: note: Got:
test11.py:45: note: def loads(self, value: str) -> Any
Found 4 errors in 1 file (checked 1 source file)
</code></pre>
<p>Is there a way to please mypy with those protocols?</p>
|
<python><python-typing><mypy>
|
2023-03-19 19:05:02
| 1
| 8,635
|
Copperfield
|
75,784,094
| 4,502,950
|
ValueError: time data '23/11/2022' does not match format '%m/%d/%Y' (match)
|
<p>I have user-entered data where some people put the date as 'm/d/y' while others entered it as 'd/m/y'. I am trying to convert the column to datetime using try except blocks. But it keeps throwing me this error</p>
<pre><code>ValueError: time data '23/11/2022' does not match format '%m/%d/%Y' (match)
</code></pre>
<p>I know it doesn't match the format as 23 is not a month, but this is exactly why I am using the try and except blocks.</p>
<pre><code>date_df = pd.DataFrame({'timestamp':['11/23/2022', '23/11/2022']})
try:
date_df['timestamp'] = pd.to_datetime(date_df['timestamp'], format = '%d/%m/%Y').dt.strftime('%d/%m/%Y')
except ValueError:
date_df['timestamp'] = pd.to_datetime(date_df['timestamp'], format = '%m/%d/%Y').dt.strftime('%d/%m/%Y')
</code></pre>
<p>It seems like the try block is not even executing. The result should be:</p>
<pre><code>timestamp
23/11/2022
23/11/2022
</code></pre>
|
<python><datetime>
|
2023-03-19 18:21:39
| 2
| 693
|
hyeri
|
75,784,057
| 8,201,204
|
Jupyter notebook command doesn't bring up Jupyter
|
<p>I am using windows 11
I installed Python latest version and installed pip also
I installed Jupyter using the command (at command prompt) "pip install jupyter"
Installation went fine.</p>
<p>When I try to launch Jupyter notebook using the command "jupyter notebook" it says "jupyter is not a recognzied internal or external command"</p>
<p>Can someone suggest what I am doing wrong?</p>
<p><a href="https://i.sstatic.net/aJ7Ol.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/aJ7Ol.png" alt="enter image description here" /></a></p>
|
<python><windows><jupyter-notebook><pip>
|
2023-03-19 18:15:32
| 2
| 557
|
Jason
|
75,784,038
| 1,011,253
|
Python multiprocessing application is getting stuck in docker container
|
<p>I am trying to run a multiprocessing Python application to speedup and parallel my tasks.
My application is using a simple multiprocessing <code>Pool</code> and running within docker container with limited resources.</p>
<p>I have noticed that my application is getting stuck from time to time; It's never end/terminated but nothing moves (tasks stop running, no logs).</p>
<p>After digging around, I found that it's a memory issue: if there's is not enough RAM the application keeps running (doing nothing), but if I add more memory to the container, all tasks finish successfully and the container finish and exit.</p>
<p>I was expecting for either:</p>
<ol>
<li>A retry mechanism.</li>
<li>An exception (of a dying Process, OOM, etc.).</li>
<li>A log message with a proper severity.</li>
</ol>
<p>None of them happen. Is there a way to make <code>multiprocessing</code> to give me some feedback instead of being so quite?</p>
<p>Below you can find a simple reproducible <a href="https://github.com/itayB/aiomultiprocess-mem/tree/multi" rel="nofollow noreferrer">example</a>, with a stupid task that's only eat the memory. Running it with <code>--memory=2g</code> will stuck forever with no indication, while running it with <code>--memory=3g</code> finish successfully after a few minutes:</p>
<pre><code>docker build -t multiprocess_mem .
docker run --rm --memory=2g --cpus=5 multiprocess_mem
</code></pre>
<p>Application's tree structure:</p>
<pre><code>├── Dockerfile
└── multi
├── __init__.py
├── __main__.py
└── app.py
</code></pre>
<p><code>app.py</code></p>
<pre><code>import logging
import os
import sys
from multiprocessing import Pool
logger = logging.getLogger(__name__)
def init_logger():
logging.basicConfig(
format="%(asctime)-15s %(process)d %(levelname)-18.18s %(message)s [%(filename)s:%(lineno)d]",
stream=sys.stdout
)
logging.root.setLevel(logging.INFO)
def my_mem_task(task_id):
logger.info(f"T{task_id:03} started!")
data = []
for i in range(100_000):
data.append([i] * 1_000)
logger.info(f"T{task_id:03} {len(data)}")
def main():
init_logger()
number_of_processes = int(os.getenv("NUMBER_OF_PROCESSES", "4"))
logger.info("creating pool")
with Pool(
processes=number_of_processes,
initializer=init_logger,
) as pool:
task_ids = [task_id for task_id in range(150)]
pool.map(my_mem_task, task_ids)
pool.close()
logger.info("processes pool closed")
pool.join()
logger.info("all processes are done")
</code></pre>
<p><code>__main__.py</code>:</p>
<pre><code>from multi.app import main
if __name__ == "__main__":
main()
</code></pre>
<p><code>Dockerfile</code>:</p>
<pre><code>FROM python:3.11.2-slim-bullseye
WORKDIR /
COPY multi /multi
CMD ["python", "-m", "multi"]
</code></pre>
<p>Lastly, <code>exec</code> into the "stuck" container shows that both parent & child processes are still running:</p>
<pre><code>docker exec -it <container_id> bash
root@ff5ca6bf92f3:/# apt-get update && apt-get install -y procps
...
root@ff5ca6bf92f3:/# ps -ef
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 18:06 ? 00:00:00 python -m multi
root 9 1 55 18:06 ? 00:01:24 python -m multi
root 10 1 55 18:06 ? 00:01:24 python -m multi
root 15 1 29 18:07 ? 00:00:36 python -m multi
root 19 1 28 18:07 ? 00:00:30 python -m multi
root 20 0 0 18:07 pts/0 00:00:00 bash
root 346 20 0 18:09 pts/0 00:00:00 ps -ef
</code></pre>
|
<python><docker><memory><multiprocessing><python-multiprocessing>
|
2023-03-19 18:12:50
| 1
| 11,527
|
ItayB
|
75,784,018
| 188,159
|
How to find out available system fonts in Pycairo?
|
<p>I'm writing SVG text in Pycairo and want to set the font like so:</p>
<pre><code>context.select_font_face ("Adventure", Cairo.FontSlant.NORMAL, Cairo.FontWeight.BOLD);
</code></pre>
<p>(example from <a href="https://valadoc.org/cairo/Cairo.Context.set_font_size.html" rel="nofollow noreferrer">Valadoc</a>)</p>
<p>but I want to know which font names I can use / are available without having to try and guess. I'm hoping I can generate a list with Python, ideally with Pycairo. I'm on Windows with Python 3.7.9 at the moment. I <a href="https://pycairo.readthedocs.io/en/latest/search.html?q=fonts&check_keywords=yes&area=default#" rel="nofollow noreferrer">can't find anything in the documentation</a>.</p>
<p>There are good solutions at <a href="https://stackoverflow.com/questions/64070050/how-to-get-a-list-of-installed-windows-fonts-using-python">How to get a list of installed windows fonts using python?</a> but rather than getting surprised at some point, I'd like to find out which methods give me all the fonts Pycairo sees, including potential additional folders (like <code>%UserProfile%\.fonts\</code> for Inkscape) and excluding any paths it might not see.</p>
|
<python><windows><fonts><pycairo>
|
2023-03-19 18:10:07
| 0
| 9,813
|
qubodup
|
75,783,837
| 1,438,082
|
write to configuration fmodule
|
<p>I am using the code as menstioned <a href="https://stackoverflow.com/questions/5055042/whats-the-best-practice-using-a-settings-file-in-python">here</a></p>
<pre><code>truck = dict(
color = 'blue',
brand = 'ford',
)
city = 'new york'
cabriolet = dict(
color = 'black',
engine = dict(
cylinders = 8,
placement = 'mid',
),
doors = 2,
)
</code></pre>
<p>and using it like this</p>
<pre><code>import config
print(config.truck['color'])
</code></pre>
<p>How do I write to the config, I tried the code below but it does not work.</p>
<pre><code>config.truck['color'] = "yellow"
</code></pre>
|
<python><python-3.x><dictionary>
|
2023-03-19 17:39:34
| 1
| 2,778
|
user1438082
|
75,783,751
| 7,102,572
|
Reading csv with numpy has extra row of 1's
|
<p>I am using <code>np.genfromtxt</code> to read a csv file, and trying to use the <code>converters</code> argument to preprocess each column.</p>
<p>CSV:</p>
<pre><code>"","Col1","Col2","Col3"
"1","Cell.1",NA,1
"2","Cell.2",NA,NA
"3","Cell.3",1,NA
"4","Cell.4",NA,NA
"5","Cell.5",NA,NA
"6","Cell.6",1,NA
</code></pre>
<p>Code:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
filename = 'b.csv'
h = ("", "Col1", "Col2", "Col3")
def col1_converter(v):
print(f'col1_converter {v = }')
return v
def col2_converter(v):
print(f'col2_converter {v = }')
return v
def col3_converter(v):
print(f'col3_converter {v = }')
return v
a = np.genfromtxt(
filename,
delimiter=',',
names=True,
dtype=[None, np.dtype('U8'), np.dtype('U2'), np.dtype('U2')],
usecols=range(1, len(h)),
converters={1: col1_converter, 2: col2_converter, 3: col3_converter},
deletechars='',
)
print()
print(a)
</code></pre>
<p>When I put print statements in the converters, I see printed an extraneous row of 1's at the beginning which doesn't actually appear in the matrix that is output. Why am I seeing this row of 1's?</p>
<pre><code>col1_converter v = b'1'
col2_converter v = b'1'
col3_converter v = b'1'
col1_converter v = b'"Cell.1"'
col1_converter v = b'"Cell.2"'
col1_converter v = b'"Cell.3"'
col1_converter v = b'"Cell.4"'
col1_converter v = b'"Cell.5"'
col1_converter v = b'"Cell.6"'
col2_converter v = b'NA'
col2_converter v = b'NA'
col2_converter v = b'1'
col2_converter v = b'NA'
col2_converter v = b'NA'
col2_converter v = b'1'
col3_converter v = b'1'
col3_converter v = b'NA'
col3_converter v = b'NA'
col3_converter v = b'NA'
col3_converter v = b'NA'
col3_converter v = b'NA'
[('"Cell.1"', 'NA', '1') ('"Cell.2"', 'NA', 'NA') ('"Cell.3"', '1', 'NA')
('"Cell.4"', 'NA', 'NA') ('"Cell.5"', 'NA', 'NA') ('"Cell.6"', '1', 'NA')]
</code></pre>
|
<python><numpy><csv><converters><genfromtxt>
|
2023-03-19 17:22:35
| 1
| 1,048
|
efthimio
|
75,783,694
| 9,601,748
|
Trying to pivot a large dataframe, but get 'IndexError: index 875914235 is out of bounds for axis 0 with size 875909652'
|
<p>I'm trying to pivot this dataframe ('refined_dataset'):</p>
<p><a href="https://i.sstatic.net/k3I14.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/k3I14.png" alt="dataframe" /></a></p>
<p>Like this:</p>
<pre><code>movieUser_df = refined_dataset.pivot(
index='userID',
columns='primaryTitle',
## Replacing all movies users haven't rated with a rating of 0
values='rating').fillna(0)
</code></pre>
<p>And it returns the error: <code>IndexError: index 875914235 is out of bounds for axis 0 with size 875909652</code></p>
<p>I've done this exact method with almost identical (but much smaller) datasets in the past, I looked up for why I might be having this problem and came across <a href="https://stackoverflow.com/questions/48492451/indexerror-index-1491188345-is-out-of-bounds-for-axis-0-with-size-1491089723">this</a> post from 5 years ago where it's explained that it's an ongoing Pandas issue. Apart from a couple of comments on that post, of which the most recent was two years ago and I don't know if there's any updates since, I can't find others talking about this problem or possible solutions. Does anyone know if this Pandas issue is indeed my problem, and whether it is or isn't, if there's any ways I can try and do it differently?</p>
|
<python><pandas><dataframe><pivot-table>
|
2023-03-19 17:14:14
| 1
| 311
|
Marcus
|
75,783,605
| 402,281
|
Why is Type[T] defined to be covariant in T?
|
<p><a href="https://peps.python.org/pep-0484/#the-type-of-class-objects" rel="nofollow noreferrer">PEP 484</a> declares that <code>typing.Type[T]</code> is covariant, i.e. that for any types <code>A</code> and <code>B</code>, <code>B</code> being a subtype of <code>A</code> implies that <code>Type[B]</code> is a subtype of <code>Type[A]</code>, which is obviously wrong:</p>
<pre><code>>>> from typing import Type
>>>
>>> class A:
... def __init__(self, x: int): pass
...
>>> t: Type[object] = A
>>> t()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() missing 1 required positional argument: 'x'
</code></pre>
<p>What is the rationale behind that decision?</p>
<p>To rule out the error above, every class would need to allow calling <code>__init__()</code> with no arguments, which is not enforced at least by <code>mypy</code>. Is there any documentation of that exception?</p>
|
<python><python-typing><covariance>
|
2023-03-19 16:59:21
| 1
| 10,085
|
Feuermurmel
|
75,783,420
| 1,893,164
|
How can you detect if the mouse buttons are swapped on Windows from Python?
|
<p>Left-handed users may have swapped the mouse buttons on Windows by setting the primary button to the right mouse button instead of the left. What Python code will let me detect this setting?</p>
<p>There are similar questions for C++ and C#:</p>
<p><a href="https://stackoverflow.com/questions/34997186/use-c-sharp-to-read-handedness-setting-from-windows-8/34997444#34997444">Use C# to read handedness setting from Windows 8</a></p>
<p><a href="https://stackoverflow.com/questions/45627956/check-if-mouse-buttons-are-swapped-or-not-in-c">Check if mouse buttons are swapped or not in C++</a></p>
|
<python><winapi><mouse>
|
2023-03-19 16:26:39
| 2
| 13,197
|
Al Sweigart
|
75,783,393
| 585,806
|
A value is trying to be set on a copy of a slice from a DataFrame, but not slice
|
<p>I read several similar question on stackoverflow, but I still don't understand, I'm doing:</p>
<pre><code>dictionnaire = {}
for i, valeur in enumerate(streets):
dictionnaire[valeur] = i+1
for index, elem in enumerate(home_data['Street']):
home_data['Street'][index]=dictionnaire[elem]
</code></pre>
<p>Which seems to work but I have that warning, I tried that:</p>
<pre><code>dictionnaire = {}
for i, valeur in enumerate(streets):
dictionnaire[valeur] = i+1
streets=home_data.Street
for index, elem in enumerate(streets):
home_data['Street'][index]=dictionnaire[elem]
</code></pre>
<p>thinking it's because I'm setting <code>home_data['Street'][index]</code> whie browsing it, but I get this error:</p>
<pre><code>KeyError: 'Pave'
</code></pre>
<p>'Pave' is a value of <code>home_data['Street']</code>, that exists in <code>dictionnaire</code></p>
|
<python><pandas>
|
2023-03-19 16:22:51
| 0
| 2,271
|
Entretoize
|
75,783,251
| 17,487,457
|
dataframe: column statistics after grouping
|
<p>I know this question has been asked, but I can't the answer worked for me, so I ask.
Having this dataframe:</p>
<pre class="lang-py prettyprint-override"><code>data = pd.DataFrame({'id': [9,9,9,2,2,7,7,7,5,8,8,4,4,3,3,3,
1,1,1,1,1,6,6,6,6,6,10,11,11,11,11],
'signal': [1,3,5,7,9,13,17,27,5,1,5,5,11,3,7,11,6,
8,12,14,18,1,3,5,111,115,57,9,21,45,51],
'mode': [0,0,0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,2,
2,2,3,3,3,3,3,3,3,3,3,3]
})
data.head()
id signal mode
0 9 1 0
1 9 3 0
2 9 5 0
3 2 7 0
4 2 9 0
</code></pre>
<p>I want to get the distribution of <code>signal</code> by <code>mode</code>.
I know I need to do the grouping this way:</p>
<pre class="lang-py prettyprint-override"><code>data.groupby('signal')['mode'].value_counts()
</code></pre>
<p>But then I don't know how to proceed, to arrive at:</p>
<pre><code>mode total
0 8
1 5
2 8
3 10
</code></pre>
|
<python><pandas><dataframe>
|
2023-03-19 15:59:38
| 1
| 305
|
Amina Umar
|
75,783,145
| 2,998,976
|
Summing over C contiguous array in numpy returns wrong answer
|
<p>I have the following array:</p>
<pre class="lang-py prettyprint-override"><code>values = np.array(
[[0.00000000000000000000000e+00,
0.00000000000000000000000e+00],
[-4.79999759999999625000000e+14,
-0.00000000000000000000000e+00],
[4.79999759999999625000000e+14,
-0.00000000000000000000000e+00],
[-0.00000000000000000000000e+00,
-4.79999759999999625000000e+14],
[-3.74998499999999072265625e+12,
-3.74998499999999072265625e+12],
[3.74998499999999072265625e+12,
-3.74998499999999072265625e+12],
[-0.00000000000000000000000e+00,
4.79999759999999625000000e+14],
[-3.74998499999999072265625e+12,
3.74998499999999072265625e+12],
[3.74998499999999072265625e+12,
3.74998499999999072265625e+12]]
)
</code></pre>
<p>It contains 0, 4.79999759999999625e+14, 3.74998499999999072265625e+12 and their negative counterparts.</p>
<pre class="lang-py prettyprint-override"><code>print(np.sum(values, axis=0))
</code></pre>
<p>Should result in [0. 0.] (or at least something very very small), but it does not. Its result is <code>[ 0. -0.01855469]</code>.</p>
<p>I figured, this is a floating point precision error and the cause is that numpy is unable to do pair wise summation, so I tried as well:</p>
<pre class="lang-py prettyprint-override"><code>values_T = np.array(
[[0.000000000000000000000000e+00,
-4.799997599999996250000000e+14,
4.799997599999996250000000e+14,
-0.000000000000000000000000e+00,
-3.749984999999990722656250e+12,
3.749984999999990722656250e+12,
-0.000000000000000000000000e+00,
-3.749984999999990722656250e+12,
3.749984999999990722656250e+12],
[0.000000000000000000000000e+00,
-0.000000000000000000000000e+00,
-0.000000000000000000000000e+00,
-4.799997599999996250000000e+14,
-3.749984999999990722656250e+12,
-3.749984999999990722656250e+12,
4.799997599999996250000000e+14,
3.749984999999990722656250e+12,
3.749984999999990722656250e+12]]
)
print(np.sum(values_T, axis=1))
</code></pre>
<p>Which results in <code>[ 0. -0.00927734]</code>. Somehow, the error is halved but it's still not correct.</p>
<p>Both arrays are C contiguous (checked via <code>np.ndarray.flags</code>).</p>
<p>Any help is appreciated!</p>
|
<python><numpy>
|
2023-03-19 15:41:48
| 1
| 373
|
ikhebgeenaccount
|
75,783,081
| 1,788,771
|
Specifying a relation through multiple shared foreign keys
|
<p>Let's say we have 4 models, lets call them <code>Alpha</code>, <code>Beta</code>, <code>Gamma</code>, and <code>Delta</code> and the first two are something like:</p>
<pre class="lang-py prettyprint-override"><code>class Alpha(models.Model):
gamma = models.ForeignKey(Gamma, on_delete=models.RESTRICT)
delta = models.ForeignKey(Delta, on_delete=models.RESTRICT)
text = models.CharField(max_length=1024)
class Meta:
constraints = [
models.UniqueConstraint(fields=['gamma_id', 'delta_id'])
]
class Beta(models.Model):
gamma = models.ForeignKey(Gamma, on_delete=models.RESTRICT)
delta = models.ForeignKey(Delta, on_delete=models.RESTRICT)
value = models.IntegerField()
</code></pre>
<p>As you can see the two foreign keys can be used to associate any number of rows from Beta with one row from Alpha. There is essentially a one to many relationship between Beta and Alpha.</p>
<p>For various reasons it is not feasible to replace the two foreign keys in Beta with a foreign key to Alpha.</p>
<p>Is there a way to define a relationship on Alpha that returns all the rows from Beta that have the same <code>gamma_id</code> and <code>delta_id</code></p>
|
<python><django><has-many-through>
|
2023-03-19 15:32:07
| 1
| 4,107
|
kaan_atakan
|
75,783,029
| 1,314,732
|
PyTorch with Transformer - finetune GPT2 throws index out of range Error
|
<p>in my Jupiter i have the following code. I can not figure out why this throws a <code>IndexError: index out of range in self</code> error.</p>
<p>here ist the code:</p>
<pre><code>!pip install torch
!pip install torchvision
!pip install transformers
</code></pre>
<pre><code>import torch
from torch.utils.data import Dataset
class MakeDataset(Dataset):
def __init__(self, tokenized_texts, block_size):
self.examples = []
for tokens in tokenized_texts:
# truncate the tokens if they are longer than block_size
if len(tokens) > block_size:
tokens = tokens[:block_size]
# add padding tokens if the tokens are shorter than block_size
while len(tokens) < block_size:
tokens.append(tokenizer.pad_token_id)
self.examples.append(torch.tensor(tokens, dtype=torch.long))
def __len__(self):
return len(self.examples)
def __getitem__(self, item):
return self.examples[item]
</code></pre>
<pre><code>from transformers import DataCollatorForLanguageModeling, Trainer, TrainingArguments, AutoTokenizer, \
AutoModelWithLMHead, GPT2Tokenizer
# Load the tokenizer and model
tokenizer = GPT2Tokenizer.from_pretrained('gpt2', padding_side='right')
model = AutoModelWithLMHead.from_pretrained('gpt2')
PAD_TOKEN = '<PAD>'
tokenizer.add_special_tokens({'pad_token': PAD_TOKEN})
# Load text corpus
with open("texts.txt", encoding="utf-8") as f:
texts = f.read().splitlines()
print(len(texts) , " lines of text.")
# Tokenize the texts
tokenized_texts = []
for text in texts:
tokens = tokenizer.encode(text, padding='max_length', truncation='only_first')
if len(tokens) > 0:
tokenized_texts.append(tokens)
# gemerate a dataset
dataset = MakeDataset(tokenized_texts, block_size=1024)
print("Dataset length: ", len(dataset))
# Create a DataCollatorForLanguageModeling object
data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)
# Define the training arguments
training_args = TrainingArguments(
output_dir='./results', # output directory
num_train_epochs=5, # total number of training epochs
per_device_train_batch_size=16, # batch size per device during training
save_steps=1000, # number of steps between saving checkpoints
save_total_limit=2, # limit the total amount of checkpoints saved
prediction_loss_only=True, # only calculate loss on prediction tokens
learning_rate=1e-5, # learning rate
warmup_steps=500, # number of warmup steps for learning rate scheduler
fp16=False # enable mixed precision training with apex
)
# Create a Trainer object
trainer = Trainer(
model=model,
args=training_args,
data_collator=data_collator,
train_dataset=dataset
)
# Train the model
trainer.train()
# Save the trained model
trainer.save_model('./fine-tuned-gpt2')
</code></pre>
<p>The text file at the moment looks very simple:</p>
<pre><code>Hello, my name is Paul.
My cat can sing.
</code></pre>
<p>The full error is:</p>
<pre><code>IndexError Traceback (most recent call last)
Cell In[140], line 54
46 trainer = Trainer(
47 model=model,
48 args=training_args,
49 data_collator=data_collator,
50 train_dataset=dataset
51 )
53 # Train the model
---> 54 trainer.train()
56 # Save the trained model
57 trainer.save_model('./fine-tuned-gpt2')
File /opt/homebrew/lib/python3.11/site-packages/transformers/trainer.py:1633, in Trainer.train(self, resume_from_checkpoint, trial, ignore_keys_for_eval, **kwargs)
1628 self.model_wrapped = self.model
1630 inner_training_loop = find_executable_batch_size(
1631 self._inner_training_loop, self._train_batch_size, args.auto_find_batch_size
1632 )
-> 1633 return inner_training_loop(
1634 args=args,
1635 resume_from_checkpoint=resume_from_checkpoint,
1636 trial=trial,
1637 ignore_keys_for_eval=ignore_keys_for_eval,
1638 )
File /opt/homebrew/lib/python3.11/site-packages/transformers/trainer.py:1902, in Trainer._inner_training_loop(self, batch_size, args, resume_from_checkpoint, trial, ignore_keys_for_eval)
1900 tr_loss_step = self.training_step(model, inputs)
1901 else:
-> 1902 tr_loss_step = self.training_step(model, inputs)
1904 if (
1905 args.logging_nan_inf_filter
1906 and not is_torch_tpu_available()
1907 and (torch.isnan(tr_loss_step) or torch.isinf(tr_loss_step))
1908 ):
1909 # if loss is nan or inf simply add the average of previous logged losses
1910 tr_loss += tr_loss / (1 + self.state.global_step - self._globalstep_last_logged)
File /opt/homebrew/lib/python3.11/site-packages/transformers/trainer.py:2645, in Trainer.training_step(self, model, inputs)
2642 return loss_mb.reduce_mean().detach().to(self.args.device)
2644 with self.compute_loss_context_manager():
-> 2645 loss = self.compute_loss(model, inputs)
2647 if self.args.n_gpu > 1:
2648 loss = loss.mean() # mean() to average on multi-gpu parallel training
File /opt/homebrew/lib/python3.11/site-packages/transformers/trainer.py:2677, in Trainer.compute_loss(self, model, inputs, return_outputs)
2675 else:
2676 labels = None
-> 2677 outputs = model(**inputs)
2678 # Save past state if it exists
2679 # TODO: this needs to be fixed and made cleaner later.
2680 if self.args.past_index >= 0:
File /opt/homebrew/lib/python3.11/site-packages/torch/nn/modules/module.py:1501, in Module._call_impl(self, *args, **kwargs)
1496 # If we don't have any hooks, we want to skip the rest of the logic in
1497 # this function, and just call forward.
1498 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
1499 or _global_backward_pre_hooks or _global_backward_hooks
1500 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1501 return forward_call(*args, **kwargs)
1502 # Do not call functions when jit is used
1503 full_backward_hooks, non_full_backward_hooks = [], []
File /opt/homebrew/lib/python3.11/site-packages/transformers/models/gpt2/modeling_gpt2.py:1075, in GPT2LMHeadModel.forward(self, input_ids, past_key_values, attention_mask, token_type_ids, position_ids, head_mask, inputs_embeds, encoder_hidden_states, encoder_attention_mask, labels, use_cache, output_attentions, output_hidden_states, return_dict)
1067 r"""
1068 labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1069 Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1070 `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1071 are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1072 """
1073 return_dict = return_dict if return_dict is not None else self.config.use_return_dict
-> 1075 transformer_outputs = self.transformer(
1076 input_ids,
1077 past_key_values=past_key_values,
1078 attention_mask=attention_mask,
1079 token_type_ids=token_type_ids,
1080 position_ids=position_ids,
1081 head_mask=head_mask,
1082 inputs_embeds=inputs_embeds,
1083 encoder_hidden_states=encoder_hidden_states,
1084 encoder_attention_mask=encoder_attention_mask,
1085 use_cache=use_cache,
1086 output_attentions=output_attentions,
1087 output_hidden_states=output_hidden_states,
1088 return_dict=return_dict,
1089 )
1090 hidden_states = transformer_outputs[0]
1092 # Set device for model parallelism
File /opt/homebrew/lib/python3.11/site-packages/torch/nn/modules/module.py:1501, in Module._call_impl(self, *args, **kwargs)
1496 # If we don't have any hooks, we want to skip the rest of the logic in
1497 # this function, and just call forward.
1498 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
1499 or _global_backward_pre_hooks or _global_backward_hooks
1500 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1501 return forward_call(*args, **kwargs)
1502 # Do not call functions when jit is used
1503 full_backward_hooks, non_full_backward_hooks = [], []
File /opt/homebrew/lib/python3.11/site-packages/transformers/models/gpt2/modeling_gpt2.py:842, in GPT2Model.forward(self, input_ids, past_key_values, attention_mask, token_type_ids, position_ids, head_mask, inputs_embeds, encoder_hidden_states, encoder_attention_mask, use_cache, output_attentions, output_hidden_states, return_dict)
839 head_mask = self.get_head_mask(head_mask, self.config.n_layer)
841 if inputs_embeds is None:
--> 842 inputs_embeds = self.wte(input_ids)
843 position_embeds = self.wpe(position_ids)
844 hidden_states = inputs_embeds + position_embeds
File /opt/homebrew/lib/python3.11/site-packages/torch/nn/modules/module.py:1501, in Module._call_impl(self, *args, **kwargs)
1496 # If we don't have any hooks, we want to skip the rest of the logic in
1497 # this function, and just call forward.
1498 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
1499 or _global_backward_pre_hooks or _global_backward_hooks
1500 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1501 return forward_call(*args, **kwargs)
1502 # Do not call functions when jit is used
1503 full_backward_hooks, non_full_backward_hooks = [], []
File /opt/homebrew/lib/python3.11/site-packages/torch/nn/modules/sparse.py:162, in Embedding.forward(self, input)
161 def forward(self, input: Tensor) -> Tensor:
--> 162 return F.embedding(
163 input, self.weight, self.padding_idx, self.max_norm,
164 self.norm_type, self.scale_grad_by_freq, self.sparse)
File /opt/homebrew/lib/python3.11/site-packages/torch/nn/functional.py:2210, in embedding(input, weight, padding_idx, max_norm, norm_type, scale_grad_by_freq, sparse)
2204 # Note [embedding_renorm set_grad_enabled]
2205 # XXX: equivalent to
2206 # with torch.no_grad():
2207 # torch.embedding_renorm_
2208 # remove once script supports set_grad_enabled
2209 _no_grad_embedding_renorm_(weight, input, max_norm, norm_type)
-> 2210 return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse)
IndexError: index out of range in self
</code></pre>
<p>Can someone tell me what I have done wrong with the training setup?</p>
<p>++ UPDATE ++</p>
<p>I change the <code>MakeDataset</code> to <code>TextDataset</code> to get a pt tensor back:</p>
<pre><code>class TextDataset(torch.utils.data.Dataset):
def __init__(self, encodings):
self.encodings = encodings
def __getitem__(self, idx):
return {key: tensor[idx] for key, tensor in self.encodings.items()}
def __len__(self):
return len(self.encodings.input_ids)
</code></pre>
<p>the output of <code>print(dataset[0])</code> is:</p>
<pre><code>{'input_ids': tensor([15496, 11, 616, 1438, 318, 3362, 13, 50257, 50257, 50257,
50257, 50257, 50257, 50257, 50257, 50257, 50257, 50257, 50257, 50257,
50257, 50257]), 'attention_mask': tensor([1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])}
</code></pre>
<p>and with</p>
<pre><code>tokenized_texts = tokenizer(texts, padding='max_length', truncation=True, return_tensors="pt")
</code></pre>
<p>to pad them to the models length:</p>
<pre><code>6 lines of text.
Dataset length: 6
{'input_ids': tensor([[15496, 11, 616, ..., 50257, 50257, 50257],
[ 3666, 3797, 460, ..., 50257, 50257, 50257],
[32423, 1408, 46097, ..., 50257, 50257, 50257],
[10020, 1044, 6877, ..., 50257, 50257, 50257],
[31319, 288, 292, ..., 50257, 50257, 50257],
[ 7447, 24408, 8834, ..., 50257, 50257, 50257]]), 'attention_mask': tensor([[1, 1, 1, ..., 0, 0, 0],
[1, 1, 1, ..., 0, 0, 0],
[1, 1, 1, ..., 0, 0, 0],
[1, 1, 1, ..., 0, 0, 0],
[1, 1, 1, ..., 0, 0, 0],
[1, 1, 1, ..., 0, 0, 0]])}
</code></pre>
<p>But I still get the same error.
I also deleted all caches.</p>
|
<python><pytorch><huggingface><gpt-2>
|
2023-03-19 15:24:24
| 0
| 1,917
|
Peter Shaw
|
75,783,003
| 4,404,805
|
Regex: Match decimal numerals with no digits before decimal point
|
<p>I am trying to match decimal numerals with no digits before the decimal point in a string using regex. For example, I have the strings:</p>
<pre><code>The dimensions of the object-1 is: 1.4 meters wide, .5 meters long, 5.6 meters high
The dimensions of the object-2 is: .8 meters wide, .11 meters long, 0.6 meters high
</code></pre>
<p>I want to capture only the decimal numbers without integer digits and prefix leading zeros to them. So my final desired output will be:</p>
<pre><code>The dimensions of the object-1 is: 1.4 meters wide, 0.5 meters long, 5.6 meters high
The dimensions of the object-2 is: 0.8 meters wide, 0.11 meters long, 0.6 meters high
</code></pre>
<p>This is what I have tried so far:</p>
<pre><code>(\d+)?\.(\d+)
</code></pre>
<p>This expression is capturing all the decimal numbers such as: <code>1.4, .5, 5.6, .8, .11, 0.6</code>.</p>
<p>But I need to capture only decimal numbers without integer digits: <code>.5, .8, .11</code>.</p>
|
<python><regex><expression><leading-zero>
|
2023-03-19 15:18:56
| 2
| 1,207
|
Animeartist
|
75,782,915
| 12,688,015
|
cannot build package for all python3 versions
|
<p>This is my setup.py file for my C extension module for Python, I want to build my package for all py3 versions but it still builds for cp38, I don't understand why and tried every option I saw on the internet, what would be the reason of this</p>
<pre><code>import os
import glob
import pathlib
import setuptools
from setuptools.command.build_ext import build_ext
module = setuptools.Extension(
name="structura",
define_macros=[("MAJOR_VERSION", "0"), ("MINOR_VERSION", "3")],
sources=glob.glob("./src/*.c"),
include_dirs=["./src", "./include"],
)
with pathlib.Path(__file__).parent.joinpath("README.rst").open() as f:
long_description = f.read()
def main():
setuptools.setup(name="structura",
version="0.3.1",
description="C extension module for common data structures",
author="alperen serkan aksoz",
author_email="a.serkanaksoz@gmail.com",
long_description=long_description,
url="https://github.com/sekomer/structura",
license="MIT",
ext_modules=[module],
python_requires=">=3",
cmdclass={'build_ext': build_ext},
zip_safe=False,
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: POSIX :: Linux",
"Programming Language :: C",
"Programming Language :: Python :: 3.x",
"Topic :: Software Development :: Libraries :: Python Modules",
],
options={'bdist_wheel': {'universal': True}},)
if __name__ == "__main__":
main()
</code></pre>
<p>I'm building with following commands</p>
<pre><code>sudo python setup.py sdist
sudo python setup.py bdist_wheel
</code></pre>
<p>I also tried the following which uses venv to build</p>
<pre><code>sudo python3 -m build --sdist
sudo python3 -m build --wheel
</code></pre>
<p>still not working as I desired</p>
|
<python><cpython>
|
2023-03-19 15:04:50
| 0
| 742
|
sekomer
|
75,782,877
| 5,984,358
|
How does scipy minimization handle cases where hessian is not positive definite
|
<p>I am using <code>from scipy.optimize import minimize</code> to minimize a function subject to two constraints. I have been using the <code>trust-constr</code> method, which takes the value, gradient and the Hessian of the function.</p>
<p>However, in my case, the Hessian may sometimes develop negative eigenvalues (i.e. no longer positive definite). But the algorithm still needs to go downhill and not converge to a saddle point (which would be the case for Newton or quasi-Newton methods). Does the <code>trust-constr</code> optimisation method guarantee that?</p>
|
<python><scipy><scipy-optimize><hessian-matrix>
|
2023-03-19 14:56:56
| 0
| 327
|
S R Maiti
|
75,782,775
| 12,285,101
|
quit while loop inside for loop
|
<p>I have the following logic in my code:</p>
<pre><code>count=0
for x in lst:
print('hello!')
while True:
rep=input('save this?y/n?')
print(rep)
if rep=="y":
print('wow amazing')
count=count+1
break
elif rep=="n":
print('moving to next target')
count=count+1
break
else:
print('please enter either y/n')
print('DONE!')
</code></pre>
<p>I want to add a condition that <code>if rep=="quit"</code>, the code will stop running (also stop the for loop not only the while loop). currently, break just stop the current while loop but not the whole for loop. how can I quit the whole for loop base don value inserted in the while loop?</p>
|
<python><for-loop><while-loop><exit>
|
2023-03-19 14:43:28
| 2
| 1,592
|
Reut
|
75,782,765
| 11,015,558
|
Pyarrow slice pushdown for Azure data lake
|
<p>I want to access Parquet files on an Azure data lake, and only retrieve some rows.</p>
<p>Here is a reproducible example, using a public dataset:</p>
<pre><code>import pyarrow.dataset as ds
from adlfs import AzureBlobFileSystem
abfs_public = AzureBlobFileSystem(
account_name="azureopendatastorage")
dataset_public = ds.dataset('az://nyctlc/yellow/puYear=2010/puMonth=1/part-00000-tid-8898858832658823408-a1de80bd-eed3-4d11-b9d4-fa74bfbd47bc-426339-18.c000.snappy.parquet', filesystem=abfs_public)
</code></pre>
<p>The processing time is the same for collecting 5 rows compared to collecting the full dataset. Is there a way to achieve slice pushdown using Pyarrow?</p>
<p>Here are my tests:</p>
<pre><code>dataset_public.to_table()
# 5min 30s
dataset_public.head(5)
# 5min 11s
dataset_public.scanner().head(5)
# 5min 43s
</code></pre>
<p>I'm not sure if there is a difference between <code>.head()</code> and <code>.scanner().head()</code></p>
<p>Related pages:</p>
<ul>
<li>Apache Arrow website: <a href="https://arrow.apache.org/docs/python/parquet.html#reading-from-cloud-storage" rel="nofollow noreferrer">https://arrow.apache.org/docs/python/parquet.html#reading-from-cloud-storage</a></li>
<li>ADLFS Github page: <a href="https://github.com/fsspec/adlfs" rel="nofollow noreferrer">https://github.com/fsspec/adlfs</a></li>
</ul>
|
<python><azure><azure-data-lake><pyarrow><apache-arrow>
|
2023-03-19 14:42:10
| 2
| 1,994
|
Luca
|
75,782,694
| 3,848
|
Building package with 'build' does not exclude exclude-files (which setup.py does)
|
<p>We're getting deprecation warnings when building with <code>python3 setup.py sdist</code> and after reading <a href="https://blog.ganssle.io/articles/2021/10/setup-py-deprecated.html" rel="nofollow noreferrer">Why you shouldn't invoke setup.py directly?</a> I see that the recomended alternative is to use <a href="https://pypa-build.readthedocs.io/en/stable/" rel="nofollow noreferrer"><code>build</code></a>.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>setup.py command</th>
<th>New command</th>
</tr>
</thead>
<tbody>
<tr>
<td>setup.py sdist</td>
<td>python -m build (with build)</td>
</tr>
<tr>
<td>setup.py bdist_wheel</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>When comparing the outputs I see that the deprecated <code>setup.py</code> excludes the <strong>tests</strong> directory (as specified with <code>packages=find_packages(exclude=['tests']),</code> while <code>python3 -m build</code> does not exclude this directory.</p>
<p>My understanding was that <code>build</code> still uses <code>setup.py</code>, albeit not directly, am I missing something? What is the correct way to avoid packaging the <strong>tests</strong> directory?</p>
<p><strong>Environment information</strong></p>
<ul>
<li><strong>OS</strong>: Windows</li>
<li><code>python</code>: 3.10.10</li>
<li><code>pip</code>: 23.0.1</li>
<li><code>setuptools</code>: 65.5.0</li>
<li><code>build</code>: 0.10.0</li>
<li>No <code>pyproject.toml</code> file in project</li>
</ul>
<p>A minimal project behaves the same:</p>
<p>In my test sample project there is a <code>lib</code> directory with an empty <code>__init__.py</code> and <code>hello.py</code> with <code>print("hello")</code>, a <code>tests</code> directory with an empty <code>test_hello.py</code> file and the following <code>setup.py</code>:</p>
<pre><code>from setuptools import find_packages, setup
setup(
name="hello",
version="0.1",
author="myself",
description="test package",
packages=find_packages(exclude=["tests"]),
)
</code></pre>
<p><em>Edit:</em> Opened issue on github <a href="https://github.com/pypa/setuptools/issues/3870" rel="nofollow noreferrer">https://github.com/pypa/setuptools/issues/3870</a></p>
|
<python><build><setuptools><setup.py><python-packaging>
|
2023-03-19 14:30:04
| 1
| 115,461
|
Motti
|
75,782,664
| 9,418,142
|
Passing a list of senders to the sender parameter of @receiver decorator
|
<p>So at the moment, I'm working on my Django project and I have a signal receiver function that looks like this:</p>
<pre><code>@receiver(pre_save, sender=Task, dispatch_uid='core.models.task_handler_pre_1')
@receiver(pre_save, sender=TaskHistory, dispatch_uid='core.models.task_handler_pre_2')
@receiver(pre_save, sender=TaskUser, dispatch_uid='core.models.task_handler_pre_3')
def task_handler_pre(sender, instance, **kwargs):
# do some stuff
</code></pre>
<p>In an attempt to make the code look cleaner, I was wondering whether would it be possible to do something like this:</p>
<pre><code>@receiver(pre_save, sender=[Task, TaskHistory, TaskUser], dispatch_uid='core.models.task_handler_pre')
def task_handler_pre(sender, instance, **kwargs):
# do some stuff
</code></pre>
<p>i.e. Does the <code>sender</code> parameter accepts a list of senders as a valid argument ? If not, then does the value of the <code>dispatch_uid</code> parameter within the <code>@receiver</code> decorator, have to be different for each individual sender, or can it be the same i.e.</p>
<p>As mentioned previously, my receiver function looks like this at the moment:</p>
<pre><code>@receiver(pre_save, sender=Task, dispatch_uid='core.models.task_handler_pre_1')
@receiver(pre_save, sender=TaskHistory, dispatch_uid='core.models.task_handler_pre_2')
@receiver(pre_save, sender=TaskUser, dispatch_uid='core.models.task_handler_pre_3')
def task_handler_pre(sender, instance, **kwargs):
# do some stuff
</code></pre>
<p>What difference would it make if I make the following change:</p>
<pre><code>@receiver(pre_save, sender=Task, dispatch_uid='core.models.task_handler_pre')
@receiver(pre_save, sender=TaskHistory, dispatch_uid='core.models.task_handler_pre')
@receiver(pre_save, sender=TaskUser, dispatch_uid='core.models.task_handler_pre')
def task_handler_pre(sender, instance, **kwargs):
# do some stuff
</code></pre>
<p>i.e. make the value of the <code>dispatch_uid</code> parameter the same ( <code>core.models.task_handler_pre</code> ) for each individual sender. Thanks!</p>
|
<python><django><event-handling>
|
2023-03-19 14:25:38
| 1
| 716
|
AnonSar
|
75,782,594
| 9,414,470
|
RSA Implementation in Python
|
<p>I was trying to implement RSA cipher, and this is my work so far:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
def solve_diophantine_eqn(a: int, b: int, d: int):
'''
Solving ax + by = d, where a, b and d are given. \\
Solving for x and y, where d is multiple of gcd(a, b)
'''
d_sol_gcd, d_sol_0 = apply_extended_euclidean(np.array((a, 1, 0)), np.array((b, 0, 1)))
if d == 0:
return d_sol_0[1], d_sol_0[2]
return d_sol_gcd[1:] * d // d_sol_gcd[0]
def apply_extended_euclidean(a: np.ndarray, b: np.ndarray, d = 1):
'''
Solving ax + by = d, where a, b and d are given \\
Solving for x and y, where d is multiple of gcd(a, b) \\
Default case stopping at d = 0, because 0 is multiple of every integer
'''
if b[0] < d:
return a, b
q = a[0] // b[0]
return apply_extended_euclidean(b, a - q*b, d)
# print(apply_extended_euclidean(np.array((12, 1, 0)), np.array((8, 0, 1))))
# x, y = solve_diophysis_eqn(12, 8, 0)
# print(x, y)
message = 7
p = 11 # Select any large prime p
q = 7 # Select any large prime q
n = p * q # Let large natural number n be p*q
t_n = (p-1)*(q-1) # theta(n) is euler totient of n
e = t_n - 1 # e is coprime with theta(n)
d, _ = solve_diophantine_eqn(e, t_n, 1) # Solve equation e*d + theta(n) * y = 1
d = d % t_n # If d < 0, make d positive
print(d)
public_key = (e, n)
private_key = (d, n)
print(public_key)
print(private_key)
plaintext = message
print(plaintext)
ciphertext = plaintext ** d % n
print(ciphertext)
recievedtext = ciphertext ** e % n
print(recievedtext)
</code></pre>
<p>The output is:</p>
<pre><code>59
(59, 77)
(59, 77)
7
43
63
</code></pre>
<p>The strange thing is that when using a calculator, the output of <em><code>C = M^d mod n</code></em> is 63.
<a href="https://i.sstatic.net/35gBa.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/35gBa.png" alt="Math result" /></a>
Even when I step through the program, when all the values are correct, it STILL gives the incorrect answer.</p>
<p>I don't understand it. Can someone clarify how this is the case?</p>
<p>Thanks in advance!</p>
|
<python><numpy>
|
2023-03-19 14:14:52
| 2
| 896
|
Jaideep Shekhar
|
75,782,584
| 11,092,636
|
multiprocessing with SLURM, increasing number of cpus-per-ask works but not increasing number of tasks
|
<p>Whether i specify <code>--ntasks=3</code> and <code>--cpus-per-task=40</code> or <code>--ntasks=1</code> and <code>--cpus-per-task=40</code> (SLURM), the code takes the exact same time (99 seconds) to run. What am I missing?</p>
<p>I do witness a speed up when going from <code>--cpus-per-task=20</code> to <code>--cpus-per-task=40</code> (194 seconds vs 99 seconds which makes sense (two fold decrease in time when putting twice as many CPUs)!).</p>
<p>I do have 40 CPUs per node available.</p>
<p>Here is my MRE:</p>
<pre class="lang-py prettyprint-override"><code>import multiprocessing as mp
import openpyxl
import os
import time
from multiprocessing import Lock
def write_to_excel(workbook, sheet_name, row, col, data, mylock):
# just some stuff to make the calculation last a long time
for k in range(15_000):
for j in range(15_000):
a = k + j
if a % 2 == 0:
a = a + 1
else:
a = a - 1
if a is None:
print(a)
with mylock:
# Open the shared workbook in read-write mode
wb = openpyxl.load_workbook(workbook)
# Get the sheet
sheet = wb[sheet_name]
# Write the data to the specified cell
sheet.cell(row=row, column=col, value=data)
# Save the changes to the workbook
wb.save(workbook)
if __name__ == "__main__":
start_time = time.time()
# Create a new Excel workbook
wb = openpyxl.Workbook()
wb.save("shared_workbook.xlsx")
mylock = Lock()
# Get the number of tasks and CPUs per task from environment variables
num_tasks = int(os.getenv("SLURM_NTASKS", 1))
cpus_per_task = int(os.getenv("SLURM_CPUS_PER_TASK", 1))
print(f"num_tasks: {num_tasks}") # output is coherent with my slurm script
print(f"cpus_per_task: {cpus_per_task}") # output is coherent with my slurm script
# Calculate the total number of processes
num_processes = num_tasks * cpus_per_task
print(f"num_processes: {num_processes}") # output is coherent with my slurm script
# Number of parallel processes to create
num_processes_to_have = 102
# Start the processes
processes = []
for i in range(num_processes_to_have):
process = mp.Process(
target=write_to_excel,
args=(
"shared_workbook.xlsx",
"Sheet",
i + 1,
1,
f"Data from process {i + 1}",
mylock,
),
)
processes.append(process)
process.start()
# Wait for all processes to finish
for process in processes:
process.join()
print("Writing to shared workbook complete.", time.time() - start_time)
</code></pre>
<p>My slurm script looks like this:</p>
<pre><code>#SBATCH --job-name=#####
#SBATCH --output=#####
#SBATCH --time=1:00:00
#SBATCH --mem=8G
#SBATCH --partition=#####
#SBATCH --mail-user=#####
#SBATCH --mail-type=#####
#SBATCH --export=NONE
#SBATCH --ntasks=1
#SBATCH --cpus-per-task=20
</code></pre>
|
<python><python-multiprocessing><slurm>
|
2023-03-19 14:12:27
| 1
| 720
|
FluidMechanics Potential Flows
|
75,782,431
| 20,959,773
|
How to get the coordinates of Selenium Mouse cursor Python without involving any elements
|
<p>I need to find a way to get location coordinates of current Selenium ActionChains invisible cursor.</p>
<p>I can find it after I move to an element, and calculate it from size of element and location of element, but this requires to move first to it and is not very accurate.</p>
<p>I can find it injecting javascript to make a div on the cursor to make it visible, and thereby even getting the location of that element, but this is not ideal because it requires that I modify the webpage's html.</p>
<p>How can I achieve this?</p>
|
<javascript><python><html><selenium-webdriver>
|
2023-03-19 13:48:41
| 1
| 347
|
RifloSnake
|
75,782,276
| 5,082,187
|
Single quotes around types in Python variable declarations
|
<p>Python accepts this statement:</p>
<pre><code>stop:bool = False
</code></pre>
<p>I have been told this is better:</p>
<pre><code>stop:'bool' = False
</code></pre>
<p>Does it matter? Is there a kind of beautifier that will make my code use a single consistent style?</p>
|
<python>
|
2023-03-19 13:20:41
| 1
| 428
|
TradingDerivatives.eu
|
75,781,877
| 19,130,803
|
Type-hint a custom class enum
|
<p>I have a enum class, which is class variable inside person class. I am getting typehint error for <code>types</code> class variable.</p>
<p>I tried as below to typehint <code>types</code> class variable.</p>
<ul>
<li>XyzTypes</li>
<li>"XyzTypes"</li>
<li>Type[XyzTypes]</li>
<li>TypeVar["T"]</li>
</ul>
<p>None of them work. Getting error as <code>error: Incompatible types in assignment...</code></p>
<pre><code>class XyzTypes(StrEnum):
MNO: str = "mno"
PQR: str = "pqr"
@classmethod
def get_default(cls) -> str:
return cls.MNO
</code></pre>
<pre><code>class Person:
types: XyzTypes = XyzTypes
</code></pre>
<p>Accessing as <code>Person.types.get_default()</code></p>
<p>Please help.</p>
<p><strong>Edit: 1</strong>
I am using python 3.11</p>
<p><strong>Edit: 2</strong></p>
<p>Further I modified the code and made that variable private as below</p>
<pre><code>class Person:
_types: type[XyzTypes] = XyzTypes # Working now
@classmethod
def get_type_enum(cls) -> ???:
return cls._types
</code></pre>
<p>I tried below</p>
<ul>
<li>type[XyzTypes]</li>
<li>"XyzTypes"</li>
</ul>
<p>Getting error as <code>error: Incompatible return value type </code></p>
|
<python>
|
2023-03-19 12:09:10
| 1
| 962
|
winter
|
75,781,875
| 9,978,223
|
ARRAY of UUID to raw SQL
|
<p>I'm using</p>
<pre><code>Python == 3.10
flask-sqlalchemy == 2.5.1
sqlalchemy == 1.4.46
</code></pre>
<p>I have a stored procedure <code>delete_foo_by_uuids</code> to delete data from <code>foo</code> table using PostgreSQL. The stored procedure gets <code>UUID[]</code> as input parameters.
It works great inside SQL request:</p>
<pre><code>CALL delete_foo_by_uuids(ARRAY['b0f5a699-d080-4f9a-9e68-5d7b397dc4f5', '1026b21a-7ada-4a51-836e-c46579e1116c'])
[] completed in 72ms
</code></pre>
<p>But I want to run it in the flask python app.
I have tried calling it this way:</p>
<pre><code>uuids: list[UUID] = [uuid.uuid4(), uuid.uuid4()]
prepared_sql = ",".join([f"\'{_}\'" for _ in uuids])
with current_app.app_context():
db.session.execute(f"CALL delete_foo_by_uuids(ARRAY[{prepared_sql}]::uuid[]);")
</code></pre>
<p>but this way is too ugly for me.</p>
<p>How to make a SQL sentence easier using tools of sqlalchemy?
I suppose something like</p>
<pre><code>f"CALL delete_foo_by_uuids({SomePgArrayClass(uuids)});"
</code></pre>
|
<python><postgresql><sqlalchemy><flask-sqlalchemy>
|
2023-03-19 12:08:58
| 1
| 668
|
Dmitrii Sidenko
|
75,781,743
| 3,966,691
|
Python subprocess.Popen hang to prcoess stream of linux 'read -p' command
|
<p>I want to interact with Linux <code>read -p</code> prompt command through python.</p>
<p>I wrote following program using python <code>subprocess.Popen</code> but this program stuck of getting <code>read -p</code> prompt stream.</p>
<pre><code>import subprocess
import threading
import re
class ExeCmd:
def __init__(self, cmd, interactive_cmds=dict()):
self.cmd = cmd
self.err = bytearray()
self.out = bytearray()
self.ret: int
proc = subprocess.Popen(
self.cmd,
shell=False,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
def process_stream(pipe, stream):
while True:
line = pipe.readline()
if line == b'' and proc.poll() is not None:
break
stream.extend(line)
line = line.decode()
for key, value in interactive_cmds.items():
if re.search(key, line):
if str(value).startswith("Signals."):
proc.send_signal(value)
else:
proc.stdin.write(str(value + '\n').encode())
proc.stdin.flush()
break
out_thread = threading.Thread(target=process_stream, args=(proc.stdout, self.out))
err_thread = threading.Thread(target=process_stream, args=(proc.stderr, self.err))
out_thread.start()
err_thread.start()
out_thread.join()
err_thread.join()
# wait for termination
proc.communicate()
self.ret = proc.returncode
if __name__ == '__main__':
ExeCmd('s.sh', {r'Enter input:': 'y'})
</code></pre>
<p>Following is <code>s.sh</code> content</p>
<pre><code>cat s.sh
#! /bin/bash
echo "Sample taking input from users"
read -p "Enter input:"
</code></pre>
<p>So how python will know when <code>s.sh</code> prompt for input ?</p>
<p>Note: There is no stream even If I use <code>pipe.read1()</code> (read one byte at a time)</p>
|
<python><python-3.x><linux><subprocess>
|
2023-03-19 11:46:06
| 0
| 563
|
Equation Solver
|
75,781,599
| 20,266,647
|
Missing webapi parameter or V3IO_API environment variable
|
<p>I got the exception:</p>
<pre><code> File "C:\Python\ingestKVdatetime\venv\lib\site-packages\mlrun\datastore\targets.py", line 1155, in get_table_object
V3ioDriver(webapi=endpoint),
File "C:\Python\ingestKVdatetime\venv\lib\site-packages\storey\drivers.py", line 100, in __init__
NeedsV3ioAccess.__init__(self, webapi, access_key)
File "C:\Python\ingestKVdatetime\venv\lib\site-packages\storey\drivers.py", line 72, in __init__
raise ValueError("Missing webapi parameter or V3IO_API environment variable")
ValueError: Missing webapi parameter or V3IO_API environment variable
</code></pre>
<p>When I ingested data to key-value target, see source code:</p>
<pre><code>import mlrun
import mlrun.feature_store as fstore
...
mlrun.set_env_from_file("mlrun-nonprod.env")
project = mlrun.get_or_create_project(project_name, context='./', user_project=False)
feature_set = fstore.FeatureSet(feature_name, entities=[fstore.Entity("fn0"), fstore.Entity("fn1")],engine="storey")
feature_set.set_targets(targets=[mlrun.datastore.NoSqlTarget()], with_defaults=False)
feature_set.save()
fstore.ingest(feature_set, dataFrm, overwrite=True)
</code></pre>
<p>Why do I need to setup V3IO_API when I already set MLRUN_DB, V3IO_USERNAME, V3IO_ACCESS_KEY? Where can I find settings for V3IO_API?</p>
|
<python><data-ingestion><mlops><feature-store><mlrun>
|
2023-03-19 11:18:11
| 1
| 1,390
|
JIST
|
75,781,511
| 6,919,063
|
How does discord's api get live data
|
<p>I am wondering how apis like discord.py get live data. Other than putting a request.get in a while True loop I am wondering how live data can be retrieved like a push server. Is there some magic in using a discord bot that allows us to receive push information or can it be done via requests or some custom websocket?</p>
|
<python><websocket><discord>
|
2023-03-19 10:59:38
| 1
| 724
|
Jacob B
|
75,781,507
| 17,795,398
|
sqlite: error when using another sqlite command inside a custom function (sqlite3.Connection.create_function)
|
<p>I'm learning to create custom <code>sqlite3</code> functions in Python. This is my code:</p>
<pre><code>import sqlite3
conn = sqlite3.connect("data.db")
c = conn.cursor()
query = "CREATE TABLE IF NOT EXISTS names (ID INTEGER UNIQUE PRIMARY KEY NOT NULL, name TEXT)"
c.execute(query)
query = "INSERT INTO names (name) VALUES ('foo')"
c.execute(query)
query = "INSERT INTO names (name) VALUES ('boo')"
c.execute(query)
conn.commit()
def get_ID(name):
query = "SELECT ID FROM names WHERE name = '{}'".format(name)
c.execute(query)
id = c.fetchall()
print(id)
return id
print(get_ID("foo"))
conn.create_function("GETID", 1, get_ID)
query = "SELECT GETID(?)"
c.execute(query, ("foo",))
print(c.fetchall())
c.close()
conn.close()
</code></pre>
<p>This is the ouptut:</p>
<pre><code>[(1,)]
[(1,)]
Traceback (most recent call last):
File "D:\Sync1\Code\Python3\test.py", line 33, in <module>
c.execute(query, ("foo",))
sqlite3.OperationalError: user-defined function raised exception
</code></pre>
<p>Why does my function give an error?</p>
|
<python><sqlite>
|
2023-03-19 10:58:46
| 1
| 472
|
Abel Gutiérrez
|
75,781,441
| 8,350,828
|
Python binance websocket stream code for getting user data and coin price
|
<p>I am trying to get binance futures data from a websocket stream. I've gone through all the binance documentation tried several different python approaches, but don't seem to be successfull.</p>
<p>I am running my code on python-anywhere servers.</p>
<p>I would like to also know, how do you handle reconnections to the stream and for how long do the streams stay open.</p>
<p>The data I need through the websocket:</p>
<ul>
<li>SYMBOL TICKER</li>
<li>FUTURES ACCOUNT BALANCE</li>
<li>FUTURES OPEN POSITIONS, ORDERS</li>
</ul>
<p>Any help and directions would be greatly appreciated.</p>
<p>I've tried this sample, but I don't get any response from the stream.</p>
<pre><code>import asyncio
from binance import AsyncClient, BinanceSocketManager
# API keys
API_KEY = '<api_key>'
API_SECRET = '<api_secret>'
# Binance API endpoint
BASE_URL = 'https://fapi.binance.com'
async def main():
client = await AsyncClient.create(api_key=API_KEY,api_secret=API_SECRET)
bm = BinanceSocketManager(client)
# start any sockets here, i.e a trade socket
ts = bm.futures_socket() # Tried also bm.futures_user_socket()
# then start receiving messages
async with ts as tscm:
while True:
res = await tscm.recv()
print(res)
await client.close_connection()
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
</code></pre>
|
<python><websocket><binance><binance-api-client><python-binance>
|
2023-03-19 10:46:18
| 2
| 813
|
Jože Strožer
|
75,781,328
| 17,884,397
|
PyTorch + Skorch: Make the TensorBoard callbakc keep track on manual scores defined by `EpochScoring`
|
<p>I am using <a href="https://github.com/skorch-dev/skorch" rel="nofollow noreferrer">Skorch</a>.</p>
<p>I created a new score logging using the <a href="https://skorch.readthedocs.io/en/stable/callbacks.html#skorch.callbacks.EpochScoring" rel="nofollow noreferrer"><code>EpochScoring</code></a> callback.<br />
While it appears on the history log, It doesn't show on TensorBoard (I am using the <a href="https://skorch.readthedocs.io/en/stable/callbacks.html#skorch.callbacks.TensorBoard" rel="nofollow noreferrer"><code>TensorBoard</code></a> callback).</p>
<p>Is there a way to make the TensorBoard logger be aware of that key?</p>
<p>I know I can do a manual callback, but I wonder if there's a simple way to get the logger save an existing key from history.</p>
|
<python><pytorch><tensorboard><skorch>
|
2023-03-19 10:22:46
| 1
| 736
|
Eric Johnson
|
75,781,261
| 2,708,519
|
MacOS capture of still image from AVFoundation camera silently fails
|
<p><strong>Problem</strong>: I am trying to use a python function, <strong>capture_image(unique_id, dest_filename),</strong> for MacOS that is supposed to capture a still image from a video camera using the <em>AVFoundation</em> framework and the <em>pyobjc-framework-AVFoundation</em> framework.</p>
<p><strong>Expected result:</strong>
Given an AVFoundation <em>unique_id</em> and a <em>dest_filename</em> passed as parameters, a JPG still image should be captured from the camera with AVFoundation <em>unique id</em>. The image should be written to the JPG file with the name <em>dest_filename</em>.</p>
<p>In my test I called this function 5 times and I expected to see this output:</p>
<pre><code>writing /tmp/images/image_1.jpg
writing /tmp/images/image_2.jpg
writing /tmp/images/image_3.jpg
writing /tmp/images/image_4.jpg
writing /tmp/images/image_5.jpg
list_of_image_files_written=['image_1.jpg','image_2.jpg','image_3.jpg','image_4.jpg','image_5.jpg']
Process finished with exit code 0
</code></pre>
<p><strong>Observed result:</strong>
The function silently fails to write the captured image to the desired file.</p>
<p><strong>No Runtime errors are thrown.</strong></p>
<p>In my test I called this function 5 times and I actually saw output (note that image directory is actually empty - no JPGs were actually written:</p>
<pre><code>writing /tmp/images/image_1.jpg
writing /tmp/images/image_2.jpg
writing /tmp/images/image_3.jpg
writing /tmp/images/image_4.jpg
writing /tmp/images/image_5.jpg
list_of_image_files_written=[]
Process finished with exit code 0
</code></pre>
<p><strong>The <em>Pycharm</em> IDE <em>does show</em> these compile time errors and warnings:</strong></p>
<ul>
<li>Unresolved reference 'NSData': 31</li>
<li>Unresolved reference 'NSDataWritingAtomic': 32</li>
<li>Cannot find reference 'AVCaptureSession' in '__init__py | __init__py: 8</li>
<li>Cannot find reference 'AVCaptureDevice' in '__init__py | __init__py: 9</li>
<li>Cannot find reference 'AVMediaTypeVideo' in '__init__py | __init__py: 9</li>
<li>Cannot find reference 'AVCaptureDeviceInput' in '__init__py | __init__py: 17</li>
<li>Cannot find reference 'AVCaptureStillImageOutput' in '__init__py | __init__py: 18</li>
<li>Cannot find reference 'AVMediaTypeVideo' in '__init__py | __init__py: 27</li>
<li>Cannot find reference 'AVVideoCodecKey' in '__init__py | __init__py: 28</li>
<li>Cannot find reference 'AVVideoCodecTypeJPEG' in '__init__py | __init__py: 28</li>
<li>Cannot find reference 'AVCaptureStillImageOutput' in '__init__py | __init__py: 31</li>
<li>Local variable 'output_settings' value is not used: 28</li>
<li>PEP 8: E128 continuation line under_indented for visual indent: 30</li>
<li>PEP 8: E128 continuation line under_indented for visual indent: 31</li>
</ul>
<p>I am running on MacOS Ventura 13.2.1 using PyCharm.</p>
<p>I have searched the AVFoundation webpages as well as OpenStack and google, but without success in finding a better example.</p>
<p><strong>The code:</strong></p>
<pre><code>import os
import AVFoundation
import time
def capture_image(unique_id, dest_filename):
# Set up AVFoundation capture session
session = AVFoundation.AVCaptureSession.alloc().init()
devices = AVFoundation.AVCaptureDevice.devicesWithMediaType_(AVFoundation.AVMediaTypeVideo)
device = None
for dev in devices:
if dev.uniqueID() == unique_id:
device = dev
break
if device is None:
raise ValueError("No camera found with unique ID: " + unique_id)
input_session = AVFoundation.AVCaptureDeviceInput.deviceInputWithDevice_error_(device, None)[0]
output_session = AVFoundation.AVCaptureStillImageOutput.alloc().init()
session.addInput_(input_session)
session.addOutput_(output_session)
session.startRunning()
# Wait for the capture to be ready
time.sleep(2)
# Capture the image
connection = output_session.connectionWithMediaType_(AVFoundation.AVMediaTypeVideo)
output_settings = {AVFoundation.AVVideoCodecKey: AVFoundation.AVVideoCodecTypeJPEG}
output_session.captureStillImageAsynchronouslyFromConnection_completionHandler_(connection,
lambda buffer, error:
NSData.dataWithData_(AVFoundation.AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation_(buffer))
.writeToFile_options_error_(dest_filename, NSDataWritingAtomic, None))
# Stop the session
session.stopRunning()
print(f'writing {dest_filename}')
return dest_filename
if __name__ == '__main__':
images_dict = {
'0x143141300bda5829': '/tmp/images/image_1.jpg',
'0x143141100bda5829': '/tmp/images/image_2.jpg',
'0x143200000bda5829': '/tmp/images/image_3.jpg',
'0x143300000bda5829': '/tmp/images/image_4.jpg',
'0x143121200bda5829': '/tmp/images/image_5.jpg',
}
for the_unique_id in images_dict:
capture_image(the_unique_id, images_dict[the_unique_id])
list_of_image_files_written = os.listdir('/tmp/images')
print(f'{list_of_image_files_written=}')
</code></pre>
|
<python><avfoundation>
|
2023-03-19 10:07:02
| 0
| 1,529
|
mcgregor94086
|
75,781,214
| 2,669,433
|
Is there no-loop implementation of sparse dot-products of vectors in Python?
|
<p>Suppose <code>X</code> is a Numpy array of size <code>(N, d)</code>. I want to calculate an <code>N</code>-by-``N` matrix</p>
<pre><code>A[i,j] = S[i,j] * numpy.dot(X[i,:], X[j,:]),
</code></pre>
<p>where <code>S</code> is a sparse array with a few nonzero entries. Of course I can loop over all nonzero entries in <code>S</code> to calculate the corresponding <code>A[i,j]</code>, but that is slow in Python (even in Numba).</p>
<p>Is there a more elegant (efficient) way to calculate without loops (e.g., by some built-in functions)?</p>
|
<python><sparse-matrix><dot-product>
|
2023-03-19 09:54:31
| 0
| 629
|
rozyang
|
75,781,093
| 12,214,867
|
How do I put a label inside each bar with matplotlib or any other python visualization lib?
|
<p>I'm trying to draw a figure like the one below.</p>
<p><a href="https://i.sstatic.net/832GZ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/832GZ.png" alt="enter image description here" /></a></p>
<p>here is the code</p>
<pre><code>x = [0, 1, 2]
y = [88909, 27155, 12897]
plt.bar(x, y, tick_label = ['Pre-K, elementary, and middle',
'Secondary and high', 'Other, ungraded, and n/a or not reported'])
</code></pre>
<p>to put a label inside each bar, I could use <code>plt.text</code>. However, I need to calculate the coordinates for each.</p>
<p>Is there a way to have some kind of lib do it for me, and I just need to provide the strings?</p>
|
<python>
|
2023-03-19 09:27:12
| 1
| 1,097
|
JJJohn
|
75,780,885
| 7,359,831
|
Literal alternative in Python
|
<p>According to <a href="https://peps.python.org/pep-0585/#implementation" rel="nofollow noreferrer">this doc</a>,</p>
<blockquote>
<p>Importing those from typing is deprecated. Due to PEP 563 and the intention to minimize the runtime impact of typing, this deprecation will not generate DeprecationWarnings. Instead, type checkers may warn about such deprecated usage when the target version of the checked program is signalled to be Python 3.9 or newer. It’s recommended to allow for those warnings to be silenced on a project-wide basis.</p>
</blockquote>
<p>I tried to use literal type without using <code>typing.Literal</code> like the following</p>
<pre class="lang-py prettyprint-override"><code>def foo(flag: bool) -> "hello" | "hi": # <- error
return "hello" if flag else "hi"
</code></pre>
<p>I used <code>|</code> because python supports <code>str | int</code>, however, I got syntax error with literal.</p>
<p>How can I declare multiple literal type?</p>
|
<python>
|
2023-03-19 08:36:53
| 1
| 1,786
|
Pytan
|
75,780,692
| 1,319,998
|
How to show 100% for 0 iterations in tqdm?
|
<p>I have a "dynamic total" situation in tqdm, where sometimes the total number of iterations will be 0. And in this case, I would like to show 100% at the end, since all the iterations have been done.</p>
<p>I've tried this:</p>
<pre class="lang-py prettyprint-override"><code>from tqdm import tqdm
bar = tqdm()
bar.total = 0
bar.refresh()
</code></pre>
<p>but it shows:</p>
<pre><code>0it [00:00, ?it/s]
</code></pre>
<p>rather than something like:</p>
<pre><code>100%|████████████████████████████████████████████████████| 0/0 [00:00<00:00, 0it/s]
</code></pre>
<p>How can I get tqdm to treat 0 as a real total number of iterations that has been achieved?</p>
<p>In my case I will have quite a few progress bars, and some of them will have a dynamic total, and so some of them will be discovered to have 0 iterations needed.</p>
<p>I would like to be able to show 100% for the ones that are known to be done, so it's clear what's running and what's remaining.</p>
|
<python><tqdm>
|
2023-03-19 07:50:30
| 1
| 27,302
|
Michal Charemza
|
75,780,678
| 19,186,611
|
push to gateway function in prometheus client
|
<p>I want to push metrics to my Prometheus server via the push_to_gateway function but I set basic auth on the Prometheus server.
how can I send a username and password in the push_to_gateway function?</p>
|
<python><nginx><prometheus>
|
2023-03-19 07:47:23
| 1
| 433
|
lornejad
|
75,780,600
| 6,407,261
|
How to raise exceptions in python asyncio background task
|
<h3>Problem</h3>
<p>I have a few tasks that run continuously, but one of them occasionally needs to restart so this one is run in the background. How can exceptions from this background task be raised immediately? In the following example, the exception is not raised until the next attempt to restart, which can be very infrequent in real applications, so can undesirably go unnoticed for a long time.</p>
<h3>Example</h3>
<p><a href="https://replit.com/@PatrickPei/how-to-raise-exceptions-in-python-asyncio-background-task" rel="nofollow noreferrer">https://replit.com/@PatrickPei/how-to-raise-exceptions-in-python-asyncio-background-task</a></p>
<p>This example runs 3 tasks:</p>
<ol>
<li><code>foo</code>, which raises no exceptions</li>
<li><code>bar</code>, which raises an exception after 6 iterations</li>
<li><code>on_interval</code>, which restarts <code>bar</code> every 5 seconds</li>
</ol>
<pre class="lang-py prettyprint-override"><code>import asyncio
task = None
i = 0
async def foo():
while True:
print("foo")
await asyncio.sleep(1)
async def bar():
while True:
global i
i += 1
if i > 4:
raise ValueError()
print("bar", i)
await asyncio.sleep(1)
async def on_interval(n):
while True:
await asyncio.sleep(n)
# Cancel task.
global task
print("Canceling bar")
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
# Restart task.
print("Restarting bar")
task = asyncio.create_task(bar())
async def main():
# Start background task.
print("Starting bar")
global task
task = asyncio.create_task(bar())
# Start other tasks.
await asyncio.gather(
foo(),
on_interval(3),
)
if __name__ == "__main__":
asyncio.run(main())
</code></pre>
<h3>Output</h3>
<p><code>bar</code> iterates 4 times and raises an exception, which is not caught until the next restart, as shown by 3 <code>foo</code> iterations after <code>bar 4</code>. This is a problem when there is a lot of time in between restarts since exceptions go unnoticed for a long time.</p>
<pre><code>Starting bar
bar 1
foo
bar 2
foo
bar 3
foo
Canceling bar
Restarting bar
bar 4
foo
foo
foo
Canceling bar
Traceback (most recent call last):
File "~/example.py", line 60, in <module>
asyncio.run(main())
File "~/.pyenv/versions/3.10.5/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "~/.pyenv/versions/3.10.5/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
return future.result()
File "~/example.py", line 53, in main
await asyncio.gather(
File "~/example.py", line 37, in on_interval
await task
File "~/example.py", line 22, in bar
raise ValueError()
ValueError
</code></pre>
<h3>Attempts</h3>
<ul>
<li>Started another task to check <a href="https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.exception" rel="nofollow noreferrer"><code>asyncio.Task.exception</code></a>, but this is cumbersome because every background task needs another busy loop to help raise its exceptions.</li>
<li>Tried <a href="https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.add_done_callback" rel="nofollow noreferrer"><code>asyncio.Task.add_done_callback</code></a> but since the background task is still not awaited until the next restart, it only logs the error and does not stop the other task <code>foo</code>.</li>
</ul>
|
<python><python-3.x><async-await><python-asyncio>
|
2023-03-19 07:23:21
| 1
| 447
|
Patrick Pei
|
75,780,298
| 3,026,206
|
set the Python version of a venv
|
<p>I have installed a specific version of Python and it shows when I run pyenv versions:</p>
<pre><code>% pyenv versions
system
* 3.10.4 (set by .python-version)
</code></pre>
<p>However, when I try to use Python (in a venv or without), it always uses the system version instead of the specific version I want to use.</p>
<pre><code>% python3 --version
Python 3.10.6
% python3 -m venv venv3-10-4
% . venv3-10-4/bin/activate
(venv3-10-4) % python3 --version
Python 3.10.6
</code></pre>
<p>How do I get my system to use 3.10.4 inside and outside the venv?
I tried this, but it didn't help:</p>
<pre><code>pyenv global 3.10.4
</code></pre>
<p>I tried setting the version inside the venv too:</p>
<pre><code>(venv3-10-4) > % pyenv local 3.10.4
(venv3-10-4) > % python3 --version
Python 3.10.6
</code></pre>
|
<python><pyenv>
|
2023-03-19 05:48:54
| 1
| 3,560
|
beachCode
|
75,780,285
| 6,144,691
|
Passing Parameter from conf in Airflow PostgresOperator
|
<p>Want to access the config passed in the data in the API call</p>
<pre><code>curl --location 'http://localhost:8080/api/v1/dags/postgres_operator_dag/dagRuns' \
--header 'Content-Type: application/json' \
--data '{
"conf": {
"seller_id": "test_seller"
}
}'
</code></pre>
<p>Want to access seller_id in the sqlquery in PostgresOperator</p>
<pre><code>with DAG(dag_id="postgres_operator_dag", start_date=datetime(2020, 2, 2), schedule_interval=None) as dag:
# seller_id = context['dag_run'].conf['seller_id']. Cant access context here
connection_source_check = PostgresOperator(
task_id="fetch_connection_details",
postgres_conn_id="postgres_connection",
sql=f"""select c.name as connection_name, c.id as connection_id, a.name as source_name, a.id, a.actor_type as
source_id from "connection" c left join actor a on a.id=c.source_id where a.name=%(seller_id)s;""",
parameters={'seller_id': '{{ dag_run.conf["seller_id"] }}'},
dag=dag
)
</code></pre>
<p>The above task returns no data. But when I hardcode parameters as</p>
<pre><code>parameters={'seller_id': 'test_seller'}
</code></pre>
<p>It works.
Also Tried having sql file with params but with no effect.</p>
<p>This approach too doesnt work. It considers {{ dag_run.conf["seller_id"] }} as a string rather than evaluating the expression to test_seller and doesn't make the right query</p>
<pre><code>with DAG(dag_id="postgres_operator_dag", start_date=datetime(2020, 2, 2), schedule_interval=None) as dag:
connection_source_check = PostgresOperator(
task_id="fetch_connection_details",
postgres_conn_id="postgres_hogwarts_connection",
sql=f"""select c.name as connection_name, c.id as connection_id, a.name as source_name, a.id, a.actor_type as
source_id from "connection" c left join actor a on a.id=c.source_id where a.name= '{{ dag_run.conf["seller_id"] }}' ;""",
dag=dag
)
</code></pre>
<p>This approach gives a syntax error -</p>
<p>psycopg2.errors.SyntaxError: syntax error at or near "{"
LINE 2: ...ft join actor a on a.id=c.source_id where a.name={ dag_run....</p>
<pre><code>with DAG(dag_id="postgres_operator_dag", start_date=datetime(2020, 2, 2), schedule_interval=None) as dag:
connection_source_check = PostgresOperator(
task_id="fetch_connection_details",
postgres_conn_id="postgres_hogwarts_connection",
sql=f"""select c.name as connection_name, c.id as connection_id, a.name as source_name, a.id, a.actor_type as
source_id from "connection" c left join actor a on a.id=c.source_id where a.name={{ dag_run.conf["seller_id"] }};""",
dag=dag
)
</code></pre>
<p>What is the right approach to access the seller_id value that was passed in the curl request data.</p>
|
<python><postgresql><airflow><directed-acyclic-graphs><airflow-webserver>
|
2023-03-19 05:43:17
| 1
| 773
|
Arjunsingh
|
75,780,250
| 2,622,678
|
ImportError: attempted relative import with no known parent package when python file imports file from parent dir
|
<p>The following simple import fails with error. The python file child.py throws error when it imports a file from the parent dir. I can make it work by adding the parent path in sys.path.append() and importing the file. But I prefer relative import. What is the reason for import error.</p>
<pre><code>(venv) cs@comp-MBP child % ls ../
__init__.py child parent.py
(venv) cs@comp-MBP child % ls
child.py
(venv) cs@comp-MBP child % python child.py
Traceback (most recent call last):
File "....some_path/test/child/child.py", line 1, in <module>
from ..parent import test
ImportError: attempted relative import with no known parent package
</code></pre>
<p>Python file contents,</p>
<pre><code>(venv) cs@comp-MBP child % cat ../parent.py
def test():
print("calling test function")
(venv) cs@comp-MBP child %
(venv) cs@comp-MBP % cat child.py
from ..parent import test
test()
(venv) cs@comp-MBP %
</code></pre>
|
<python><python-3.x><python-import>
|
2023-03-19 05:29:16
| 0
| 443
|
user2622678
|
75,780,103
| 7,520,419
|
HuggingFace Transformers Trainer._maybe_log_save_evaluate IndexError: invalid index to scalar variable
|
<p>So, I'm working on fine tuning a BART model for question generation, and it seems to be going through training okay. Then all of a sudden, it stops at the end of the first validation with an <code>IndexError</code> which you can see below. The problem is occurring in the <code>Trainer._maybe_log_save_evaluate</code> method that is being called.</p>
<p><a href="https://i.sstatic.net/jV2jN.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/jV2jN.png" alt="IndexError: invalid index to scalar variable." /></a></p>
<p>Here is my code for setting up the model, tokenizer, dataset, etc.:</p>
<pre class="lang-py prettyprint-override"><code>from datasets import load_dataset
from evaluate import load
from accelerate import Accelerator
from transformers import BartForConditionalGeneration, BartConfig, BartTokenizer
from transformers import Seq2SeqTrainingArguments, Seq2SeqTrainer
dataset = load_dataset("squad")
metric = load("squad")
accelerator = Accelerator()
def model_init():
config = BartConfig()
return accelerator.prepare(BartForConditionalGeneration(config).from_pretrained("facebook/bart-base").cuda())
tokenizer = accelerator.prepare(BartTokenizer.from_pretrained("facebook/bart-base"))
def preprocess_function(data):
inputs = tokenizer(data['context'], add_special_tokens=True, max_length=256, padding="max_length", truncation=True)
targets = tokenizer(data['question'], add_special_tokens=True, max_length=32, padding="max_length", truncation=True)
return {'input_ids': inputs['input_ids'], 'attention_mask': inputs['attention_mask'], 'labels': targets['input_ids']}
dataset = dataset.map(preprocess_function, batched=True).shuffle(seed=777)
training_args = Seq2SeqTrainingArguments(
output_dir="./results",
evaluation_strategy="steps",
eval_steps=500,
save_steps=50000,
learning_rate=2e-5,
per_device_train_batch_size=4,
per_device_eval_batch_size=4,
num_train_epochs=2,
weight_decay=0.01,
predict_with_generate=True,
)
def compute_metrics(eval_pred):
predictions, labels = eval_pred
predictions = predictions.argmax(axis=-1)
return metric.compute(predictions=predictions, references=labels)
trainer = Seq2SeqTrainer(
args=training_args,
train_dataset=dataset["train"],
eval_dataset=dataset["validation"],
tokenizer=tokenizer,
model_init=model_init,
compute_metrics=compute_metrics,
)
trainer.train()
</code></pre>
<p>I can't seem to figure out why this is happening and nothing I've found online has helped.</p>
|
<python><pytorch><nlp><huggingface-transformers><huggingface>
|
2023-03-19 04:31:40
| 1
| 606
|
Sintrias
|
75,780,093
| 1,424,739
|
How to deal with "=2E" in get_body()?
|
<pre><code>import email
import email.policy
import sys
msg = email.message_from_string(sys.stdin.read(), policy=email.policy.default)
print(msg.get_body('plain').get_payload())
</code></pre>
<p>input.eml</p>
<pre><code>MIME-Version: 1.0
From: my from
To: email@to.com
Subject: my subject
Content-Type: multipart/mixed;
boundary="----=_Part_2296279_969698842.1679155313994"
Date: Sat, 18 Mar 2023 16:01:53 +0000 (UTC)
------=_Part_2296279_969698842.1679155313994
Content-Type: multipart/alternative;
boundary="----=_Part_2296278_601255348.1679155313994"
------=_Part_2296278_601255348.1679155313994
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
email app=2E this is a test =2E
------=_Part_2296278_601255348.1679155313994
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: 7bit
<!DOCTYPE html>
<html>
<body>
this is html
</body>
</html>
------=_Part_2296278_601255348.1679155313994--
------=_Part_2296279_969698842.1679155313994--
</code></pre>
<p><code>get_body()</code> shows things like <code>=2E</code>. Is it a dot? How to automatically convert such escaped strings to the actual characters?</p>
<pre><code>$ ./main.py < input.eml
email app=2E this is a test =2E
</code></pre>
|
<python><email><quoted-printable>
|
2023-03-19 04:28:39
| 1
| 14,083
|
user1424739
|
75,779,972
| 191,899
|
Python: Is there a way to use sql against an array?
|
<p>I am new to python, but not new to programming. So there may be a lot of knowledge I have yet to master. Or learn the best way to solve a problem.</p>
<p>I have a project, that I have gotten to using fake data generated, to display in an html table.</p>
<p>But to manipulate for various reports I want to do on it. Normally I would insert all the data to a mysql table, and then run a query against that. None of this data is something I need to keep for very long, just long enough to run a variety of reports I want to create.</p>
<p>I have two ways to get data, one way which already works creates an array of fake data with correct column headers.</p>
<p>The other way which I haven't started working on yet, will import a csv file.</p>
<p>I want to run queries against the data regardless of the source.</p>
<p>Is the only way to do this, via inserting data, and then querying that data?</p>
<p>Or is there another way, where I import the csv or fake data into an array, and run the queries on that without being forced to save or import the data?</p>
<p>That is the core of my question.</p>
<p>I apologize for my lack of knowledge of python.</p>
<p>Thank you for your time.</p>
|
<python><sql><arrays>
|
2023-03-19 03:47:36
| 0
| 1,947
|
crosenblum
|
75,779,943
| 1,989,834
|
numpy ndenumerate on 2D array with slicing gives incorrect indices
|
<p>Why I am getting incorrect indices while iterating over 2D array with slice using ndenumerate?</p>
<pre><code>arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
for idx, x in np.ndenumerate(arr[:, ::2]):
print(idx, x)
</code></pre>
<p>Output:</p>
<pre><code>(0, 0) 1
(0, 1) 3
(1, 0) 5
(1, 1) 7
</code></pre>
<p>I think it should give the following output:</p>
<pre><code>(0, 0) 1
(0, 2) 3
(1, 0) 5
(1, 2) 7
</code></pre>
<p>NOTE: Without using slice, I am getting the correct indices.</p>
|
<python><python-3.x><numpy><numpy-ndarray>
|
2023-03-19 03:36:39
| 1
| 657
|
PatilUdayV
|
75,779,796
| 145,504
|
UnicodeDecodeError for invalid sequence beyond requested read
|
<p>Suppose I write a UTF-8 encoded string to a file, followed by a byte sequence that is invalid in UTF-8:</p>
<pre class="lang-py prettyprint-override"><code>with open('/tmp/foo.txt', 'wb') as f:
f.write('αβγ'.encode('utf-8'))
f.write(b'\x80') # will cause unicode parse error if read
</code></pre>
<p>If I read exactly 3 UTF-8-encoded characters from this file, it should be fine, right?</p>
<pre class="lang-py prettyprint-override"><code>with open('/tmp/foo.txt', 'r', encoding='utf-8') as f:
print(f.read(3))
</code></pre>
<p>But actually it raises an error:</p>
<pre><code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 6: invalid start byte
</code></pre>
<p>Why is it trying to decode more than it needs to?</p>
|
<python><character-encoding>
|
2023-03-19 02:42:01
| 1
| 4,458
|
rgov
|
75,779,700
| 926,319
|
Retrieve a #[pyclass] from an attribute of an arbitrary PyAny
|
<p>Let us say I have the following Rust struct which becomes a Python class:</p>
<pre class="lang-rust prettyprint-override"><code>#[pyclass]
struct MyRustClass {
foo: i32
}
#[pymethods]
impl MyRustClass {
#[new]
fn new(foo: i32) {
MyRustClass { foo }
}
}
</code></pre>
<p>This class is made available to Python, and a new Python class, which is not implemented in Rust at all, holds an instance of this class in an attribute like so, for the purposes of this question, assume that this class is impossible to implement in Rust, and must be entirely Python side:</p>
<pre class="lang-py prettyprint-override"><code>class MyPythonClass:
def __init__(self, foo: int):
self.my_rust_class = MyRustClass(foo)
</code></pre>
<p>Now what I want to do, is be able to expose a <code>#[pyfunction]</code> which accepts an instance of <code>MyPythonClass</code> as an argument, and retrieves the <code>MyRustClass</code> struct from the <code>MyPythonClass.my_rust_class</code> attribute. This is the part I'm not sure about how to accomplish, but the function signature is something like below, where the <code>python_class</code> argument is an instance <code>MyPythonClass</code>:</p>
<pre class="lang-rust prettyprint-override"><code>#[pyfunction]
fn my_cool_function(python_class: PyAny) {
// Get some sort of reference to the MyRustClass struct from the MyPythonClass.my_rust_class attribute
}
</code></pre>
|
<python><rust><pyo3>
|
2023-03-19 02:01:15
| 1
| 2,054
|
Darren
|
75,779,691
| 1,424,739
|
How to extract text from the plain text part of multipart/alternative?
|
<pre><code># main.py
import email
from email.iterators import _structure
import sys
msg = email.message_from_string(sys.stdin.read())
_structure(msg)
</code></pre>
<pre><code>./main.py <<EOF
From: Nathaniel Borenstein <nsb@bellcore.com>
To: Ned Freed <ned@innosoft.com>
Subject: Formatted text mail
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary=boundary42
--boundary42
Content-Type: text/plain; charset=us-ascii
...plain text version of message goes here....
--boundary42
Content-Type: text/richtext
.... richtext version of same message goes here ...
--boundary42
Content-Type: text/x-whatever
.... fanciest formatted version of same message goes here
...
--boundary42--
EOF
</code></pre>
<p>The output</p>
<pre><code>multipart/alternative
text/plain
text/richtext
text/x-whatever
</code></pre>
<p>I can call the email module to get the structure of a multipart email message like the above. How can I extract the text/plain part of the email message? (In this particular example, it should be "...plain text version of message goes here....".)</p>
|
<python><email><multipart>
|
2023-03-19 01:56:43
| 1
| 14,083
|
user1424739
|
75,779,438
| 1,857,373
|
Value Error single feature (y, y_train) needs 2D array in digit recognizer train, fit/prediction OneVsRest classifier for Logistic
|
<p><strong>Problem</strong>
To perform prediction multi-class on digit-recognizer, data based on Kaggle data set.</p>
<p>Setting up OneVsRest classifier for multi-class prediction on digits using Logistic Regression and using RandomizedSearchCV for
best estimate and params, all working so far good.</p>
<p>Fit my model using the RandomizedSearchCV parameter grid results. The setup a new LogisticRegression multi-class to build models on OneVsRestClassifier.</p>
<p>Fit model is generated. Then use OneVsRestClassifier model to perform predict() on y. I know that reshaping is required before running a model. But what shape shall be appropriate with y, or y_train, when there is only one value, e.g, the 'label' value.</p>
<p>This is where the problem on ValueError occurs on ValueError that Expected 2D array, got 1D array instead:
array=[9 8 9 ... 8 8 8]. When I reshape y: y = np.array(y).reshape(1, -1), then I get "ValueError: X has 4125 features, but LogisticRegression is expecting 785 features as input."</p>
<p>I goofed, up, need code in setting up correct shape for prediction model using either y response or y_train. Both y, and y_train data has a single feature. So how does one use array.reshape(-1, 1) on a single feature (y, y_train) to create a 2D for the expected 2D array in the model execution?</p>
<p><strong>Shape</strong>
y and y_train both has shape (4125,). X_train_scaled is shape (4125, 785)</p>
<p><strong>Code for OneVsResst Classifier</strong></p>
<pre><code>train = pd.read_csv("../data/DigitRecognizer/train.csv")
test = pd.read_csv("../data/DigitRecognizer/test.csv")
train = train.loc[(train['label'] > 3) & (train['label'] > 7)]
X_train, X_test, y_train, y_test = train_test_split(train, y, test_size=0.50, random_state=42)
y = X_train['label']
df = X_train.drop(['label'], axis=1)
ovr_model = OneVsRestClassifier(LogisticRegression())
param_grid = {
'estimator__max_iter' : [2500, 4500, 6500, 9500, 14000],
'estimator__C': [0.1, 1, 100, 200]
}
ovr_grid_param = RandomizedSearchCV(ovr_model, param_grid, cv=5, n_jobs=3, error_score="raise")
min_max_scaler = preprocessing.MinMaxScaler()
X_train_scaled = min_max_scaler.fit_transform(X_train)
ovr_fit = ovr_grid_param.fit(X_train_scaled, y_train)
print("\n OVR best estimator search result:\n", ovr_fit.best_estimator_)
print("\n OVR best score search result:\n", ovr_fit.best_score_)
print("\n OVR best parameters search result:\n", ovr_fit.best_params_)
ovr_model_best = OneVsRestClassifier(LogisticRegression(multi_class='ovr', C=200, max_iter=9500, solver='liblinear'))
ovr_model_best_fit = ovr_model_best.fit(X_train_scaled, y_train)
y = np.array(y).reshape(1, -1)
ovr_model_best_pred = ovr_model_best_fit.predict(y)
ovr_score = cross_val_score(ovr_model_best, X_train, y_train, cv=3, scoring="accuracy")
</code></pre>
<p><strong>Error Logistic Model expecting</strong></p>
<pre><code>ValueError: X has 4125 features, but LogisticRegression is expecting 785 features as input.
</code></pre>
<p><strong>2D Value Error on predict</strong></p>
<pre><code>ValueError: Expected 2D array, got 1D array instead:
array=[9 8 9 ... 8 8 8].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
</code></pre>
<p><strong>Data X_train_scaled</strong></p>
<pre><code>array([[1., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[1., 0., 0., ..., 0., 0., 0.],
...,
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.]])
</code></pre>
<p><strong>Data y_train</strong></p>
<pre><code>35436 9
24713 8
37408 9
22832 9
23308 9
22425 9
28629 9
6296 9
32284 9
5523 8
19412 9
23756 9
38163 9
34117 9
15413 9
5722 8
32083 8
31210 9
26297 9
23171 8
Name: label, dtype: int64
</code></pre>
<p><strong>Data y</strong></p>
<pre><code>35436 9
24713 8
37408 9
22832 9
23308 9
22425 9
28629 9
6296 9
32284 9
5523 8
19412 9
23756 9
38163 9
34117 9
15413 9
5722 8
32083 8
31210 9
26297 9
23171 8
Name: label, dtype: int64
</code></pre>
|
<python><arrays><machine-learning><prediction>
|
2023-03-19 00:26:30
| 1
| 449
|
Data Science Analytics Manager
|
75,779,304
| 13,079,519
|
How to implement this idea into objective fucntion with Gurobi PY
|
<p>I am working on an optimization project here and my objective is to come out with the optimal amount of each item to buy at certain vendors that can minimize the cost while meeting the demand(already figured out the demand constraints). Here is a little background for the case below, there are 2 Vendor, 2 distribution centers(DC), 2 items(UPC), 2 Microfulfillment centers (MFC) and the chart also contain the price, weight, and cube of each items.</p>
<p>The freight cost of each vendor(v1, v2) is also below where v1 charges a freight fee based on the total weight and cube of all ordered items from one DC to one MFC; v2 charges a freight fee based on the total order amount(in $) from one DC to one MFC.</p>
<p>Everything else for this model is done except for this complicated freight cost in the objective function. I am stuck on this part and would really appreciate some help on how to implement this freight fee idea. I do have an idea which is to first calculate the total the weight and cube of all ordered items from one DC to one MFC(using gp.quicksum()), then use multiple if-else statements to compare with the cube and weight range and use the corresponding freight fee. The same idea applies to v2 where it is based on the total order amount in dollars.</p>
<p>Would really want some advice on whether my idea will work OR if anyone can share an easier way to implement this idea would be greatly appreciated!</p>
<p><a href="https://i.sstatic.net/0CbUZ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/0CbUZ.png" alt="enter image description here" /></a></p>
<p><a href="https://i.sstatic.net/Jmuom.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Jmuom.png" alt="enter image description here" /></a></p>
<p><a href="https://i.sstatic.net/rFvRv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/rFvRv.png" alt="enter image description here" /></a></p>
|
<python><optimization><gurobi>
|
2023-03-18 23:42:08
| 2
| 323
|
DJ-coding
|
75,779,053
| 17,884,397
|
Subclass a Python class with predefined parameters in one liner
|
<p>Given a simple class:</p>
<pre class="lang-py prettyprint-override"><code>class MyClassA():
def __init__(self, param_a, param_b):
self.param_a = param_a
self.param_b = param_b
def my_method(self, param_c):
return some_fun(self.param_a, self.param_b)
</code></pre>
<p>Now I want to create an instance of this class with just <code>param_b</code> being set.
Namely something like:</p>
<pre class="lang-py prettyprint-override"><code>class MyClassB(MyClassA):
def __init__(self, param_a):
super().__init__(param_a, something)
</code></pre>
<p>Now I want: <code>my_obj_c = MyClassB(some_val)</code>.</p>
<p>The question, is there a way to get <code>my_obj_c</code> in one liner without explicitly building <code>MyClassB</code>?</p>
<h3>Motivation</h3>
<p>The reason I need this is actually this class is used by a different procedure which supports calling the class with a single input.<br />
What I want is to try it (like grid search) which many different values of <code>param_b</code>. This is why setting a default value won't do it.</p>
|
<python><class><subclassing>
|
2023-03-18 22:35:01
| 2
| 736
|
Eric Johnson
|
75,779,002
| 14,847,960
|
Why can't I import config?
|
<p>I have a config.yml file with api keys in it, further, I have a .py file which greps for it.</p>
<p>I should theoretically be able to import config, and I can do so when I move the config.py file from the main directory into the correct subdirectory, but that doesn't quite work efficiently.</p>
<p>Forgive the poor attempt at file structure formatting.</p>
<p>in <code>directory</code></p>
<ul>
<li>servers
<ul>
<li>backend
<ul>
<li>file1.py</li>
<li>file2.py</li>
<li>file_i_need_config.py</li>
</ul>
</li>
</ul>
</li>
<li>config.py</li>
</ul>
<p>I am trying:</p>
<pre><code>from config import Config
print(Config.get_property("api_key_for_thing").unwrap())
</code></pre>
<p>and receiving the error:
ModuleNotFoundError: No module named 'config'</p>
<p>Any advice would be appreciated.</p>
|
<python>
|
2023-03-18 22:20:41
| 2
| 324
|
jd_h2003
|
75,778,972
| 5,574,107
|
Plotly choropleth with area labels
|
<p>I am trying to make a choropleth with this data (source links in code). The below does produce one, but it's hard to really get anything meaningful from it without knowing which area is which.</p>
<p>I have tried making an interactive choropleth with the second block of code. All this does is break my laptop - it just freezes, I guess some kind of memory issue (tried folium too and can't align my coords to theirs). The only alternative I could think of was to try and add coloured dots and a legend with the 'local authority name' column, but I have no idea how to do that. I also tried just adding labels with the initials of the area, but they are far too big for the granularity of the areas and the whole plot disappears under them.</p>
<p>Is there a way to neatly attach the local authority information to my plot? Thanks for any suggestions! :)</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
import geopandas as gpd
from mpl_toolkits.axes_grid1 import make_axes_locatable
import folium
import plotly.express as px
import pyproj
plt.style.use('ggplot')
import json
#source: https://www.ons.gov.uk/peoplepopulationandcommunity/personalandhouseholdfinances/incomeandwealth/datasets/householdsinpovertyestimatesformiddlelayersuperoutputareasinenglandandwales
populationData=pd.read_csv("householdsinpoverty2014.csv")
#source: https://geoportal.statistics.gov.uk/datasets/ons::msoa-dec-2021-boundaries-full-extent-bfe-ew/explore
mapData= gpd.read_file("MSOA.shp")
mapData.drop(columns=['Shape__Are', 'Shape__Len','GlobalID','OBJECTID'],inplace=True)
populationData.drop(columns=['Unnamed: 9'],inplace=True)
populationData2=populationData.iloc[3:].copy()
populationData2.columns=populationData2.iloc[0]
populationDataClean=populationData2.iloc[1:].copy()
populationDataClean.reset_index(inplace=True)
populationDataClean.dropna(inplace=True)
populationDataClean.drop(columns=['MSOA name', 'Local authority code','Percentage of Households Below 60% of the Median Income; (after housing costs); 95% Confidence Interval Lower Limit','Percentage of Households Below 60% of the Median Income; (after housing costs); 95% Confidence Interval Upper Limit'],inplace=True)
populationDataClean.sort_values(by=['Percentage of Households Below 60% of the Median Income; (after housing costs)'],inplace=True)
populationDataClean['PercentBelowMedIncome']=populationDataClean['Percentage of Households Below 60% of the Median Income; (after housing costs)'].astype(float)
mapStats=mapData.merge(populationDataClean[populationDataClean['Region name']=='London'],left_on='MSOA21CD',right_on='MSOA code') #Zoom into London: [populationDataClean['Region name']=='London']
fig, ax = plt.subplots(1, figsize=(8, 8))
plt.xticks(rotation=90)
#divider = make_axes_locatable(ax)
#cax = divider.append_axes("right", size="5%", pad=0.1)
mapStats.plot(column="PercentBelowMedIncome", cmap="Blues", linewidth=0.4, ax=ax, edgecolor=".4",scheme='equalinterval',missing_kwds={
"color": "lightgrey",
"edgecolor": "red",
"hatch": "///",
"label": "Missing values",
})
ax.set_title('% of Households Below 60% \n of the Median Income (London)', fontdict={'fontsize': '25', 'fontweight' : '3'})
ax.axis("off")
sm = plt.cm.ScalarMappable(cmap='Blues', norm=plt.Normalize(vmin=6.7, vmax=50))
# empty array for the data range
sm._A = []
# add the colorbar to the figure
cbar = fig.colorbar(sm)
</code></pre>
<pre><code>from plotly import graph_objects as go
fig = go.Figure(
go.Choroplethmapbox(
geojson=json,
featureidkey="properties.MSOA21CD",
locations=mapStats["MSOA21CD"], # <=== not areaCode
z=mapStats['PercentBelowMedIncome'],
zauto=True,
colorscale='Reds',
showscale=True
)
)
[ ]: fig.update_layout(mapbox_style='carto-positron',
mapbox_zoom=5,
mapbox_center_lon=-2.057852,
mapbox_center_lat=53.404854,
height=700,
width=700)
fig.show()
</code></pre>
|
<python><plotly><geopandas>
|
2023-03-18 22:13:59
| 1
| 453
|
user13948
|
75,778,919
| 3,507,584
|
How to load Plotly graphs fast in a webpage?
|
<p>I am using Django to create my first website. I have some complex plots made with Plotly which get passed to the render function as html (saved using <code>to_html</code> function). For example:</p>
<pre><code>def sample_plot():
import numpy as np
import pandas as pd
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Barpolar(
r=[77.5, 72.5, 70.0, 45.0, 22.5, 42.5, 40.0, 62.5],
name='11-14 m/s',
marker_color='rgb(106,81,163)'
))
fig.add_trace(go.Barpolar(
r=[57.5, 50.0, 45.0, 35.0, 20.0, 22.5, 37.5, 55.0],
name='8-11 m/s',
marker_color='rgb(158,154,200)'
))
fig.add_trace(go.Barpolar(
r=[40.0, 30.0, 30.0, 35.0, 7.5, 7.5, 32.5, 40.0],
name='5-8 m/s',
marker_color='rgb(203,201,226)'
))
fig.add_trace(go.Barpolar(
r=[20.0, 7.5, 15.0, 22.5, 2.5, 2.5, 12.5, 22.5],
name='< 5 m/s',
marker_color='rgb(242,240,247)'
))
fig.update_traces(text=['North', 'N-E', 'East', 'S-E', 'South', 'S-W', 'West', 'N-W'])
fig.update_layout(
title='Wind Speed Distribution in Laurel, NE',
font_size=16,
legend_font_size=16,
polar_radialaxis_ticksuffix='%',
polar_angularaxis_rotation=90,
)
return fig.to_html(config={'displayModeBar': False})
</code></pre>
<p><a href="https://i.sstatic.net/Lclke.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Lclke.png" alt="Sample plot" /></a></p>
<p>This is rendered as follows:</p>
<pre><code>sample_plot = sample_plot()
context = {'plot':sample_plot, ... other stuff ... }
return render(request, 'webpage.html', context)
</code></pre>
<p>Just passing this plot to the webpage (including it in <code>context</code>) increases loading time by 2.1 seconds (comparison using local server and same conditions). I have a few plots as complex as this one so the loading times make the webpage unusable.</p>
<p>Is this behaviour expected? Is there a better approach than using to_html to render the Plotly graphs? or is Plotly a non starter for webpage plots? Sorry if it is a basic mistake, it is my first website.</p>
<p><a href="https://i.sstatic.net/aG5SX.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/aG5SX.png" alt="Loading times comparison" /></a></p>
|
<python><html><django><plot><plotly>
|
2023-03-18 22:02:43
| 2
| 3,689
|
User981636
|
75,778,800
| 7,752,049
|
Filter on json data with in_() sqlalchemy
|
<p>I want to filter features(Json field on database) with items = a or b, but here it returns 0, when I use other columns the filter works correctly. It returns correct data with ["a"] or ["b"] too, what is the reason? and what is the solution?</p>
<pre><code>data.filter(Data.id.in_([1,2])) #works
data.filter(Data.features['items'].in_(["a"])) # returns 3
data.filter(Data.features['items'].in_(["b"])) # returns 1
data.filter(Data.features['items'].in_(["a","b"])) # returns 0 I exepect 4
</code></pre>
|
<python><sqlalchemy>
|
2023-03-18 21:34:51
| 2
| 2,479
|
parastoo
|
75,778,685
| 2,512,443
|
How to group each individual transaction from a buy and sell history
|
<p>Given a data frame that is sorted by symbol and date. I would like to add a new column that identifies each individual transaction. Each individual transaction means that the position is opened and closed after a set of buy and sell orders.</p>
<p>Input data</p>
<pre><code>time symbol side price size
08-19-2021 AAPL buy 150 1 ----> position opened here
08-20-2021 AAPL buy 100 1
08-21-2021 AAPL buy 200 1
08-22-2021 AAPL sell 300 1
08-23-2021 AAPL sell 350 0.5
08-24-2021 AAPL sell 400 1.5 ----> position closed here
08-25-2021 AAPL buy 150 2 -----> position opened here
08-26-2021 AAPL sell 100 2 ----> position closed here
08-27-2021 AAPL buy 100 2 ---> position opened here
08-28-2021 AAPL sell 150 1.5
08-29-2021 AAPL buy 100 0.5
08-29-2021 AAPL sell 50 0.5
08-29-2021 AAPL sell 50 0.5 ---> position closed here
08-29-2021 AAPL buy 100 1 ----> position opened here
08-29-2021 AAPL sell 50 0.5 ---> position still open here
</code></pre>
<p>Desired output (added column trade #)</p>
<pre><code>time symbol side price size trade #
08-19-2021 AAPL buy 150 1 0
08-20-2021 AAPL buy 100 1 0
08-21-2021 AAPL buy 200 1 0
08-22-2021 AAPL sell 300 1 0
08-23-2021 AAPL sell 350 0.5 0
08-24-2021 AAPL sell 400 1.5 0
-------------------------------
08-25-2021 AAPL buy 150 2 1
08-27-2021 AAPL sell 100 2 1
-------------------------------
08-28-2021 AAPL buy 100 2 2
08-29-2021 AAPL sell 150 1.5 2
08-29-2021 AAPL buy 100 0.5 2
08-29-2021 AAPL sell 50 0.5 2
08-29-2021 AAPL sell 50 0.5 2
------------------------------
08-29-2021 AAPL buy 100 1 3
08-29-2021 AAPL sell 50 0.5 3
</code></pre>
<p>The last trade is still open so I would like to still have a number for it.</p>
<p>Input data</p>
<pre><code>pd.DataFrame.from_dict({'symbol': ['AAPL', 'AAPL', 'AAPL', 'AAPL', 'AAPL', 'AAPL', 'AAPL', 'AAPL', 'AAPL', 'AAPL', 'AAPL', 'AAPL', 'AAPL', 'AAPL', 'AAPL'],
'side': ['buy', 'buy', 'buy', 'sell', 'sell', 'sell', 'buy', 'sell', 'buy', 'sell', 'buy', 'sell', 'sell', 'buy', 'sell'],
'size': [1,1,1,1,0.5,1.5,2,2,2,1.5, 0.5, 0.5, 0.5, 1, 0.5]})
</code></pre>
|
<python><pandas>
|
2023-03-18 21:10:06
| 1
| 473
|
user2512443
|
75,778,614
| 1,305,688
|
Merging on DatetimeIndexes and on = ''
|
<p>I have two <a href="/questions/tagged/pandas" class="post-tag" title="show questions tagged 'pandas'" aria-label="show questions tagged 'pandas'" rel="tag" aria-labelledby="tag-pandas-tooltip-container">pandas</a> data frames, that I need to merge on both indexes and one other variables. Like this,</p>
<pre><code>import pandas as pd
import numpy as np
n = 9
df1 = pd.DataFrame({
"ctr": np.repeat(['India', 'Indonesia', 'Italy'],n),
"group": np.resize([10,10,10,200,200,200,300,300,300],n*3),
"num": list(range(0,n*3))
})
index1 = pd.DatetimeIndex(np.tile(pd.date_range(start='31/12/2021', periods=3, freq='Q'), 9))
df1.index = pd.DatetimeIndex(index1)
df1
ctr group num
2021-12-31 India 10 0
2022-03-31 India 10 1
2022-06-30 India 10 2
2021-12-31 India 200 3
2022-03-31 India 200 4
2022-06-30 India 200 5
2021-12-31 India 300 6
2022-03-31 India 300 7
2022-06-30 India 300 8
2021-12-31 Indonesia 10 9
2022-03-31 Indonesia 10 10
2022-06-30 Indonesia 10 11
2021-12-31 Indonesia 200 12
2022-03-31 Indonesia 200 13
2022-06-30 Indonesia 200 14
2021-12-31 Indonesia 300 15
2022-03-31 Indonesia 300 16
2022-06-30 Indonesia 300 17
2021-12-31 Italy 10 18
2022-03-31 Italy 10 19
2022-06-30 Italy 10 20
2021-12-31 Italy 200 21
2022-03-31 Italy 200 22
2022-06-30 Italy 200 23
2021-12-31 Italy 300 24
2022-03-31 Italy 300 25
2022-06-30 Italy 300 26
df2 = pd.DataFrame({
"group": [10,10,200,200,300,300],
"num2": list(range(n*3,n*3+6))
})
index2 = pd.DatetimeIndex(np.tile(pd.date_range(start='31/3/2022', periods=2, freq='Q'), 3))
df2.index = pd.DatetimeIndex(index2)
df2
group num2
2022-03-31 10 27
2022-06-30 10 28
2022-03-31 200 29
2022-06-30 200 30
2022-03-31 300 31
2022-06-30 300 32
</code></pre>
<p>Now I've come as far as this,</p>
<pre><code>pd.merge(df1, df2, how='inner', left_index=True, right_index=True, on = 'group')
</code></pre>
<p>but it doesn't give what I'm looking for. What I would like to obtain is something like this where <code>df2</code> is repeated for each country in <code>df1</code>, like this. Is that possible?</p>
<pre><code> ctr group num num2
2021-12-31 India 10 0
2022-03-31 India 10 1 27
2022-06-30 India 10 2 28
2021-12-31 India 200 3
2022-03-31 India 200 4 29
2022-06-30 India 200 5 30
2021-12-31 India 300 6
2022-03-31 India 300 7 31
2022-06-30 India 300 8 32
2021-12-31 Indonesia 10 9
2022-03-31 Indonesia 10 10 27
2022-06-30 Indonesia 10 11 28
2021-12-31 Indonesia 200 12
2022-03-31 Indonesia 200 13 29
2022-06-30 Indonesia 200 14 30
2021-12-31 Indonesia 300 15
2022-03-31 Indonesia 300 16 31
2022-06-30 Indonesia 300 17 32
2021-12-31 Italy 10 18
2022-03-31 Italy 10 19 27
2022-06-30 Italy 10 20 28
2021-12-31 Italy 200 21
2022-03-31 Italy 200 22 29
2022-06-30 Italy 200 23 30
2021-12-31 Italy 300 24
2022-03-31 Italy 300 25 31
2022-06-30 Italy 300 26 32
</code></pre>
|
<python><pandas><datetime><merge>
|
2023-03-18 20:54:42
| 1
| 8,018
|
Eric Fail
|
75,778,543
| 649,133
|
Python telnetlib3 examples
|
<p>I would like to understand how to use telnetlib3 for a simple scenario.</p>
<p>The longstanding telnetlib (not 3) has a simple example at <a href="https://docs.python.org/3/library/telnetlib.html" rel="noreferrer">https://docs.python.org/3/library/telnetlib.html</a> where the python program connects to a telnet server, then looks for prompts and provides responses. One can readily see how to extend this example to different prompts, add timeouts, and add more prompt-response steps.</p>
<pre><code>import getpass
import telnetlib
HOST = "localhost"
user = input("Enter your remote account: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until(b"login: ")
tn.write(user.encode('ascii') + b"\n")
if password:
tn.read_until(b"Password: ")
tn.write(password.encode('ascii') + b"\n")
tn.write(b"ls\n")
tn.write(b"exit\n")
print(tn.read_all().decode('ascii'))
</code></pre>
<p>However, telnetlib (not 3) is deprecated.</p>
<p>The replacement, telnetlib3 ( <a href="https://telnetlib3.readthedocs.io/en/latest/intro.html#quick-example" rel="noreferrer">https://telnetlib3.readthedocs.io/en/latest/intro.html#quick-example</a> ) provides an example based on asyncio, and the async "shell" function (that interacts with the server) blocks waiting for prompt (rationale for async) and always responds to the server with 'y'.</p>
<pre><code>import asyncio, telnetlib3
async def shell(reader, writer):
while True:
# read stream until '?' mark is found
outp = await reader.read(1024)
if not outp:
# End of File
break
elif '?' in outp:
# reply all questions with 'y'.
writer.write('y')
# display all server output
print(outp, flush=True)
# EOF
print()
loop = asyncio.get_event_loop()
coro = telnetlib3.open_connection('localhost', 6023, shell=shell)
reader, writer = loop.run_until_complete(coro)
loop.run_until_complete(writer.protocol.waiter_closed)
</code></pre>
<p>I am a few clues short on how to get code that's structured this way to perform the more mainstream task that's demonstrated in the (literally!) straightforward telnetlib (not 3) example where the server provides a series of different prompts, and the python program is to provide corresponding responses. I suspect that this is partly down to my unfamiliarity with asyncio and what code patterns one should use to get an async function to carry out a series of steps.</p>
<p>So it would be a great help to see the telnetlib (not 3) example implemented in this style.</p>
|
<python><python-asyncio><telnetlib><telnetlib3>
|
2023-03-18 20:37:06
| 2
| 3,056
|
gwideman
|
75,778,369
| 19,349,670
|
Defining python class method with multiple function signature
|
<p>How to allow multiple behaviour of the delta_ method within the class depending on the parameters list?</p>
<pre><code>class Greeks:
@staticmethod
def delta_(
X: Option
) -> float:
"""
Compute the delta of an option represented by an `Option` object.
The delta measures the rate of change of the theoretical option value
with respect to changes in the underlying asset’s price.
Parameters:
X (Option): An `Option` object representing an option contract.
Returns:
float: The delta of the option.
"""
if X.flag == 'c':
return stats.norm.cdf(X.d1, 0, 1)
elif X.flag == 'p':
return -stats.norm.cdf(X.d1, 0, 1)
@staticmethod
def delta_(
S: float,
K: float,
v: float,
r: float,
T: datetime.datetime,
flag: str
) -> float:
"""
Compute the delta of an option represented by its parameters.
The delta measures the rate of change of the theoretical option value
with respect to changes in the underlying asset’s price.
Parameters:
S (float): The underlying asset price.
K (float): The strike price.
v (float): The volatility.
r (float): The risk-free interest rate.
T (datetime.datetime): The expiration date.
flag (str): The option type ('c' for call, 'p' for put).
Returns:
float: The delta of the option.
"""
T0 = datetime.datetime.today()
t = ((T - T0).days + 1) / 365 # Time to expiration in years
d1 = (np.log(S / K) + (r + 0.5 * v ** 2) * t) / (v * np.sqrt(t))
if flag == 'c':
return stats.norm.cdf(d1, 0, 1)
elif flag == 'p':
return -stats.norm.cdf(d1, 0, 1)
</code></pre>
<p>A possible solution, maybe not the cleanest, which allows one input only (Union[Option, Tuple[float, float, float, float, datetime.datetime, str]]) and has potentally lots of isinstance controls within:</p>
<pre><code>class Greeks(object):
@staticmethod
def delta_(
X: typing.Union[Option, typing.Tuple[float, float, float, float, datetime.datetime, str]]
) -> float:
"""
Delta measures the rate of change of the theoretical option value
with respect to changes in the underlying asset’s price.
"""
if isinstance(X, Option):
if X.flag == 'c': return stats.norm.cdf(X.d1, 0, 1)
elif X.flag == 'p': return -stats.norm.cdf(X.d1, 0, 1)
else:
S, K, v, r, T, flag = X
T0 = datetime.datetime.today()
t = ((T - T0).days + 1) / 365 # Time to expiration in years
d1 = (np.log(S / K) + (r + 0.5 * v ** 2) * t) / (v * np.sqrt(t))
d2 = d1 - v * np.sqrt(t)
if flag == 'c': return stats.norm.cdf(d1, 0, 1)
elif flag == 'p': return -stats.norm.cdf(d1, 0, 1)
</code></pre>
|
<python><class>
|
2023-03-18 20:02:37
| 1
| 873
|
solid
|
75,778,242
| 11,665,178
|
Signed Url is working after the expiration date Cloud Storage python
|
<p>I have found this <a href="https://stackoverflow.com/questions/56504545/signed-url-is-working-beyond-expiration-date">question</a> that seems dead so i will add more context.</p>
<p>i am using the python google-cloud-storage sdk to generate signed urls using <code>blob.generated_signed_url()</code>.</p>
<p>Here is the full method i use :</p>
<pre><code>blob.generate_signed_url(expiration=datetime.now() + timedelta(minutes=1), version="v4")
</code></pre>
<p>I live in France so my Timezone is +1h from datetime.now().</p>
<p>The generated URL looks fine, i see the part of the expiration and the date : <code>X-Goog-Date=20230318T191451Z&X-Goog-Expires=3659</code></p>
<p>But now it's 20min after this delay and the doc is still available.</p>
<p>Note : I have also tried using <code>timedelta(hours=1, minutes=1)</code> to simulate the France Timezone but it is still available also after 2mins of waiting.</p>
<p>What I am doing wrong ?</p>
|
<python><google-cloud-platform><google-cloud-storage>
|
2023-03-18 19:38:45
| 1
| 2,975
|
Tom3652
|
75,778,228
| 5,212,614
|
How can we loop through dates in a dataframe, and append strings to create a valid URL?
|
<p>I am trying to loop through dates in a dataframe (dates are formatted as string type) and get two rows at a time, for start and end. For each pair, I am trying to append to a string to create a URL and pass it to an API. Here is the code that I have so far.</p>
<pre><code>import pandas as pd
from datetime import date, timedelta
sdate = date(2023,1,1) # start date
edate = date(2023,3,20) # end date
df_dates=pd.date_range(sdate,edate-timedelta(days=1),freq='w')
df_dates=pd.DataFrame(df_dates)
print(type(df_dates))
print(df_dates.shape)
df_dates.columns = ['mydate']
df_dates['mydate']=df_dates['mydate'].astype(str)
print(df_dates.dtypes)
df_dates
</code></pre>
<p>The above part seems pretty much OK, unless I am missing something. Then, I run this line of code.</p>
<pre><code>url = "https://internal_api/assets?StartTime="+ str(row1) +"T12:00:12-04:00&EndTime="+ str(row2) +"T12:00:12-04:00"
</code></pre>
<p>Now, when I print the URL, I get this.</p>
<pre><code>https://internal_api/assets?StartTime=mydate 2023-03-12
Name: 10, dtype: objectT12:00:12-04:00&EndTime=mydate 2023-03-19
Name: 11, dtype: objectT12:00:12-04:00
</code></pre>
<p>This is what I actually need.</p>
<pre><code>"https://internal_api/assets?startTime=2023-03-12T14%3A00%3A12-04%3A00&endTime=2023-03-19T14%3A00%3A12-04%3A00"
</code></pre>
<p>How can I change the first URL into the second URL?</p>
|
<python><python-3.x><string><dataframe>
|
2023-03-18 19:36:36
| 1
| 20,492
|
ASH
|
75,778,215
| 7,236,133
|
build a list with different values in different indexes
|
<p>I have a <a href="https://datascience.stackexchange.com/questions/22762/understanding-predict-proba-from-multioutputclassifier">predictions probabilities</a> for multiclasses [0, 1], and I need to save the correct prediction probability for each row in my data set:</p>
<pre><code>probs = model.predict_proba(X_test)
idx_1 = np.where(y_test == 1)[0]
idx_0 = np.where(y_test == 0)[0]
</code></pre>
<p><code>probs</code> includes pairs of values, the first value in each pair is the probability for class 0 and the second is the probability for class 1 (both summing up to 1).</p>
<p>The shape of probs differs cause am calling it during cross_validation, but let's take an example of one iteration: (568, 2) and for y_test: 568</p>
<p>I tried the following to save the correct probability for each labeled data:</p>
<p><code>probs_per_class = [probs[idx_1, 1][i] if i in idx_1 else probs[idx_0, 0][i] for i in range(len(y_test))]</code></p>
<p>but getting</p>
<blockquote>
<p>out of bound</p>
</blockquote>
<p>error</p>
<p>if I expand it to simulate verbus mode:</p>
<pre><code> probs_per_class = []
for i in range(len(y_test)):
if i in idx_1:
probs_per_class.append(probs[idx_1, 1][i])
print(i, probs[idx_1, 1][i])
elif i in idx_0:
probs_per_class.append(probs[idx_0, 0][i])
print(i, probs[idx_0, 0][i])
</code></pre>
<p>failing on:</p>
<blockquote>
<p>IndexError: index 194 is out of bounds for axis 0 with size 191</p>
</blockquote>
<p>What is going wrong?</p>
|
<python>
|
2023-03-18 19:33:29
| 1
| 679
|
zbeedatm
|
75,778,166
| 6,843,103
|
DataprocCreateClusterOperator - in Composer2(Airflow), pip install specific versions
|
<p>I'm using DataprocCreateClusterOperator to create Dataproc cluster in the dag, using the following code (only relevant part of the dag shown below) :
I'm using init_actions_uris & passing script pip_install_versions.sh</p>
<p>This script installs 'specific' versions of the required software using 'pip install ==' command, as shown below :</p>
<pre><code>
path = "gs://pip-install/pip_install_versions.sh"
CLUSTER_GENERATOR_CONFIG = ClusterGenerator(
project_id=PROJECT_ID,
zone="us-east1-b",
master_machine_type="n1-highmem-8",
worker_machine_type="n1-highmem-8",
num_workers=2,
storage_bucket="dataproc-spark-logs",
init_actions_uris=[path],
metadata={'PIP_PACKAGES': 'pyyaml requests pandas openpyxl numpy google-cloud-storage prophet kafka-python pyspark'},
).make()
with models.DAG(
'vani-intf-test',
schedule_interval='0 18 * * *',
catchup=False,
max_active_runs=1,
default_args=default_dag_args
) as dag_pred:
create_dataproc_cluster = DataprocCreateClusterOperator(
task_id="create_dataproc_cluster",
cluster_name=CLUSTER_NAME,
region=REGION,
cluster_config=CLUSTER_GENERATOR_CONFIG
)
pip_install_version.sh
----------------------
pip install google-cloud-storage==1.31.0
pip install pandas==1.4.2
pip install pyspark==3.1.3
pip install prophet==1.1.1
pip install numpy==1.21.5
pip install kafka-python==2.0.2
pip install pymongo==4.3.3
</code></pre>
<p>Is this the best way to install specific versions in Composer2 ?
Can this be achieved using a requirements.txt file(containing the package & version) passed as well ?</p>
<p>I looked at the documentation, and somehow could not find examples using requirements.txt</p>
<p>Another clarification:
what does the PIP_PACKAGES in metadata do ?</p>
<pre><code>metadata={'PIP_PACKAGES': 'pyyaml requests pandas openpyxl numpy google-cloud-storage prophet kafka-python pyspark'
</code></pre>
<p>The difference between init_actions_uris=[path], & PIP_PACKAGES is not clear, appreciate if someone can clarify why we need both.</p>
<p>tia!</p>
|
<python><google-cloud-platform><pip><airflow><google-cloud-composer-2>
|
2023-03-18 19:25:05
| 2
| 1,101
|
Karan Alang
|
75,777,951
| 15,520,615
|
How to access the latest version of Delta table as Integer?
|
<p>Can someone let me know to convert the following from a Dataframe to an InterType()</p>
<pre><code>df = DeltaTable.forPath(spark, '/mnt/lake/BASE/SQLClassification/cdcTest/dbo/cdcmergetest/1').history().select(max(col("version")).alias("version"))
</code></pre>
<p>I have tried the following</p>
<pre><code>result = df.collect()[0]
result2 = df.withColumn("version",df.version.cast('integer'))
</code></pre>
<p>But with no luck</p>
<p>Any thoughts?</p>
|
<python><pyspark><delta-lake>
|
2023-03-18 18:44:22
| 3
| 3,011
|
Patterson
|
75,777,829
| 10,673,107
|
Python - Translate vertices to a different axis
|
<p>I am struggling with the following. I have 2 surfaces with the following vertices:</p>
<pre><code># Triangle
[[ 50. 50. 100.]
[100. 0. 0.]
[100. 100. 0.]]
#Square
[[ 0. 100. 0.]
[ 0. 100. 100.]
[100. 100. 0.]
[100. 100. 100.]]
</code></pre>
<p>Now here is how they look in a 3D chart:
<a href="https://i.sstatic.net/ieTGc.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ieTGc.png" alt="enter image description here" /></a></p>
<p>And:<br>
<a href="https://i.sstatic.net/TNgbc.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/TNgbc.png" alt="enter image description here" /></a></p>
<p>Now I want to apply some kind of translation on both these vertices so that both surfaces lay flat on the XY axis. I got this working for both figures, but the problem is that I need a function which can handle any given surface to be translated. I can provide code of what I had, but I don't think that that will help, because the code I have is written specifically for a triangle and square.</p>
<p>Working with these vertices is kinda new for me, so I don't know a lot of tricks, but I would really appreciate some tips on how I can achieve this!</p>
<p>My default code:</p>
<pre><code>import trimesh
import numpy as np
import matplotlib.pyplot as plt
vertices = np.array([[0, 100, 0], [0, 100, 100], [100, 100, 0], [100, 100, 100]])
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(vertices[:, 0], vertices[:, 1], vertices[:, 2])
plt.show()
</code></pre>
<h2>UPDATE</h2>
<p>After the given answer, I build an implementation of <a href="https://github.com/Funderburger/mpi-planar-correction/blob/7f028b052d5fecc14dcb1502306e9ac65942a31f/MonoDepth-FPN-PyTorch/main_fpn_curv_grad.py#L325" rel="nofollow noreferrer">this</a> method. Mine looks like this (not sure if it does work):</p>
<pre><code>def find_plane(pts, thresh=0.05):
"""
Find the equation of a plane from a set of points that lie on the plane.
:param pts: 3D point cloud as a `numpy.array (N,3)`.
:param thresh: Threshold distance from the plane which is considered inlier.
:returns:
- `plane_eq`: Parameters of the plane using Ax+By+Cy+D `torch.tensor (1, 4)`
"""
n_points = pts.shape[0]
# We have to find the plane equation described by three points on the plane
# Select three random points
pt_samples = pts[:3]
# We find first 2 vectors that are part of this plane
# A = pt2 - pt1
# B = pt3 - pt1
vecA = pt_samples[1, :] - pt_samples[0, :]
vecB = pt_samples[2, :] - pt_samples[0, :]
# Now we compute the cross product of vecA and vecB to get vecC which is normal to the plane
vecC = np.cross(vecA, vecB)
# The plane equation will be vecC[0]*x + vecC[1]*y + vecC[0]*z = -k
# We have to use a point to find k
vecC = vecC / np.linalg.norm(vecC)
k = -np.sum(np.multiply(vecC, pt_samples[1, :]))
plane_eq = [vecC[0], vecC[1], vecC[2], k]
# Distance from a point to a plane
# https://mathworld.wolfram.com/Point-PlaneDistance.html
pt_id_inliers = [] # list of inliers ids
dist_pt = (
plane_eq[0] * pts[:, 0] + plane_eq[1] * pts[:, 1] + plane_eq[2] * pts[:, 2] + plane_eq[3]
) / np.sqrt(plane_eq[0] ** 2 + plane_eq[1] ** 2 + plane_eq[2] ** 2)
# Select indexes where distance is biggers than the threshold
pt_id_inliers = np.where(np.abs(dist_pt) <= thresh)[0]
return torch.tensor(plane_eq), pt_id_inliers
</code></pre>
<p>But I am running into a problem. After calling this method I need to apply it on my vertices, so I tried this:</p>
<pre><code># Plot the points
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
plane_eq, inliers = find_plane(vertices)
# Extract the inlier points from the original vertices
inlier_points = vertices[inliers]
# Find the centroid of the inlier points
centroid = np.mean(inlier_points, axis=0)
# Compute the normal vector of the plane using the plane equation
normal = plane_eq[:3]
# Compute the distance of the plane from the origin
distance = plane_eq[3] / np.linalg.norm(normal)
# Compute the projection of each point in the inliers onto the plane
projected_points = inlier_points - np.outer(np.dot(inlier_points - centroid, normal), normal)
# Construct the new set of vertices by adding the projected points to the plane
transformed_vertices = np.concatenate((projected_points, np.array([centroid + distance * normal])))
ax.scatter(transformed_vertices[:, 0], transformed_vertices[:, 1], transformed_vertices[:, 2], c='green', marker='o')
plt.show()
</code></pre>
<p>The error I am getting is:</p>
<pre><code>---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[289], line 167
165 print(distance)
166 print(normal)
--> 167 transformed_vertices = np.concatenate((projected_points, np.array([centroid + distance * normal])))
168 print(transformed_vertices)
169 ax.scatter(transformed_vertices[:, 0], transformed_vertices[:, 1], transformed_vertices[:, 2], c='green', marker='o')
TypeError: Concatenation operation is not implemented for NumPy arrays, use np.concatenate() instead. Please do not rely on this error; it may not be given on all Python implementations.
</code></pre>
<p>These are the values I am trying to concatenate:</p>
<pre><code>centroid: [83.33333333 50. 33.33333333]
distance: tensor(-89.4427, dtype=torch.float64)
normal: tensor([0.8944, 0.0000, 0.4472], dtype=torch.float64)
</code></pre>
<p>Again, I am not sure if I am doing this correctly, so all the help is welcome!</p>
<p>How can I fix this?</p>
|
<python>
|
2023-03-18 18:19:44
| 1
| 994
|
A. Vreeswijk
|
75,777,664
| 8,497,979
|
Install python 3.10 on Debian 11 WSL to replace default version
|
<p>I would like to install Python 3.10.10 on my WSL Debian System. In particular I want to install it in the root usr/bin. The idea is that Debian uses python 3.10 as default python. Right now it uses 3.9.</p>
<p>What I tried was:</p>
<ol>
<li><p>install the required dependencies to be able to build Python 3.10 from the source.</p>
<pre><code> sudo apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev libsqlite3-dev wget libbz2-dev
</code></pre>
</li>
<li><p>Then download Python 3.10 from the official Python release page.</p>
<pre><code>wget https://www.python.org/ftp/python/3.10.0/Python-3.10.10.tgz
</code></pre>
</li>
<li><p>extract it as below</p>
<pre><code>tar -xf Python-3.10.*.tgz
</code></pre>
</li>
<li><p>now run the configure command</p>
<pre><code>./configure --enable-optimizations --prefix="/usr/bin"
</code></pre>
</li>
<li><p>finally I build python from that source</p>
<pre><code>make -j 4
</code></pre>
</li>
</ol>
<p>It builds python just right, but builds it in the local bin (usr/local/bin).
Hence when I check:</p>
<pre><code> python3 -V
</code></pre>
<p>I get the old Python Version (3.9) instead of the new one used as default.
What am I doing wrong?</p>
<p>Tkx in advance</p>
|
<python><windows-subsystem-for-linux>
|
2023-03-18 17:51:32
| 3
| 1,410
|
aerioeus
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.