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
77,707,507
2,423,198
How to Include System Prompt and Instruction in Vertex AI LLaMA 2-7B Chat Model
<p>I'm working with the LLaMA 2-7B chat model deployed on Google Cloud's Vertex AI, and I'm facing a challenge in including a system prompt and user instruction within the model's prompt format.</p> <p>For local versions, I've been using a formatted prompt structure as follows:</p> <pre class="lang-py prettyprint-override"><code>system_prompt = &quot;Your system instruction here&quot; user_message = &quot;Your user input here&quot; formatted_prompt = f&quot;&quot;&quot; &lt;s&gt;[INST] &lt;&lt;SYS&gt;&gt; { system_prompt } &lt;&lt;/SYS&gt;&gt; { user_message } [/INST] &quot;&quot;&quot; </code></pre> <p>However, I'm unsure how to adapt this for use with the deployed model in Vertex AI. Here's the current code snippet I'm using for making predictions:</p> <pre class="lang-py prettyprint-override"><code>from google.cloud import aiplatform PROJECT_ID = &quot;--&quot; ENDPOINT_ID = &quot;--&quot; LOCATION = &quot;us-central1&quot; SERVICE_ACCOUNT_FILE = &quot;service_account.json&quot; def endpoint_predict_sample(project: str, location: str, instances: list, endpoint: str): aiplatform.init(project=project, location=location) endpoint = aiplatform.Endpoint(endpoint) prediction = endpoint.predict(instances=instances) print(prediction) return prediction instances = [ { &quot;prompt&quot;: &quot;Some prompt&quot;, &quot;max_tokens&quot;: 2000 } ] response = endpoint_predict_sample( project=PROJECT_ID, location=LOCATION, instances=instances, endpoint=ENDPOINT_ID ) </code></pre> <p>My question is, how do I properly integrate the system_prompt and user_message into the instances object for the deployed model? Should the formatted prompt be used directly, or is there a specific way to structure it for Vertex AI?</p>
<python><google-cloud-platform><google-cloud-vertex-ai><llama>
2023-12-23 11:43:17
0
3,400
deltascience
77,707,364
893,254
How should I structure my code when using SQL Alchemy and Reflection?
<p>I appologize for this question being slightly lengthy. The TLDR is:</p> <ul> <li>I am struggling to understand how to structure my code when using the reflection features of SQL Alchemy ORM</li> <li>This is because in order to construct &quot;an instance of a table type&quot; I appear to have to pass around a <code>metadata</code> object, rather than &quot;just being able to use the type&quot; as you would any other Python type</li> <li>This might be necessary, becuase the types are not known statically (when the Python code has been written)</li> <li>but I am seeking further advice becuase this is unfamiliar to me and I do not really know what I am doing</li> </ul> <h3>End of TLDR</h3> <p>I'm struggling slighly with understanding exactly what the intention is in regards to how I should structure my code when working with SQL Alchemy and Reflection.</p> <p>When using Reflection, types are dynamically created at runtime by Python depending on the structure of a table in an SQL database.</p> <p>Because my types are only available when I execute my code, and not when I write it, I am having a bit of a conceptual block as to how to structure it.</p> <p>The minimum amount of code required to perform a reflection operation and obtain an object representing a type is something like the following:</p> <pre><code>db_url = &quot;postgresql://postgres:password@localhost/postgresdb&quot; engine = sqlalchemy.create_engine(url=db_url) metadata = sqlalchemy.MetaData() my_table_object = sqlalchemy.Table('my_table', metadata, autoload_with=engine) with engine.connect() as connection: # rest of code </code></pre> <p><code>my_table_object</code> can now be used to perform CRUD:</p> <pre><code>query = sqlalchemy.select(my_table_object) result_proxy = connection.execute(query) result_set = result_proxy.fetchall() print(result_set[0]) </code></pre> <h3>My existing code:</h3> <p>Most of my existing code has been written without using any of the ORM features of SQL Alchemy. This means that I was working exclusively with the <code>text</code> object and SQL DSL code.</p> <p>For example, I have functions which look a bit like this:</p> <pre><code>def select_id_from_my_table(connection: sqlalchemy.Connection): query_string = text( ''' select id from my_table ''' ) query_params = { } result = connection.execute(query_string, query_params) # do something with result and return value(s) </code></pre> <p>Rather than passing the <code>engine</code> around, I decided to pass a single <code>connection</code> object. This is for two reasons:</p> <ul> <li>This is a single thread process (it's Python - and no libraries such as multiprocess are being used)</li> <li>There doesn't seem to be a lot of point adding additional latency by opening and closing the connection to perform database operations when I can just keep a single connection open for the lifetime of my program (opening it at the top level in the <code>def main</code> function and passing it around the call stack)</li> </ul> <p>As an asside, I am assuming this is a sensible design. If it isn't, please do leave a comment.</p> <h3>Adding ORM code:</h3> <p>The following line of code (taken from the first snippet) effectively creates a Python type. (A factory?)</p> <pre><code>my_table_object = sqlalchemy.Table('my_table', metadata, autoload_with=engine) </code></pre> <p>The question I have is how is it intended to be worked with?</p> <ul> <li>My previous code which just use SQL requires me to pass a <code>connection</code> object around the call stack. This is not too arduous.</li> </ul> <p>If I want to now work with the ORM functionality, I have to either:</p> <ul> <li>Create my table types using reflection at the start of the code, or</li> <li>Create them &quot;lazily&quot; - only when needed</li> </ul> <p>If I understand correctly the actual information about the reflected tables is stored in the <code>metadata</code> object, as well as being returned by the function call to <code>sqlalchemy.Table()</code>.</p> <p>If I choose the first option, and create all required tables at the beginning, I now need to pass these objects around my call stack just to have access to them when needed.</p> <p>There appear to be two choices to do this:</p> <ul> <li>create some new structure to hold the reflected table types (a dict would do fine)</li> <li>pass the <code>metadata</code> object around, which has a <code>tables</code> attribute, from which the table &quot;types&quot; can be obtained:</li> </ul> <pre><code>my_table_object = metadata.tables.get('my_table') </code></pre> <p>The second option appears to be more sensible - pass the <code>metadata</code> object around.</p> <p>This then leads to the previous question being somewhat redundant. Creating the tables lazily requires some additional code to check if the table type object has been created every time we want to use it, so we might as well just reflect all the required tables at the beginning.</p> <h3>Summary:</h3> <p>I have described above a possible way that the dynamic runtime reflection features of SQL Alchemy <em>could be used</em>. However it seems a bit strange to me for the following reasons:</p> <ul> <li>To interact with the database I need to pass around a <code>connection</code> object</li> <li>To use the ORM features, I now need to pass around a <code>metadata</code> object just to get access to the &quot;types&quot; (***)</li> <li>If I want to create another connection, or perform further reflection operations, I also need to pass around the <code>engine</code> object</li> <li>There doesn't seem to be a way to use the <code>connection</code> object to perform the reflection operations</li> <li>These points lead to writing code where at least 3 objects are being passed around at all levels of the call stack, in case they are needed somewhere</li> <li>I could of course wrap them in a tuple, or some more structured type. A more structured type leads to a lot of additional code which needs to be written, and likely a more rigid overall structure. This isn't obviously a good thing, especially in a language which is designed to be very flexible.</li> </ul> <p>(***) This point should be stressed further: I find this really weird. Usually types are &quot;globally&quot; accessable from anywhere in a Python code. If I want to construct a <code>MyClass</code> type, provided I have correctly imported <code>MyClass</code> from the source code where it is defined, I can just use it anywhere I like. I do not &quot;have to pull the <code>MyClass</code> thing out from some <code>metadata</code> object.</p> <p>It might be that this style of programming is just unfamilar to me and therefore it seems strange, and there is nothing wrong with this approach, and that it is indeed necessary to structure things this way.</p> <h5>Note:</h5> <p>Please note that I am aware there are an additional two ways to work with the SQL Alchemy ORM, both of which can be used to define tables at &quot;compile&quot; time (when the code is written - Python does not have a compiler). I suppose you might describe this as a &quot;static&quot; definition rather than a dynamic one using reflection at runtime.</p> <p><em>I do not want to do this. I want to leverage the &quot;code&quot; (metadata/structure) which is already inside my SQL database to define the table structure for me.</em></p> <p>This leads to less maintainance overhead because if the SQL Database structure changes, often no code changes are required, unless the logic needs to be changed. There is little point in using a dynamic language such as Python to then not leverage its dynamic features. (Although the reverse approach would make perfect sense if you were using Python code to drive the creation of a database.)</p>
<python><sqlalchemy>
2023-12-23 10:48:05
1
18,579
user2138149
77,707,308
896,112
Why do attributes that are being set by a custom type initializer need to be protected?
<p>The <a href="https://septatrix.github.io/cpython-dark-docs/extending/newtypes_tutorial.html#adding-data-and-methods-to-the-basic-example" rel="nofollow noreferrer">CPython Tutorial</a> defines a custom initializer for a custom type which has the following lines :</p> <pre class="lang-cpp prettyprint-override"><code>if (first) { tmp = self-&gt;first; Py_INCREF(first); self-&gt;first = first; Py_XDECREF(tmp); } </code></pre> <p>but the tutorial advises against this simpler but more nefarious version :</p> <pre class="lang-cpp prettyprint-override"><code>if (first) { Py_XDECREF(self-&gt;first); Py_INCREF(first); self-&gt;first = first; } </code></pre> <p>For the following reason :</p> <blockquote> <p>But this would be risky. Our type doesn’t restrict the type of the first member, so it could be any kind of object. It could have a destructor that causes code to be executed that tries to access the first member; or that destructor could release the Global interpreter Lock and let arbitrary code run in other threads that accesses and modifies our object.</p> </blockquote> <p>I understand the reason why a multithreaded programming can break the simple version. There can be a race condition where the <em>new</em> <code>self-&gt;first</code> is set by one thread and freed by another thread (by way of <code>Py_XDECREF</code>). This is avoided in the correct version because both threads will have had to set <code>self-&gt;first</code> <em>before</em> freeing it.</p> <p>The part I don't understand is this section :</p> <blockquote> <p>It could have a destructor that causes code to be executed that tries to access the first member</p> </blockquote> <p>If <code>first</code> is an object that is getting garbage collected, its destructor would have to be called and it should have access to itself through the duration of the destructor. Why can this be dangerous?</p> <p>Thank you!</p>
<python><cpython><python-c-api>
2023-12-23 10:20:35
1
9,259
Carpetfizz
77,707,014
5,591,958
How to efficiently find second-order neighbors in graph-tool?
<p>I'm using graph-tool and would like to find the second-order neighbors of a node (neighbors of neighbors who are not the node itself or the original neighbors). I thought it might be faster to use graph-tool's built-in topology functions, so I tried</p> <pre><code># Here g is the digraph, and node is the vertex whose neighbors we want d = gt.topology.shortest_distance(g,g.vertex(node),max_dist=2) f = gt.GraphView(g,vfilt=d.a == radius) second_neighbors = f.vertices() </code></pre> <p>However, this appears to be considerably slower than direct iteration, even on large graphs. How can I do this very quickly for large networks?</p>
<python><graph-theory><graph-tool>
2023-12-23 08:09:43
1
489
geofurb
77,706,826
3,050,341
Manim animate group and child at the same time
<p>I have two mobjects which are grouped into one <code>VGroup</code>. I want to animate some properties of group and, in the same time, animate children porperties:</p> <pre class="lang-py prettyprint-override"><code>from manim import * class Visualisation(Scene): def construct(self): circle1 = Circle(1, RED) circle2 = Circle(1, BLUE).shift(RIGHT) circles = VGroup(circle1, circle2) self.add(circles) self.play(circles.animate.scale(.85).shift(LEFT * 2), FadeOut(circle2)) self.wait(2) </code></pre> <p>The problem is that only child animation is playing for <code>circle2</code> (fading out), it is not scaling and moving like <code>circle1</code> does! But it should because it is a part of <code>circles</code> group.</p> <p>How to make <code>circle2</code> both play his own animation <strong>and</strong> respect parent group transformation? I am using Manim CE.</p>
<python><manim>
2023-12-23 06:33:52
0
3,111
CMTV
77,706,773
13,520,498
`AssertionError` while installing `deepface` via pip
<p>I'm trying to install <code>deepface</code> library via <code>pip</code> but it fails with <code>AssertionError</code>.</p> <p>My system specs are:</p> <ul> <li>OS : POP-OS 22.04</li> <li>Python: Python-3.10.12</li> <li>Pip: pip-22.0.2</li> </ul> <h4>update 01</h4> <p>I did the following with <code>pip</code>:</p> <pre><code>pip install deepface </code></pre> <p>Here's the full error message that I got:</p> <pre><code>ERROR: Exception: Traceback (most recent call last): File &quot;/usr/lib/python3/dist-packages/pip/_internal/cli/base_command.py&quot;, line 165, in exc_logging_wrapper status = run_func(*args) File &quot;/usr/lib/python3/dist-packages/pip/_internal/cli/req_command.py&quot;, line 205, in wrapper return func(self, options, args) File &quot;/usr/lib/python3/dist-packages/pip/_internal/commands/install.py&quot;, line 389, in run to_install = resolver.get_installation_order(requirement_set) File &quot;/usr/lib/python3/dist-packages/pip/_internal/resolution/resolvelib/resolver.py&quot;, line 188, in get_installation_order weights = get_topological_weights( File &quot;/usr/lib/python3/dist-packages/pip/_internal/resolution/resolvelib/resolver.py&quot;, line 276, in get_topological_weights assert len(weights) == expected_node_count AssertionError </code></pre> <h4>update 02</h4> <p>I also tried to build from the source by following these, and it also resulted in the same error! :</p> <pre><code>git clone https://github.com/serengil/deepface.git cd deepface pip install -e . </code></pre> <p>Links to the <code>deepface</code> library for your reference:</p> <ul> <li><a href="https://pypi.org/project/deepface/" rel="nofollow noreferrer">https://pypi.org/project/deepface/</a></li> <li><a href="https://github.com/serengil/deepface" rel="nofollow noreferrer">https://github.com/serengil/deepface</a></li> </ul> <p>Any help would be greatly appreciated!</p>
<python><python-3.x><pip><deepface>
2023-12-23 06:07:13
4
1,991
Musabbir Arrafi
77,706,694
10,633,596
How to modify my Python Slack Bolt Socket mode code to reload automatically during any code changes
<p>I have the following Python code which works fine using the Web Socket mode. When I type a slash command (<code>/hello-socket-mode</code>) on my Slash application then it very well invokes my method, <code>handle_some_command()</code>:-</p> <pre><code>import os from slack_bolt import App from slack_bolt.adapter.socket_mode import SocketModeHandler # Install the Slack app and get xoxb- token in advance app = App(token=&quot;&lt;bot token&gt;&quot;) # Add functionality here @app.command(&quot;/hello-socket-mode&quot;) def handle_some_command(ack, body, logger): ack() print('testing slash command') logger.info(body) if __name__ == &quot;__main__&quot;: # Create an app-level token with connections:write scope handler = SocketModeHandler(app,&quot;&lt;app token&gt;&quot;) handler.start() </code></pre> <p>Since I'm in the development phase of my Slack app, I want to add reload functionality to this backend code of the web socket such that it reloads automatically whenever there is a change in the code. I tried to add <code>uvicorn</code> here but with that, I stopped getting invocation to my backend method, <code>handle_some_command()</code>whenever I tried to enter the slash command in the my slack application. I created a separate Python script called run.py with following code:-</p> <pre><code>from uvicorn import run if __name__ == &quot;__main__&quot;: run(&quot;main:app&quot;, host=&quot;0.0.0.0&quot;, port=3000, reload=True, log_level=&quot;info&quot;) </code></pre> <p>And then executed, <code>python run.py</code> to run my app using <code>uvicorn</code> to reload whenever there is a code change. It is not working at all, I'm not getting any slash command invocation to my backend code now. I just need some way of reload and not necessarily <code>uvicorn</code> here. I would appreciate it if someone could please guide me on this to make it work.</p>
<python><uvicorn><slack-bolt>
2023-12-23 05:17:29
1
1,574
vinod827
77,706,666
8,554,833
Python Selenium JavaScript Horizontal Scroll
<p>I'm not very good at using pyhton/selenium on a website using javascript.</p> <p>I have a website that will only read the source for what is visible. So I am trying to scroll to the right a handful of pixels at a time to get the whole table eventually.</p> <p>The scroll element looks like this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="ag-body-horizontal-scroll" aria-hidden="true" style="height: 17px; max-height: 17px; min-height: 17px;"&gt; &lt;div class="ag-horizontal-left-spacer ag-scroller-corner" ref="eLeftSpacer" style="width: 0px; max-width: 0px; min-width: 0px;"&gt;&lt;/div&gt; &lt;div class="ag-body-horizontal-scroll-viewport" ref="eViewport" style="height: 17px; max-height: 17px; min-height: 17px;"&gt; &lt;div class="ag-body-horizontal-scroll-container" ref="eContainer" style="height: 17px; max-height: 17px; min-height: 17px; width: 7400px;"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="ag-horizontal-right-spacer ag-scroller-corner" ref="eRightSpacer" style="width: 17px; max-width: 17px; min-width: 17px;"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Would love some help on getting this to work.</p>
<javascript><python><selenium-webdriver>
2023-12-23 04:54:29
0
728
David 54321
77,706,615
9,586,195
How to initialize env variable in current process with bash script when importing python package
<p>I have a custom python package which wraps some C code in library files (.so/.a). This C code depends on some env variables and I cannot change the C code.</p> <p>To initialize them, I have a bash script like so:</p> <pre class="lang-bash prettyprint-override"><code>PACKAGE_PATH=/path/to/package export PYTHONPATH=$PYTHONPATH:$PACKAGE_PATH/lib export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$PACKAGE_PATH/lib etc. </code></pre> <p>The package structure looks like this:</p> <pre><code>my_py_package ├── __init__.py ├── env.sh ├── lib | └── libC.so └── other_file.py </code></pre> <p>I would like to be able to automatically <strong>source</strong> the <code>env.sh</code> script in current process when importing my package in a script or console:</p> <pre class="lang-py prettyprint-override"><code># Loads env.sh in current process import my_py_package </code></pre> <p>I tried to update my environment with <code>os.environ</code> in <code>__init__.py</code> but it updates env for child processes not current process</p> <p>I also tried to emulate <code>source</code> following this <a href="https://stackoverflow.com/questions/3503719/emulating-bash-source-in-python">Emulating Bash &#39;source&#39; in Python</a> but the <code>os.execve</code> makes me lose the current process</p> <p>It is possible to achieve this ?</p>
<python><bash>
2023-12-23 04:12:44
0
408
Sunchock
77,706,557
14,055,985
Can `cmake` ignore `cmake_minimum_required` (or can `conan` leave my changes alone?)
<p>I am trying to build <a href="https://github.com/Ultimaker/Cura/wiki/Running-Cura-from-Source" rel="nofollow noreferrer">Cura</a> using <code>conan</code> and a dependency fails to build because my version of <code>cmake</code> is 3.20, but it wants 3.23. I can manually change it to 3.20 and it builds just fine, but <code>conan</code> keeps resetting <code>CMakeLists.txt</code> to its pre-modified state when I run this to build Cura:</p> <pre class="lang-bash prettyprint-override"><code>## Build it # conan install . --build=missing --update -o cura:devtools=True -g VirtualPythonEnv ... CMake Error at CMakeLists.txt:3 (cmake_minimum_required): CMake 3.23 or higher is required. You are running version 3.20.2 ... ConanException: Error 1 while executing cmake -G &quot;Ninja&quot; -DCMAKE_TOOLCHAIN_FILE=&quot;/home/ewheeler/.conan/data/arcus/5.3.0/_/_/build/7bb59b7dbf92ac7a06f25b01418f550161106450/build/Release/generators/conan_toolchain.cmake&quot; -DCMAKE_INSTALL_PREFIX=&quot;/home/ewheeler/.conan/data/arcus/5.3.0/_/_/package/7bb59b7dbf92ac7a06f25b01418f550161106450&quot; -DCMAKE_POLICY_DEFAULT_CMP0077=&quot;NEW&quot; -DCMAKE_POLICY_DEFAULT_CMP0091=&quot;NEW&quot; -DCMAKE_BUILD_TYPE=&quot;Release&quot; &quot;/home/ewheeler/.conan/data/arcus/5.3.0/_/_/build/7bb59b7dbf92ac7a06f25b01418f550161106450/.&quot; ## Fix it # vim /home/ewheeler/.conan/data/arcus/5.3.0/_/_/build/7bb59b7dbf92ac7a06f25b01418f550161106450/CMakeLists.txt &lt;fix it by changing 3.23 to 3.20 in CMakeLists.txt&gt; ## Re-run the command that failed: # cmake -G &quot;Ninja&quot; -DCMAKE_TOOLCHAIN_FILE=&quot;/home/ewheeler/.conan/data/arcus/5.3.0/_/_/build/7bb59b7dbf92ac7a06f25b01418f550161106450/build/Release/generators/conan_toolchain.cmake&quot; -DCMAKE_INSTALL_PREFIX=&quot;/home/ewheeler/.conan/data/arcus/5.3.0/_/_/package/7bb59b7dbf92ac7a06f25b01418f550161106450&quot; -DCMAKE_POLICY_DEFAULT_CMP0077=&quot;NEW&quot; -DCMAKE_POLICY_DEFAULT_CMP0091=&quot;NEW&quot; -DCMAKE_BUILD_TYPE=&quot;Release&quot; &quot;/home/ewheeler/.conan/data/arcus/5.3.0/_/_/build/7bb59b7dbf92ac7a06f25b01418f550161106450/.&quot; &lt;cmake succeeds&gt; ## re-run `conan install`, but the problem ## repeats because conan resets the build environment. </code></pre> <p>Question: How do can I get this to build?</p> <p><a href="https://xyproblem.info/" rel="nofollow noreferrer">xyproblem</a> questions that would solve it:</p> <ol> <li>Can <code>cmake</code> ignore <code>cmake_minimum_required</code> via environment variable?</li> <li>Can conan leave my changes alone, or pick up where it left off without reset? <ul> <li>I already tried <code>chattr +i</code> but it blows up during cleanup</li> </ul> </li> <li>Other fixes?</li> </ol> <p>This is my first experience with <code>conan</code>, so any help would be appreciated.</p> <p><s>nb, I would rather not install a newer version of cmake...</s> <em>(I rebuilt cmake 3.24 and <code>conan</code> is continuing, but I'll leave SE question here in case someone has an answer for the next person.)</em></p>
<python><c++><cmake><conan><ninja>
2023-12-23 03:36:52
1
1,981
KJ7LNW
77,706,529
23,002,898
In Django i can't display a form in index, from another page. I only see the button, but i don't see the textboxes
<p>I would like to view the registration form directly on the index<code>.html</code> page (home page). In index.html, i would like to display <code>register.html</code>.</p> <p>The registration form was created in registration/register.html. I call it in index.html using:</p> <pre><code>{% block content %} {% include 'registration/register.html' %} {%endblock%} </code></pre> <p>In the <code>urlpatterns</code> of <code>App1/views.py</code>, i use:</p> <pre><code>path(&quot;register_request&quot;, views.register_request, name='register_request') </code></pre> <p>The problem is that on the index.html i see the form button, but not its textboxes (username, email, password).</p> <p><a href="https://i.sstatic.net/VUDv2.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/VUDv2.png" alt="enter image description here" /></a></p> <p>I can't understand where I'm wrong. Can you tell me what i'm doing wrong and can you show me code how to fix it?</p> <p>This is <code>App1</code>:</p> <pre><code>App1 .migrations .static .templates ..index.html ..registration ...register.html </code></pre> <p><strong>index.html</strong></p> <pre><code>{% load static %} &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;University&lt;/title&gt; &lt;!-- Bootstrap CSS --&gt; &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;link href=&quot;https://getbootstrap.com/docs/5.3/assets/css/docs.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;link href=&quot;/static/css/style.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;/head&gt; &lt;body&gt; ....... ....... {% block content %} {% include 'registration/register.html' %} {%endblock%} &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>App1/templates/registration/register.html</strong></p> <pre><code>&lt;!--Register--&gt; &lt;div class=&quot;container py-5&quot;&gt; &lt;h1&gt;Register&lt;/h1&gt; &lt;form method=&quot;POST&quot;&gt; {% csrf_token %} {{ register_form.as_p }} &lt;button class=&quot;btn btn-primary&quot; type=&quot;submit&quot;&gt;Register&lt;/button&gt; &lt;/form&gt; &lt;p class=&quot;text-center&quot;&gt;If you already have an account, &lt;a href=&quot;/login&quot;&gt;login&lt;/a&gt; instead.&lt;/p&gt; &lt;/div&gt; </code></pre> <p><strong>App1/forms.py</strong></p> <pre><code>from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User # Create your forms here. class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = (&quot;username&quot;, &quot;email&quot;, &quot;password1&quot;, &quot;password2&quot;) def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user </code></pre> <p><strong>App1/urls.py</strong></p> <pre><code>from django.urls import path from . import views urlpatterns=[ path('', views.index, name='index'), path(&quot;register_request&quot;, views.register_request, name='register_request'), ] </code></pre> <p><strong>App1/views.py</strong></p> <pre><code>from .forms import NewUserForm from django.contrib import messages from django.contrib.auth.decorators import login_required def index(request): &quot;&quot;&quot;View function for home page of site.&quot;&quot;&quot; return render(request, 'index.html') def register_request(request): if request.method == &quot;POST&quot;: form = NewUserForm(request.POST) if form.is_valid(): user = form.save() login(request, user) messages.success(request, &quot;Registration successful.&quot; ) return redirect(&quot;index.html&quot;) messages.error(request, &quot;Unsuccessful registration. Invalid information.&quot;) form = NewUserForm() return render (request=request, template_name=&quot;registration/register.html&quot;, context={&quot;register_form&quot;:form}) #NO: return render(request, &quot;registration/register.html&quot;,{&quot;register_form&quot;:form}) </code></pre> <p><strong>MYSITE (PROJECT)</strong></p> <p><strong>mysite/urls.py</strong></p> <pre><code>from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from django.contrib.auth.views import LoginView urlpatterns = [ path('admin/', admin.site.urls), path('', include('App1.urls')), </code></pre> <p><strong>mysite/setting.py</strong></p> <pre><code>TEMPLATES = [ { .... #NO: &quot;DIRS&quot; : [ BASE_DIR / &quot;templates&quot; ], 'DIRS': [&quot;templates&quot;], [ STATIC_DIR = os.path.join(BASE_DIR,&quot;static&quot;) STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR,] </code></pre> <p>In <code>models.py</code> i didn't write anything.</p>
<python><python-3.x><django><django-forms>
2023-12-23 03:21:59
2
307
Nodigap
77,706,103
22,285,820
Replacing google slides images using slides api
<p>I have the following scripts to update the images in google slides, it works fine but sometimes it gives me 400 error, service account has a write permission to the drive/images and the presentation</p> <pre><code>image_mappings = { &quot;id_in_presenation&quot;: &quot;name_of_the_image&quot;, &quot;id_in_presenation1&quot;: &quot;name_of_the_image1&quot;, } # listing .png files def get_png_files(drive_folder_id, drive_service): query = f&quot;'{drive_folder_id}' in parents and mimeType='image/png'&quot; results = drive_service.files().list(q=query, supportsAllDrives=True, fields=&quot;files(id, name, webViewLink, webContentLink)&quot;).execute() drive_png_files = results.get('files', []) print('drive_png_files', drive_png_files) return drive_png_files` # updating images in slides def update_images_in_slides(drive_png_files, slides_service, presentation_id): &quot;&quot;&quot; Updates images in a Google Slides presentation. Args: drive_png_files: A list of .png files from Google Drive. slides_service: The authenticated Google Slides service object. presentation_id: The ID of the presentation to update. &quot;&quot;&quot; requests = [] for slide_image_id, new_image_name in info.image_mappings.items(): drive_file = next((item for item in drive_png_files if item['name'] == new_image_name), None) if drive_file: requests.append({ 'replaceImage': { 'imageObjectId': slide_image_id, 'imageReplaceMethod': 'CENTER_INSIDE', 'url': f'https://drive.google.com/uc?id={drive_file[&quot;id&quot;]}' } }) if requests: body = {'requests': requests} try: response = slides_service.presentations().batchUpdate(presentationId=presentation_id, body=body).execute() time.sleep(10) print(f&quot;\nUpdated the slide: {response}&quot;) except Exception as exc: raise ValueError(f&quot;Failed to update the presentation.&quot;) from exc </code></pre> <p>gave editor and writer access permission to the service account for the drives, images, presentation did not help</p>
<python><service-accounts><presentation><google-slides-api><google-slides>
2023-12-22 22:43:38
1
596
nisakova
77,706,064
13,264,143
How do you get all the classes in another package so they can be instantiated in Python3?
<p>I read the question <a href="https://stackoverflow.com/questions/54699587/importing-a-whole-folder-of-python-files">&quot;Importing a whole folder of python files&quot;</a>, but it does not include a way to do it without one import per file.</p> <p>Beside the requirement of avoiding several imports, it is required that the number of classes have nothing to do with the amount of code written. I also want to avoid &quot;from source import *&quot; from being in the code, but am not against it.</p> <p>I have tried this.</p> <pre><code>from system.models import * </code></pre> <p>but that results in</p> <blockquote> <pre><code>model = globals()[class_name](labels.size()[:-1], labels.size()[-1]) </code></pre> <p>TypeError: 'module' object is not callable</p> </blockquote> <p>I have also tried this</p> <pre><code>import sys sys.path.insert(0, r'../system/models') </code></pre> <p>but that results in the globals not containing the classes.</p> <p>The ultimate goal is, given a folder designated as a python package, to get all the classes in the python files contained in that package.</p>
<python><python-3.x><module><python-import><global>
2023-12-22 22:31:14
1
966
John Glen
77,706,005
5,633,063
How can I more efficiently use the Python REPL for package development?
<h2>My current workflow</h2> <ol> <li>I install my package in <a href="https://setuptools.pypa.io/en/latest/userguide/development_mode.html" rel="nofollow noreferrer">editable mode</a> (usually in a virtual environment): <pre class="lang-bash prettyprint-override"><code>&gt; python -m pip install -e . </code></pre> </li> <li>I write some code in <code>pkgfoo/pkgfoo/bar.py</code>: <pre><code># Example directory structure pkgfoo/ ├── dev/ │ └── dev.py ├── pkgfoo/ │ ├── __init__.py │ └── bar.py ├── pyproject.toml └── setup.py </code></pre> </li> <li>I spin up the python REPL and start running some testing code to see if my package is working. Usually this code lives in a folder like <code>dev</code>, often getting turned into unit tests later on: <pre class="lang-bash prettyprint-override"><code>&gt; python </code></pre> <pre class="lang-py prettyprint-override"><code># pkgfoo/dev/dev.py import pkgfoo as pf # Does this work? pf.bar.baz() </code></pre> </li> <li>Once I'm done testing, I quit python using <code>quit()</code>, then repeat the process starting at step (2).</li> </ol> <h2>Issues I'm having</h2> <ul> <li><p>Rerunning <code>&gt;&gt;&gt; quit()</code>, <code>&gt; python</code>, <code>&gt;&gt;&gt; import pkgfoo as pf</code> every time I want to test my code gets tedious, and isn't good for my hands.</p> </li> <li><p>Each cycle, any python objects I've been working with in the previous cycle are lost, so the code I'm able to use for adhoc testing has to be be very short and quick to run so as not to encumber my workflow.</p> </li> </ul> <p><strong>I'm interested in any answers which solve these issues.</strong> I'm not wedded to VSCode, but I'd prefer to keep using it as my editor if possible.</p> <h2>What I've tried</h2> <ul> <li><p>Instead of restarting python, I've tried reloading my package using <code>importlib</code>:</p> <pre class="lang-py prettyprint-override"><code># pkgfoo/dev/dev.py import pkgfoo from importlib import reload reload(pkgfoo) # Does this work? pf.bar.baz() </code></pre> <p>Unfortunately, this doesn't seem to make available any changes I've made to the package code since I last restarted the REPL.</p> </li> <li><p>I've looked at creating a keyboard shortcut to restart python and import my package, but I have no idea how I'd set this up so that:</p> <ul> <li>It works for any project with a package structure, not just <code>pkgfoo</code></li> <li>It first runs <code>quit()</code> if the python REPL is already running</li> </ul> </li> </ul>
<python><visual-studio-code><python-packaging>
2023-12-22 22:10:32
0
2,818
wurli
77,705,916
2,179,222
Reset prometheus metric if it was not reported for period of time in python
<p>I have a python app with Gauge metric where I report latest value reported by some device. I want to create a mechanism that will reset the value to zero if the metric was not reported for more than 30 min. Is there a way to do it without keeping the map of last report times? Is there a way to get the last report time from the metric object itself?</p>
<python><prometheus><prometheus-python-client>
2023-12-22 21:37:57
1
349
Eduard Grinberg
77,705,875
2,755,307
Trying to get a Gaussian GLM to simply match OLS but is either very wrong or has perfect separation
<p>I'm trying to make a GLM do what an OLS does, just to get a baseline understanding of GLM. But it doesn't seem to do what I'm after. Consider this code:</p> <pre><code>import numpy as np import statsmodels.api as sm from scipy import stats print(&quot;### This is dummy data that clearly is y = 0.25 * x + 5: #############&quot;) aInput = np.arange(10) print(aInput) aLinear = aInput.copy() * 0.25 + 5 print(aLinear) print(&quot;### This is OLS to show clearly what we're after: ####################&quot;) aInputConst = sm.add_constant(aInput) model = sm.OLS(aLinear, aInputConst) results = model.fit() print(results.params) print(&quot;This is GLM which looks nothing like what I expect: ##################&quot;) model = sm.GLM(aLinear, aInput, family=sm.families.Gaussian()) result = model.fit() y_hat = result.predict(aInput) print(y_hat) print(&quot;This is GLM with the constant, but it just fails: ####################&quot;) # vvvvvvvvvvv model = sm.GLM(aLinear, aInputConst, family=sm.families.Gaussian()) result = model.fit() y_hat = result.predict(aInput) print(y_hat) </code></pre> <p>Now consider the output:</p> <pre><code>### This is dummy data that clearly is y = 0.25 * x + 5: ############# [0 1 2 3 4 5 6 7 8 9] [5. 5.25 5.5 5.75 6. 6.25 6.5 6.75 7. 7.25] ### This is OLS to show clearly what we're after: #################### [5. 0.25] This is GLM which looks nothing like what I expect: ################## [0. 1.03947368 2.07894737 3.11842105 4.15789474 5.19736842 6.23684211 7.27631579 8.31578947 9.35526316] This is GLM with the constant, but it just fails: #################### Traceback (most recent call last): File &quot;min.py&quot;, line 26, in &lt;module&gt; result = model.fit() File &quot;/export/home/jm43436e/.local/lib/python3.6/site-packages/statsmodels/genmod/generalized_linear_model.py&quot;, line 1065, in fit cov_kwds=cov_kwds, use_t=use_t, **kwargs) File &quot;/export/home/jm43436e/.local/lib/python3.6/site-packages/statsmodels/genmod/generalized_linear_model.py&quot;, line 1211, in _fit_irls raise PerfectSeparationError(msg) statsmodels.tools.sm_exceptions.PerfectSeparationError: Perfect separation detected, results not available </code></pre> <p>Observe:</p> <ul> <li>The data is contrived to be y = 0.25 x + 5 so that we know the &quot;right&quot; answer when we see it.</li> <li>The OLS finds this naturally. It finds the 5 and it finds the 0.25. Easy enough.</li> <li>But the first attempt with the GLM just goes from roughly 0 to 10, when I would expect it to go from about 5 to about 7.25 which is what the original outputs are. Why didn't it? Now, one thing I've read is you need to add the constant, which leads to the next issue:</li> <li>When I add the constant, it get the &quot;perfect separation&quot; error. If I'm supposed to add that constant, how can I add it without getting the error?</li> </ul> <p>My question is:</p> <ul> <li>How can I just get the GLM to behave like an OLS and tell me 5 and 0.25. I'm just trying to get this as a starting baseline but can't. That would either be by getting the first GLM call to have b1 and b0, as well as the right range of output; or by adding the constant if I'm supposed to, then providing b1 and b0.</li> </ul> <p>I'm clearly confused. All help appreciated!</p>
<python><statsmodels><glm>
2023-12-22 21:23:36
1
953
James Madison
77,705,849
1,228,906
ModuleNotFoundError when trainng on a custom Azure environment
<p>I have a tensorflow script that works perfectly when trained on ACR image: AzureML-tensorflow-2.7-ubuntu20.04-py38-cuda11-gpu (mcr.microsoft.com/azureml/curated/tensorflow-2.7-ubuntu20.04-py38-cuda11-gpu:28)</p> <p>I need to include a few additional dependencies so I'm creating a custom environment (conda.yml and code included below). The environment image is build successfully, but when I execute the training job, it complains that tensorflow is not found.</p> <p>In my conda.yml, I've commented out the packages that are already included in tensorflow-2.7-ubuntu20.04-py38-cuda11-gpu. If I do not comment them, then the image creation fails.</p> <p>conda.yml:</p> <pre><code>name: keras-env channels: - conda-forge dependencies: - python=3.8 - pip=20.2.4 - pip: #- protobuf~=3.20 #- numpy~=1.21.0 #- tensorflow-gpu~=2.7.0 #- matplotlib~=3.5.0 #- azureml-mlflow==1.51.0 #- horovod[tensorflow-gpu]~=0.23.0 - azureml.core - keras - mlflow - pyarrow - idx2numpy - scikit-learn </code></pre> <p>Code for environment build:</p> <pre><code>import os from azure.ai.ml.entities import Environment custom_env_name = &quot;stb-dist-keras-env&quot; dependencies_dir = &quot;./&quot; from azure.ai.ml import MLClient from azure.identity import DefaultAzureCredential ml_client = MLClient( DefaultAzureCredential(), 'a', 'ab', 'abc' ) job_env = Environment( name=custom_env_name, description=&quot;Custom environment distributed environment&quot;, conda_file=os.path.join(dependencies_dir, &quot;conda.yml&quot;), image=&quot;mcr.microsoft.com/azureml/curated/tensorflow-2.7-ubuntu20.04-py38-cuda11-gpu:28&quot; ) job_env = ml_client.environments.create_or_update(job_env) print( f&quot;Environment with name {job_env.name} is registered to workspace, the environment version is {job_env.version}&quot; ) </code></pre> <p>This is the error reported in the std_log</p> <blockquote> <p>Traceback (most recent call last): File &quot;train.py&quot;, line 18, in import tensorflow as tf ModuleNotFoundError: No module named 'tensorflow'</p> </blockquote> <p>Update 1: Including additional data.</p> <p>This is my <a href="https://github.com/horovod/horovod/blob/master/examples/tensorflow2_keras_mnist.py" rel="nofollow noreferrer">train.py</a>. I'm using the same train.py between the two runs.</p> <p>Custom environment succeeded: <a href="https://i.sstatic.net/qsMfH.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/qsMfH.png" alt="Custom environment" /></a></p> <p>Succeeded on MCR environment: <a href="https://i.sstatic.net/YdveR.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/YdveR.png" alt="succeeded on mcr image" /></a></p> <p>Failed on custom environment: <a href="https://i.sstatic.net/XYIpg.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/XYIpg.png" alt="enter image description here" /></a></p> <p>Code to kick off the job:</p> <pre><code>from azure.ai.ml import command, MpiDistribution job = command( code=&quot;./&quot;, # local path where the code is stored command=&quot;python train.py --epochs ${{inputs.epochs}}&quot;, inputs={&quot;epochs&quot;: 1}, #environment=&quot;AzureML-tensorflow-2.7-ubuntu20.04-py38-cuda11-gpu@latest&quot;, environment=&quot;stb-dist-keras-env@latest&quot;, compute=&quot;&quot;, instance_count=1, distribution=MpiDistribution(process_count_per_instance=1), display_name=&quot;tensorflow-mnist-distributed-horovod-example&quot; # experiment_name: tensorflow-mnist-distributed-horovod-example # description: Train a basic neural network with TensorFlow on the MNIST dataset, distributed via Horovod. ) </code></pre>
<python><azure><tensorflow><azure-machine-learning-service><azure-container-registry>
2023-12-22 21:15:59
1
1,896
webber
77,705,565
15,019,223
Slice array along axis with list of different indices
<p>I have a 3-dimensional array/tensor of shape <code>(a, b, c)</code>, and I have a list of length <code>a</code> of different indices, each in the range <code>[0, b)</code>. I want to use the indices to get an array of size <code>(a, c)</code>. Right now I do this with an ugly list comprehension</p> <pre class="lang-py prettyprint-override"><code>z = torch.stack([t_[b, :] for t_, b in zip(tensor, B)]) </code></pre> <p>This is implemented in a forward pass for a neural network, so I really want to avoid a list comprehension. Is there any torch (or numpy) function that does what I want more efficient?</p> <p>Also a small example:</p> <pre><code>tensor = [[[ 0, 1], [ 2, 3], [ 4, 5]], [[ 6, 7], [ 8, 9], [10, 11]], [[12, 13], [14, 15], [16, 17]], [[18, 19], [20, 21], [22, 23]]] # shape: (4, 3, 2) B = [0, 1, 2, 2] output = [[ 0, 1], [ 8, 9], [16, 17], [22, 23]] # shape (4, 2) </code></pre> <p>Background: I have time series data which has time windows of different lengths. I use torch's <code>pack_padded_sequence</code> (and reverse) to mask it, but I have to get the output of the <code>LSTM</code> at the time step before the masking starts, because then the output of the network gets unusable. In the example, I would have 4 time steps with length <code>0, 1, 2, 2</code> each with 2 features.</p>
<python><numpy><pytorch><numpy-slicing>
2023-12-22 19:49:22
1
1,953
mhenning
77,705,521
5,335,180
Why is pdb showing Blank line or comment, but there is a line?
<p>I'm trying to interactively run pdb on a remote system I don't own (I'm not sure if that's relevant), and it's behaving a bit differently than I expect. Listing the source shows there is clearly a line 22, but when I try to set the breakpoint, it tells me the line is blank. Fiddling a bit, I can get it to break on line 23, which is the line AFTER the one I want to break on. See terminal output below. I'm sure it's something dumb, but I'm at a loss.</p> <p>EDIT: I just noticed something new.... I'm using conda, and if I use the base environment, I don't see this issue, but if I use an environment I created, it does.</p> <pre><code>(ecg) [tmhedr3@hmrihpcp03 ecg_analysis]$ python -m pdb rnn.py &gt; /home/tmhedr3/ecg_analysis/rnn.py(1)&lt;module&gt;() -&gt; import os (Pdb) ll 0 import os 1 -&gt; import glob 2 import numpy as np 3 import pandas as pd 4 # import tensorflow as tf 5 # import keras 6 # from keras import layers 7 8 ages = open('ages.csv', 'r') 9 lines = ages.readlines() 10 n = len(lines) 11 12 data = np.ndarray((n, 5000, 12)) 13 14 for i in range(n): 15 li = lines[i].strip().split(sep=',') 16 name = li[0] 17 age = li[1] 18 19 leadData = np.loadtxt('./data/csv/' + name, skiprows=1, delimiter=',', usecols=(0,1,2,3,4,5,6,7,8,9,10,11), dtype='int') 20 data[i] = leadData 21 22 print(data.shape) 23 (Pdb) b 22 *** Blank or comment (Pdb) b 23 Breakpoint 1 at /home/tmhedr3/ecg_analysis/rnn.py:23 (Pdb) c &gt; /home/tmhedr3/ecg_analysis/rnn.py(23)&lt;module&gt;() -&gt; print(data.shape) (Pdb) </code></pre>
<python><pdb>
2023-12-22 19:35:49
1
489
reas0n
77,705,520
6,432,861
Python argparse: accessing the same ArgumentParser/argument in multiple files
<p>I have a script, <code>main.py</code>, that sets up an <code>argumentParser()</code> object to read in <code>commandline</code> arguments before calling a <code>main()</code> file that lives in another module, <code>alation_cronjob.py</code>.</p> <p>in <strong>main.py</strong>. I actually made <code>make_parser()</code> based on other suggestions, originally there was only <code>configure_and_run()</code>. So not as much thought has been put towards how this file is currently organized. I have also omitted multiple other arguments from this code snippet that aren't really relevant.</p> <pre><code>from mypkg.alation_cronjob import main def make_parser(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument( &quot;-v&quot;, &quot;--verbose&quot;, help=&quot;Increase verbosity of output&quot;, action=&quot;store_true&quot; ) parser.add_argument( &quot;--alation-instance&quot;, type=str, choices=[&quot;prod&quot;, &quot;dev&quot;], required=True, ) args = parser.parse_args() return args def configure_and_run(): logging.basicConfig(level=logging.INFO) args = make_parser() if args.verbose: logging.getLogger().setLevel(logging.DEBUG) logging.debug(&quot;Verbose output enabled.&quot;) main( alation_instance=args.alation_instance, consul_url=args.consul_url, ) if __name__ == &quot;__main__&quot;: configure_and_run() </code></pre> <p>in <strong>alation_cronjob.py</strong> where main() lives, at the top of the file is the import of another script called alation.py.</p> <pre><code>from mypkg.alation import delete_article, find_article_by_title, update_existing_article </code></pre> <p>Meanwhile, in <strong>alation.py</strong></p> <pre><code>from utils.get_refresh_token import get_refresh_token from utils.get_access_token import get_access_token access_token = get_access_token(get_refresh_token()) </code></pre> <p>So the problem is that. I need to access <code>args.alation_instance</code> in <code>utils.get_refresh_token().</code> I know that one workaround is to use sys.argv, though I'd have to add some extra code to make sure I select the alation_instance argument specifically. I also know i can add an ArgumentParser() to utils.create_refresh_token.py, but I would also have to add in all the other arguments provided in main.py including ones I don't intend to use in utils.create_refresh_token. The onlly argument I want is args.alation_instance.</p> <p>Is there an easy way to achieve that? I expect that I'll have to refactor this code, I'm just looking for the cleanest way to do this.</p>
<python><python-3.x><argparse>
2023-12-22 19:35:43
0
607
Byron Smith
77,705,471
2,414,957
cannot import name 'CppEGLRenderer' from 'lib.egl_renderer'
<p>I connect to destination machine (ada) like this:</p> <pre><code>connect to globalprotect vpn ssh -X machine 1 (machine 1) : ssh -X ada </code></pre> <p>my own machine is Ubuntu and the other two I ssh to also same version of Ubuntu. How can I fix this error?</p> <pre><code>(gdrnpp) mona@ada:~/gdrnpp_bop2022$ ./core/gdrn_modeling/train_gdrn.sh configs/gdrn/ycbv/convnext_a6_AugCosyAAEGray_BG05_mlL1_DMask_amodalClipBox_classAware_ycbv.py 0 ++ dirname ./core/gdrn_modeling/train_gdrn.sh + this_dir=./core/gdrn_modeling + CFG=configs/gdrn/ycbv/convnext_a6_AugCosyAAEGray_BG05_mlL1_DMask_amodalClipBox_classAware_ycbv.py + CUDA_VISIBLE_DEVICES=0 + IFS=, + read -ra GPUS + NGPU=1 + echo 'use gpu ids: 0 num gpus: 1' use gpu ids: 0 num gpus: 1 + NCCL_DEBUG=INFO + OMP_NUM_THREADS=1 + MKL_NUM_THREADS=1 + PYTHONPATH=./core/gdrn_modeling/../..:/home/mona/realsense-ros/install/realsense2_camera_msgs/local/lib/python3.10/dist-packages:/opt/ros/humble/lib/python3.10/site-packages:/opt/ros/humble/local/lib/python3.10/dist-packages + CUDA_VISIBLE_DEVICES=0 + python ./core/gdrn_modeling/main_gdrn.py --config-file configs/gdrn/ycbv/convnext_a6_AugCosyAAEGray_BG05_mlL1_DMask_amodalClipBox_classAware_ycbv.py --num-gpus 1 /home/mona/.local/lib/python3.10/site-packages/mmcv/__init__.py:20: UserWarning: On January 1, 2023, MMCV will release v2.0.0, in which it will remove components related to the training process and add a data transformation module. In addition, it will rename the package names mmcv to mmcv-lite and mmcv-full to mmcv. See https://github.com/open-mmlab/mmcv/blob/master/docs/en/compatibility.md for more details. warnings.warn( You requested to import horovod which is missing or not supported for your OS. /home/mona/.local/lib/python3.10/site-packages/mmcv/device/npu/data_parallel.py:22: UserWarning: Torchaudio's I/O functions now support par-call bakcend dispatch. Importing backend implementation directly is no longer guaranteed to work. Please use `backend` keyword with load/save/info function, instead of calling the udnerlying implementation directly. if hasattr(sys.modules[m], '_check_balance'): /home/mona/gdrnpp_bop2022/core/gdrn_modeling/../../lib/pysixd/misc.py:586: NumbaDeprecationWarning: The 'nopython' keyword argument was not supplied to the 'numba.jit' decorator. The implicit default value for this argument is currently False, but it will be changed to True in Numba 0.59.0. See https://numba.readthedocs.io/en/stable/reference/deprecation.html#deprecation-of-object-mode-fall-back-behaviour-when-using-jit for details. def get_obj_im_c(K, t): /home/mona/gdrnpp_bop2022/core/gdrn_modeling/../../lib/pysixd/misc.py:765: NumbaDeprecationWarning: The 'nopython' keyword argument was not supplied to the 'numba.jit' decorator. The implicit default value for this argument is currently False, but it will be changed to True in Numba 0.59.0. See https://numba.readthedocs.io/en/stable/reference/deprecation.html#deprecation-of-object-mode-fall-back-behaviour-when-using-jit for details. def compute_2d_bbox_xyxy_from_pose(points, pose, K, width=640, height=480, clip=False): /home/mona/gdrnpp_bop2022/core/gdrn_modeling/../../lib/pysixd/misc.py:793: NumbaDeprecationWarning: The 'nopython' keyword argument was not supplied to the 'numba.jit' decorator. The implicit default value for this argument is currently False, but it will be changed to True in Numba 0.59.0. See https://numba.readthedocs.io/en/stable/reference/deprecation.html#deprecation-of-object-mode-fall-back-behaviour-when-using-jit for details. def compute_2d_bbox_xyxy_from_pose_v2(points, pose, K, width=640, height=480, clip=False): /home/mona/gdrnpp_bop2022/core/gdrn_modeling/../../lib/pysixd/misc.py:822: NumbaDeprecationWarning: The 'nopython' keyword argument was not supplied to the 'numba.jit' decorator. The implicit default value for this argument is currently False, but it will be changed to True in Numba 0.59.0. See https://numba.readthedocs.io/en/stable/reference/deprecation.html#deprecation-of-object-mode-fall-back-behaviour-when-using-jit for details. def compute_2d_bbox_xywh_from_pose(points, pose, K, width=640, height=480, clip=False): Traceback (most recent call last): File &quot;/home/mona/gdrnpp_bop2022/./core/gdrn_modeling/main_gdrn.py&quot;, line 39, in &lt;module&gt; from core.gdrn_modeling.engine.engine_utils import get_renderer File &quot;/home/mona/gdrnpp_bop2022/core/gdrn_modeling/../../core/gdrn_modeling/engine/engine_utils.py&quot;, line 7, in &lt;module&gt; from lib.egl_renderer.egl_renderer_v3 import EGLRenderer File &quot;/home/mona/gdrnpp_bop2022/core/gdrn_modeling/../../lib/egl_renderer/egl_renderer_v3.py&quot;, line 27, in &lt;module&gt; from . import CppEGLRenderer ImportError: cannot import name 'CppEGLRenderer' from 'lib.egl_renderer' (/home/mona/gdrnpp_bop2022/core/gdrn_modeling/../../lib/egl_renderer/__init__.py) </code></pre> <p>I have:</p> <pre><code> (base) mona@ada:~$ uname -a Linux ada 6.2.0-37-generic #38~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Thu Nov 2 18:01:13 UTC 2 x86_64 x86_64 x86_64 GNU/Linux (base) mona@ada:~$ lsb_release -a LSB Version: core-11.1.0ubuntu4-noarch:security-11.1.0ubuntu4-noarch Distributor ID: Ubuntu Description: Ubuntu 22.04.3 LTS Release: 22.04 Codename: jammy (base) mona@ada:~$ nvidia-smi Fri Dec 22 14:24:54 2023 +---------------------------------------------------------------------------------------+ | NVIDIA-SMI 535.104.12 Driver Version: 535.104.12 CUDA Version: 12.2 | |-----------------------------------------+----------------------+----------------------+ | GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. | | | | MIG M. | |=========================================+======================+======================| | 0 NVIDIA RTX 6000 Ada Gene... On | 00000000:52:00.0 Off | Off | | 31% 60C P2 71W / 300W | 4213MiB / 49140MiB | 1% Default | | | | N/A | +-----------------------------------------+----------------------+----------------------+ +---------------------------------------------------------------------------------------+ | Processes: | | GPU GI CI PID Type Process name GPU Memory | | ID ID Usage | |=======================================================================================| | 0 N/A N/A 2310 G /usr/lib/xorg/Xorg 913MiB | | 0 N/A N/A 2535 G /usr/bin/gnome-shell 80MiB | | 0 N/A N/A 3040 G ...AAAAAAAACAAAAAAAAAA= --shared-files 43MiB | | 0 N/A N/A 26577 G /usr/lib/thunderbird/thunderbird 19MiB | | 0 N/A N/A 151053 G ...AAAAAAAIAAAAAAAAAA== --shared-files 102MiB | | 0 N/A N/A 862586 C python 918MiB | | 0 N/A N/A 863180 C python 730MiB | | 0 N/A N/A 864122 C python 730MiB | | 0 N/A N/A 901572 C+G ./blender 411MiB | | 0 N/A N/A 1014271 G ...sion,SpareRendererForSitePerProcess 51MiB | | 0 N/A N/A 1023738 G meshlab 13MiB | | 0 N/A N/A 3651908 G ...irefox/3358/usr/lib/firefox/firefox 68MiB | +------------------------------------------------------------------------------- </code></pre>
<python><x11><egl>
2023-12-22 19:22:04
1
38,867
Mona Jalal
77,705,421
8,231,763
access aspen plus through COM interface -- using python vs matlab
<p>I have successfully accessed many different Aspen Plus variables through COM interface using Python (win32com), but failed to do so for the following variable, using the same command.</p> <pre><code>AspenPlus.Tree.FindNode(&quot;\Data\Reactions\Reactions\ReactionABC\Input\RVALUE_LIST\#1&quot;).Value = 11 </code></pre> <p>However, this exact same command worked well using Matlab. It appears that python failed to deal with &quot;#&quot;. How to fix this? Any suggestion or help will be highly appreciated.</p>
<python><matlab><com><win32com><aspen>
2023-12-22 19:07:38
1
325
Shu Pan
77,705,303
14,923,227
Sympy get valid integer range for each variable in expression
<p>Given that I have the following expression:</p> <pre><code>from sympy import * a,b,c,d = var('a b c d') variables = { 'a': a, 'b': b, 'c': c, 'd': d } string = &quot;(a &gt; 1548) | (a &gt; 2090) | (b &gt; 2662) | ((c &gt; 838) &amp; (c &lt; 1801)) | ((d &gt; 2770) &amp; (d &lt; 3448))&quot; expr = eval(string,variables) expr </code></pre> <pre><code>(a &gt; 1548) | (a &gt; 2090) | (b &gt; 2662) | ((c &gt; 838) &amp; (c &lt; 1801)) | ((d &gt; 2770) &amp; (d &lt; 2900)) </code></pre> <p>I want to get the valid value range for each variable if each variable can be between 1 and 3000. In other words:</p> <pre><code>valid_expr = expr &amp; ((1 &lt;= a) &amp; (a &lt;= 3000)) &amp; ((1 &lt;= b) &amp; (b &lt;= 3000)) &amp; ((1 &lt;= c) &amp; (c &lt;= 3000)) &amp; ((1 &lt;= d) &amp; (d &lt;= 3000)) </code></pre> <p>How do I get the range for each variable?</p> <p>I want to somehow get an output similar to</p> <pre><code>{ 'a': [1548,3000], 'b': [2662,3000], 'c': [838,1801], 'd': [2770,2900] } </code></pre>
<python><sympy>
2023-12-22 18:36:50
3
3,418
Kevin
77,705,227
7,745,011
scikit-image RAG mergine leaves black areas
<p><a href="https://scikit-image.org/docs/stable/auto_examples/segmentation/plot_rag_merge.html#sphx-glr-auto-examples-segmentation-plot-rag-merge-py" rel="nofollow noreferrer">Following this example on the scikit-image homepage</a>, in my example the image has some black areas after merging the RAG in case the threshold is set too high. From the documentation I understand that &quot;similiar&quot; regions should be merged, however it seems that some RAG regions are removed altogether. I'm wondering what the issue here might be, since for my applications it would be nice to segment many regions with SLIC (to get more structural details) and afterwards combine to bigger regions.</p> <p>Here is my full script:</p> <pre><code>import click import numpy as np import skimage as ski from PIL import Image def _weight_mean_color(graph, src, dst, n): diff = graph.nodes[dst][&quot;mean color&quot;] - graph.nodes[n][&quot;mean color&quot;] diff = np.linalg.norm(diff) return {&quot;weight&quot;: diff} def merge_mean_color(graph, src, dst): graph.nodes[dst][&quot;total color&quot;] += graph.nodes[src][&quot;total color&quot;] graph.nodes[dst][&quot;pixel count&quot;] += graph.nodes[src][&quot;pixel count&quot;] graph.nodes[dst][&quot;mean color&quot;] = ( graph.nodes[dst][&quot;total color&quot;] / graph.nodes[dst][&quot;pixel count&quot;] ) @click.command() @click.version_option() @click.option( &quot;--path&quot;, type=str, required=True, help=&quot;path to an image&quot;, ) def main(path: str) -&gt; None: print(f&quot;loading image {path}&quot;) pil_img = Image.open(path) # pil_img = pil_img.resize((pil_img.size[0] // 4, pil_img.size[1] // 4)) # downsize during testing to reduce waiting times input_image = np.asarray(pil_img) print(&quot;making slic&quot;) slic = ski.segmentation.slic( image=input_image, n_segments=5000, compactness=0.1, sigma=0.95, slic_zero=True ) slic_rgb = ski.util.img_as_ubyte( ski.color.label2rgb(label=slic, image=input_image, kind=&quot;avg&quot;) ) result = Image.fromarray(slic_rgb) result.save(&quot;results/slic_rgb.png&quot;) print(&quot;making rag&quot;) rag = ski.graph.rag_mean_color(input_image, slic) rag_thresh_cut = ski.graph.merge_hierarchical( labels=slic, rag=rag, thresh=32, # no issues here with a lower thresh, e.g.8 rag_copy=False, in_place_merge=True, merge_func=merge_mean_color, weight_func=_weight_mean_color, ) rag_rgb = ski.color.label2rgb(rag_thresh_cut, slic_rgb, kind=&quot;avg&quot;) result = Image.fromarray(rag_rgb) result.save(&quot;results/rag_rgb.png&quot;) </code></pre> <p>For example, here is a section of the original segmented image (slic segmentation)</p> <p><a href="https://i.sstatic.net/pZSyv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/pZSyv.png" alt="enter image description here" /></a></p> <p>And here the resulting image after merging the RAG (note the black area on the top-center)</p> <p><a href="https://i.sstatic.net/fVbG8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fVbG8.png" alt="enter image description here" /></a></p> <p><strong>EDIT</strong></p> <p>I have found at least part of the problem. In the code above <code>rag_thresh_cut</code> contains the label <code>0</code> for one color which is interpreted as background color by <code>skimage.color.label2rgb()</code>. In my case background color was set to black, if I set it to red for example, the area in the image above becomes red. A simple workaround for now is to simply add <code>1</code> to <code>rag_thresh_cut</code>, but I am still wondering how to best avoid this problem in the first place.</p>
<python><scikit-image>
2023-12-22 18:17:45
1
2,980
Roland Deschain
77,705,220
19,916,174
Remove Annotations from typing.Annotated
<p>Let's say I have some type aliases, maybe</p> <pre class="lang-py prettyprint-override"><code>Point3D = Annotated[tuple[float, float, float], &quot;A 3D Point&quot;] Points = Annotated[list[Point3D, list[float]], &quot;A collection of points&quot;] </code></pre> <p>If I try to print Points, I get</p> <pre class="lang-py prettyprint-override"><code>typing.Annotated[list[typing.Annotated[tuple[float, float, float], 'A 3D Point'] | list[float]], 'A collection of points'] </code></pre> <p>I want to only get the <code>list[tuple[float, float, float]]</code> part. I tried using <code>typing.get_args(Points)[0]</code> but that just gives this:</p> <pre class="lang-py prettyprint-override"><code>list[typing.Annotated[tuple[float, float, float], 'A 3D Point'] | list[float]] </code></pre> <p>Where there is still the unwanted <code>'A 3D Point'</code>. How can I achieve this? I tried replacing it with the <code>&quot;, '.*?'</code> regex, but that didn't work, and I'm not experienced enough with regex to be able to figure out why.</p> <p>Note: I can't just change all the <code>Annotated</code> types to normal type hints because I still need that annotation content to be displayed elsewhere.</p>
<python><regex><python-sphinx><python-typing>
2023-12-22 18:16:44
2
344
Jason Grace
77,705,194
23,106,915
Facing prob. while importing font in Tkinter
<p><strong>Description:</strong> So I am using customtkinter for my project and I used Armin Grotesk font in my project the problem is if the project is running on my system it works like a charm as soon as I transfer the files over to a new pc the font disappears, I think sans-serif replaces it.</p> <p><strong>Expecting:</strong> A solution maybe like installing the font in the background without the user knowing or maybe a method through which I can transfer the font file.</p>
<python><tkinter>
2023-12-22 18:11:22
1
546
AshhadDevLab
77,705,175
8,194,777
Unable to pass parameters when using pyodbc in Django for large query
<p>Working on: Django framework pyodbc package (MSSQL Version 18) DS: Azure synapse</p> <p>I would like to know what is the best way to go about when trying to load a large number of parameters into the SQL query for Azure synapse.</p> <p>The scale I'm looking for is in millions.</p> <p>I can split the parameters into chunks of 2k which is the limit specified here: <a href="https://learn.microsoft.com/en-us/azure/synapse-analytics/sql-data-warehouse/sql-data-warehouse-service-capacity-limits#queries" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/azure/synapse-analytics/sql-data-warehouse/sql-data-warehouse-service-capacity-limits#queries</a></p> <p>However, that would mean the number of queries would be too many. ~500 per million parameters.</p> <p>This isn't just for 1 type of parameter for e.g in where clause I may have 2 columns, each column with its own set of a million values which I would like to pass through the query params.</p> <p>What's the best way to about this?</p> <p>As a sidenote: I hadn't been able to get the queries working with '?' parameter holder, I had to use '%s' to fix this.</p> <p>Thanking in advance!</p>
<python><django><t-sql><pyodbc><azure-synapse>
2023-12-22 18:06:50
0
361
SagarM
77,705,122
5,924,264
How to speedup a dataframe's apply function on a custom input function
<p>I have a dataframe with millions of rows. I want to compute another column <code>new_col</code> based on an existing <code>col</code>.</p> <pre><code> df[&quot;new_col&quot;] = (df[&quot;col&quot;].apply(my_obj.move, args=(1,))) </code></pre> <p><code>my_obj</code> is a class instance with an <code>instance</code> method <code>move</code> that takes in a value and some constant (<code>1</code> in this case) and does some numerical operations before returning it.</p> <p>My script is stuck on this line where it's taking hours (and counting) to execute. How can I speed up this operation?</p>
<python><pandas><dataframe>
2023-12-22 17:51:03
1
2,502
roulette01
77,705,057
12,425,004
How to pass a .pem key in GitHub actions via environment variable without characters causing YAML parsing issues
<p>I have a GitHub environment secret <code>{{ secrets.GITHUBAPP_KEY }</code> that holds a .pem key, in a workflow step, I'm trying to pass the secret to an env variable <code>GITHUBAPP_KEY</code></p> <pre><code> - name: Do Certain Step run: Insert fancy command here env: GITHUBAPP_KEY: &quot;${{ secrets.GITHUBAPP_KEY }}&quot; </code></pre> <p>Here is the error the GitHub actio workflow gets when I run it:</p> <p>error: error parsing STDIN: invalid Yaml document separator: --END RSA PRIVATE KEY-----&quot;</p> <p>The key is the correct format, I have also wrapped double quotes around the secrets context, yet, the file still does not get parsed correctly.</p> <p>How can I solve this issue?</p>
<python><yaml><cryptography><github-actions><ssh-keys>
2023-12-22 17:34:16
1
1,826
yung peso
77,704,843
10,595,871
recursively create new keys in dictionary if len(value) is greater than x
<p>I have a dictionary where tha values are list of strings. I need to perform the sum of the word in the whole strings and, when I reach a number x, I need to go back to the previous string, duplicate the key (with maybe a _i as suffix) and insert the remaining strings in the new value. Also, I need to delete the remaining strings from the previous value. I need to do this also for the new keys created.</p> <p>Example where x = 5:</p> <pre><code>initial_dict = {'key1': ['abc wer', 'defgh e', 'ij r', 'klmnopqr r', 'e r stuv', 'wxyz aaa', 'extra word'], 'key2': ['ciao']} output = {'key1': ['abc wer', 'defgh e'], 'key1_1' : ['ij r', 'klmnopqr r'], 'key1_2' : [ 'e r stuv', 'wxyz aaa'], 'key1_3' : [ 'extra word'], 'key2': ['ciao']} </code></pre> <p>So the sum of the words is always &lt;= 5.</p> <p>Thanks!</p>
<python><dictionary>
2023-12-22 16:42:47
0
691
Federicofkt
77,704,835
11,426,624
calculate weighted_average of pandas df in a function
<p>I have a function and in this function I would like to calculate the weighted average of the column <code>other_column</code> (weighted with column <code>amount</code>). If I did not have this in a function then it would work, but like this I am not sure how to pass the dataframe? I'm also getting an error: <code>NameError: name 'df1' is not defined</code>.</p> <pre><code>def weighted_mean(x): try: return np.average(x, weights=df1.loc[x.index, 'amount']) &gt; 0.5 except ZeroDivisionError: return 0 def some_function(df1=None): df1 = df1.groupby('id').agg(xx=('amount', lambda x: x.sum() &gt; 100), yy=('other_col', weighted_mean)).reset_index() return df1 df2 = pd.DataFrame({'id':[1,1,2,2,3], 'amount':[10, 200, 1, 10, 150], 'other_col':[0.1, 0.6, 0.7, 0.2, 0.4]}) df2 = some_function(df1=df2) </code></pre> <p>so that I get</p> <pre><code> id xx yy 0 1 True True 1 2 False False 2 3 True False </code></pre>
<python><pandas><dataframe><group-by><aggregate>
2023-12-22 16:40:57
2
734
corianne1234
77,704,793
7,262,393
Simulating mutation in a population of cells. Numpy arr size manipulation efficiency
<p>I am working on a project where we would like to figure out a way to estimate the mean generation a mutation first appears in a replicating population of cells through simulating the frequency in the population. I realize I could just track the first instance of it but this isn't going to be very helpful when dealing with populations of new cells and new mutations. I'd like to be able to do it through looking at the percentages of mutations in a grouping, given the mutation rate. For the simulation, we are starting with two cells of the wild type and simulating 30 generations (i.e.; all cells will replicate once in every generation). Meaning, the total number of cells at the end of the experiment will be 2^30 (i.e.; the number of cells double every generation 2-&gt; 4, 4-&gt;8, 8-&gt;16 etc), and the generation of first appearance should be able to be predicted/estimated through the proportion of mutated cells in the final number of cells.</p> <p>I figured the best way to do this was create one array containing an element for every cell that will be generated through the experiment, the starting position of which will be all zeros. The array will be updated after each generation dependent on the type of mutation and mutation rate, by changing the next slice of the array dependent on a random selection from a mutation array and mutation frequency array.</p> <p>There are two types of mutation in my model and they will be designated with a +1 or a -1 with the frequency of the -1 being approximately 10X that of the +1 (0.0078, and 0.00079 respectively). I choose +1 and -1 so that I can also track multiple mutations of the same type in the cell line through the generations. For example if there is a -5 in the end product, I know that cell line has mutated in the -1 direction at least 5 times. Tracking a mutation back in the other direction I haven’t quite figured out how to detect in my model yet, but I will worry about that later.</p> <p>As an example I will draw out what might happen if there was a mutation in the 2nd and 3rd generation and show what the 4th generation would look like in the array.</p> <h2>My starting array for the population</h2> <p>[0,0,0,0,0,0,…,0] where # elements = 1,073,741,824</p> <h2>Progenitor generation: Two wild type cells</h2> <p>[0, 0]</p> <h2>2nd generation: This generation splits to 4 cells with the second cell producing a -1 mutation</h2> <p>[0,0] -&gt; [0,0,<strong>0,-1</strong>] <code>- bold indicates the replicated cells</code></p> <p>Update the population array</p> <p>[0,0,<strong>0,-1</strong>,...,0] where # elements = 1,073,741,824</p> <h2>3rd generation: This generation splits into 8 cells with the 4th cell still containing the -1 and now producing a copy of the -1, and the first cell producing another -1 mutation.</h2> <p>[0,0,0,-1] -&gt; [0,0,0,-1,<strong>-1,0,0,-1</strong>]</p> <p>Update the population array</p> <p>[0,0,0,-1,<strong>-1,0,0,-1</strong>,...,0] where # elements = 1,073,741,824</p> <h2>4th generation: No mutations happen. This produces an exact copy of the previous generation</h2> <p>[0,0,0,-1,-1,0,0,-1] - &gt; [0,0,0,-1,-1,0,0,-1,<strong>0,0,0,-1,-1,0,0,-1</strong>]</p> <p>Update the population array</p> <p>[0,0,0,-1,-1,0,0,-1,<strong>0,0,0,-1,-1,0,0,-1</strong>...,0] where # elements = 1,073,741,824</p> <p>The trouble I am having is the length of time that the generation of the data is taking above 25 generations. I would like to be able to manipulate this simulation in multiple ways and do it many times but the time that the final generations are taking is prohibitive. Does anyone have any suggestions for a better or more efficient way to go about this simulation (besides doing less generations. 30 is a minimum we are looking for)? My Code:</p> <pre><code>import numpy as np import pandas as pd def mutation_model(total_splits, m_type1_freq, my_type2_freq): &quot;&quot;&quot;Simulates mutation over n generations. You enter the number of generations, and the frequency of each mutation Parameters: ---------- _total_splits: integer The number of generations (ie splits). The total number of cells will be 2^splits _m_type1_freq: float The expected frequency of the occurrence of the first type of mutation. _my_type2_freq: float The expected frequency of the occurrence of the second type of mutation. &quot;&quot;&quot; # array for mutation type 1 (-1), wild type(0), and mutation type (1) mutation_types = np.array([-1, 0, 1]) # frequency array to sample from mutation_freqs = np.array([m_type1_freq, 1-(m_type1_freq + my_type2_freq), my_type2_freq]) # target number of cells cell_arr = np.zeros((2**total_splits, ), dtype=int) # multiplier exponent = 2 # simulating generations for i in range(total_splits - 1): # make a copy of the first 2x part duplicate_arr = cell_arr[:exponent] # determine if the new copy will be rev, fwd, or a parent copy random_indices = np.random.choice(len(mutation_types), size=exponent, p=mutation_freqs) # get the new copy to update the next range of values in the array selection = mutation_types[random_indices] # update the next slice of the array cell_arr[exponent:(exponent * 2)] = np.add(duplicate_arr, selection) # increment exponent exponent *= 2 dict_data = {'+2 mutation': np.count_nonzero(cell_arr == 2)/2**total_splits, '+1 mutation': np.count_nonzero(cell_arr == 1)/2**total_splits, 'Wild type': np.count_nonzero(cell_arr == 0)/2**total_splits, '-1 mutation': np.count_nonzero(cell_arr == -1)/2**total_splits, '-2 mutation': np.count_nonzero(cell_arr == -2)/2**total_splits, '-3 mutation': np.count_nonzero(cell_arr == -3)/2**total_splits, '-4 mutation': np.count_nonzero(cell_arr == -4)/2**total_splits, '-5 mutation': np.count_nonzero(cell_arr == -5)/2**total_splits} return dict_data # pd.set_option('display.max_rows', None) # pd.set_option('display.max_columns', None) data = [] for i in range(100): print(&quot;Working on iteration: &quot;, i + 1) mutation_dict = mutation_model(30, 0.078, 0.0076) data.append(mutation_dict) df = pd.json_normalize(data) # print(df) df.to_csv('mutation.csv') </code></pre>
<python><numpy>
2023-12-22 16:34:21
1
773
Dan
77,704,523
1,775,010
Sounddevice + big array + OOP = Segfault / Bus Error
<p>I'm having a very strange problem, which I managed to reduce as much as possible like this:</p> <pre class="lang-py prettyprint-override"><code>import sounddevice import time class SamplerBox: def __init__(self): self.samples = {} def audio_callback(self, outdata, frame_count, time_info, status): print('ac') def init(self): self.connect_audio_output() self.load_samples() time.sleep(20) def connect_audio_output(self): try: sd = sounddevice.OutputStream(callback=self.audio_callback) sd.start() print('Opened audio device') except: print('Invalid audio device') exit(1) def load_samples(self): for midinote in range(128): for velocity in range(128): self.samples[midinote, velocity] = Sound() class Sound: def __init__(self): pass sb = SamplerBox() sb.init() </code></pre> <p>As soon as I create that big <code>self.samples</code> dict, and only create a new audio stream with an empty callback, I get &quot;Bus Error 10&quot; with Python 3.11.</p> <p>With Python 3.9 I get &quot;Illegal instruction 4&quot;</p> <p>In my original script (reduced here) I got &quot;Segmentation Fault 11&quot;</p> <p>I'm running Homebrew Python 3.11 on MacOS 10.15.7.</p> <p>Worst than that, <em><strong>written in a procedural way, it runs perfectly</strong></em> :</p> <pre class="lang-py prettyprint-override"><code>import sounddevice import time samples = {} class Sound: def __init__(self): pass def audio_callback(self, outdata, frame_count, time_info, status): print('ac') try: sd = sounddevice.OutputStream(callback=audio_callback) sd.start() print('Opened audio device') except: print('Invalid audio device') exit(1) for midinote in range(128): for velocity in range(128): samples[midinote, velocity] = Sound() time.sleep(20) </code></pre> <p>Any idea?</p>
<python><audio><python-sounddevice>
2023-12-22 15:33:26
1
1,068
theredled
77,704,416
17,835,120
Delete label using Gmail API Python
<p><strong>Trying to use Gmail API to delete a label</strong>. But it doesn't seem to be working and triggering an <strong>insufficient permission</strong> error in python. It doesn't seem correct because in google shows all permissions checked off. Is there a code fix that I can apply to resolve or is it something else?</p> <p><strong>CODE USED TO DELETE LABEL</strong></p> <pre><code>try: target_label_name = &quot;Label_8&quot; service = build(&quot;gmail&quot;, &quot;v1&quot;, credentials=creds) messages_results = service.users().messages().list(userId=&quot;me&quot;, labelIds=[target_label_name]).execute() messages = messages_results.get(&quot;messages&quot;, []) if not messages: print(f&quot;No emails found with label: {target_label_name}&quot;) return for message in messages: # Remove the label from the message service.users().messages().modify(userId=&quot;me&quot;, id=message['id'], body={'removeLabelIds': [target_label_name]}).execute() print(f&quot;Label {target_label_name} removed from message {message['id']}.&quot;) </code></pre> <p><strong>Get this error about insufficient permissions</strong></p> <p>&lt;HttpError 403 when requesting <a href="https://gmail.googleapis.com/gmail/v1/users/me/messages/18c8dae6ea7e602e/modify?alt=json" rel="nofollow noreferrer">https://gmail.googleapis.com/gmail/v1/users/me/messages/18c8dae6ea7e602e/modify?alt=json</a> returned &quot;Request had insufficient authentication scopes.&quot;. Details: &quot;[{'message': 'Insufficient Permission', 'domain': 'global', 'reason': 'insufficientPermissions'}]&quot;&gt;</p> <p><strong>But Google Console Shows I have all permissions</strong></p> <p><a href="https://i.sstatic.net/g4abJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/g4abJ.png" alt="enter image description here" /></a></p> <p><strong>FULL CODE</strong></p> <pre><code>import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError SCOPES = [&quot;https://www.googleapis.com/auth/gmail.modify&quot;] def main(): creds = None credentials_path = &quot;C:\\credentials1.json&quot; if os.path.exists(&quot;token.json&quot;): creds = Credentials.from_authorized_user_file(&quot;token.json&quot;, SCOPES) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( credentials_path, SCOPES ) creds = flow.run_local_server(port=0) with open(&quot;token.json&quot;, &quot;w&quot;) as token: token.write(creds.to_json()) try: target_label_name = &quot;Label_8&quot; service = build(&quot;gmail&quot;, &quot;v1&quot;, credentials=creds) messages_results = service.users().messages().list(userId=&quot;me&quot;, labelIds=[target_label_name]).execute() messages = messages_results.get(&quot;messages&quot;, []) if not messages: print(f&quot;No emails found with label: {target_label_name}&quot;) return for message in messages: # Remove the label from the message service.users().messages().modify(userId=&quot;me&quot;, id=message['id'], body={'removeLabelIds': [target_label_name]}).execute() print(f&quot;Label {target_label_name} removed from message {message['id']}.&quot;) except HttpError as error: print(f&quot;An error occurred: {error}&quot;) if __name__ == &quot;__main__&quot;: main() </code></pre> <p><strong>MAYBE RELATED TO SCOPES IN OAUTH CONSENT SCREEN</strong> <a href="https://i.sstatic.net/R3fI3.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/R3fI3.png" alt="enter image description here" /></a></p>
<python><gmail-api>
2023-12-22 15:12:43
1
457
MMsmithH
77,704,291
4,865,723
Problems getting results of MatchIt with rpy2 / How to debug R function with rpy2?
<p>I wasn't able to reproduce this in an MWE. I was using this code in the past and it worked. Some might have changed since then.</p> <p>There is no error. The problem is that <code>get_balance</code> is of <code>NoneType</code>. The self build R function did not return something.</p> <pre><code>get_balance = robjects.r('''f &lt;- function(match_out) { result &lt;- summary(match_out)$sum.all result &lt;- as.data.frame(result) return(result) } ''') balance = get_balance(match_result) </code></pre> <p>I am not well experienced with R. So I don't know how to debug this or to add some debug helper lines in that R code.</p> <p>I could break it into several steps e.g. <code>robjects.r['summary']</code>. But I don't know how to &quot;translate&quot; the <code>$sum.all</code> into Python.</p> <p>I don't know where to start.</p>
<python><r><rpy2><matchit>
2023-12-22 14:43:14
1
12,450
buhtz
77,704,283
22,213,065
The script is not skipping the lines mentioned in my skip list
<p>I wrote a very simple python script that must apply some changes in my input txt file<br /> for example my input txt file is:</p> <pre><code>ari2600 ARI 304,975 nnelun CHALF185,406 Magnassey PHPS119,353 dioI 69,671 ari5200 ARI 0 ari7800 ARI 0 assesion EPOCH0 Coleion QUECO0 Gatch Nido® 0 Mavsion MEL 0 NESSD Ndo® 0 SG-1000 SAO Sestem SEO 1978Q2 </code></pre> <p>and my skip list is:</p> <pre><code>ari2600 nnelun Magnassey dioI ari5200 ari7800 assesion Coleion Gatch Mavsion NESSD SG-1000 Sestem </code></pre> <p>script must check <strong>each line of my input txt file</strong> and each line must <strong>exclude my skip list lines</strong>.<br /> after that if checked line exclude my skip list then script must apply following find &amp; replace on that line and if checked line include my skip list then must skip that line and no need any changes.</p> <pre><code>find what : ^(?!\d{4}Q[1-4])([^\d\n]+)([\d,]+) replace : \r\n$&amp; </code></pre> <p>my python script is:</p> <pre><code>import re # Define the input file path file_path = r'E:\Desktop\edit1\joined.txt' # Pattern to match lines to be skipped skip_pattern = r'G:\\NOW\\joined.txt' # Pattern for finding and replacing in non-skipped lines find_pattern = r'^(?!\d{4}Q[1-4])([^\d\n]+)([\d,]+)' replace_pattern = r'\r\n$&amp;' # Read file, check each line, and modify accordingly with open(file_path, 'r') as file: lines = file.readlines() modified_lines = [] for line in lines: if re.search(skip_pattern, line): # Skip lines matching the skip pattern modified_lines.append(line) else: # Modify lines that don't match the skip pattern modified_line = re.sub(find_pattern, replace_pattern, line) modified_lines.append(modified_line) # Write modified lines back to the file with open(file_path, 'w') as file: file.writelines(modified_lines) </code></pre> <p><strong>my script working but it have a problem!</strong>, it doesn't skip my skip list<br /> <strong>for example it not skip ari2600</strong> and convert it to following result by regex:</p> <pre><code>ari 2600 </code></pre> <p>where is my script problem?</p>
<python><regex>
2023-12-22 14:41:31
1
781
Pubg Mobile
77,704,187
929,732
PIP Python not installing latest version of package
<p>So installing the JIRA python package. The PyPi repo says there is a 3.5.2 but when asking for the specific version I get. the below... the generic install give me 3.2 which is not the latest version.</p> <pre><code>pip install jira==3.5.2 or pip install jira </code></pre> <blockquote> <p>ERROR: Could not find a version that satisfies the requirement jira==3.5.2 (from versions: 0.1.0, 0.16, 0.17, 0.18, 0.19, 0.20, 0.21, 0.22, 0.23, 0.25, 0.28, 0.30, 0.31, 0.32, 0.33, 0.35, 0.36, 0.37, 0.38, 0.39, 0.40, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.50, 1.0.3, 1.0.7.dev20160607111203, 1.0.7, 1.0.8, 1.0.9, 1.0.10, 1.0.11, 1.0.13, 1.0.14, 1.0.15, 2.0.0.0rc3, 2.0.0.0rc4, 2.0.0.0rc6, 2.0.0.0rc7, 2.0.0.0rc9, 2.0.0.0rc10, 2.0.0, 2.0.1.0rc1, 3.0.0.0a0, 3.0a1, 3.0a2, 3.0.1, 3.1.0rc1, 3.1.1, 3.2.0) ERROR: No matching distribution found for jira==3.5.2</p> </blockquote> <p>Not understanding why..</p>
<python><jira><python-jira>
2023-12-22 14:23:49
0
1,489
BostonAreaHuman
77,704,029
7,474,589
Pandas - calculate rolling standard deviation over all columns
<p>Say I have a pd.DataFrame and want to calculate the rolling Standard deviation. In pandas I can use <code>rolling(window=x).std()</code>, but it gives me the SD by column. I however want the standard deviation over all columns in a given row.</p> <p>As an example consider the pd dataframe</p> <pre><code>df = pd.DataFrame({'col1': [1,2,3,4,5,6], 'col2': [-1,-2,-3,-4,-5,-6], 'col3': [1,2,3,4,5,6]}) df col1 col2 col3 0 1 -1 1 1 2 -2 2 2 3 -3 3 3 4 -4 4 4 5 -5 5 5 6 -6 6 </code></pre> <p>When calculating for a window size of 2, for instance, I would like to have the standard deviation in row 2 as the sum of the two rows divided by 6 (or 6-1), doesn't matter), so: np.std([2,-2,2,1,-1,1]).</p> <p>I tried to calculate it on a melted dataframe, but I didn't get the result as expected:</p> <pre><code>df.reset_index().melt(id_vars='index').set_index('index')['value'].rolling(2).std() </code></pre> <p>Does anyone have an idea how to do it? I appreciate your feedback.</p>
<python><pandas><rolling-computation><standard-deviation>
2023-12-22 13:49:56
2
349
W. Walter
77,703,777
625,350
No TypeError raised for missing abc.abstractmethod when deriving a PySide6 widget
<p>I have an object that inherits both from a <code>QWidget</code> and an <code>abc.ABC</code> interface. See <code>MyWindow</code> in my example below.</p> <pre><code>import abc from PySide6 import QtCore, QtWidgets #from PyQt6 import QtCore, QtWidgets # It works as expected in PyQt6 #from PyQt5 import QtCore, QtWidgets # Idem for PyQt5 class Interface(abc.ABC): @abc.abstractmethod def myMethod(self, a): pass class NormalClass(Interface): def myMethod(self, a): &quot;When you delete this method, you get an error as expected.&quot; print(&quot;my method normally&quot;) class QObjectAbcMeta(type(QtCore.QObject), type(abc.ABC)): pass class MyWindow(QtWidgets.QWidget, Interface, metaclass=QObjectAbcMeta): # Even though myMethod is missing, you don't get an error with PySide6 pass def main(): normal = NormalClass() app = QtWidgets.QApplication([]) win = MyWindow() win.show() app.exec() if __name__ == &quot;__main__&quot;: main() </code></pre> <p>I would expect that Python raises a TypeError here because the <code>MyWindow</code> class is missing a definition for the <code>myMethod</code> abstract method. However, it just runs without any error.</p> <p>When I use PyQt6 I get a TypeError as expected. Also when I don't inherit from <code>QWidget</code> (my <code>NormalClass</code>) it works as expected.</p> <p>Does anybody know a solution?</p>
<python><pyqt><pyside6><abc>
2023-12-22 12:58:03
0
5,596
titusjan
77,703,763
1,771,155
dbt python models and unitests
<p>I have a dbt python model in my folder <code>foo</code></p> <pre><code> |-foo | |-post_to_api.py | |-test_post_to_api.py | |-foo.sql </code></pre> <p>How can I exclude all my python tests when I do <code>dbt run</code>?</p> <pre><code>dbt run --models foo --exclude foo.test_post_to_api Parsing Error in model test_post_to_api (models/geronimo/test_post_to_api.py) dbt allows exactly one model defined per python file, found 0 </code></pre> <p>Or should I put my unittests in another location?</p>
<python><dbt>
2023-12-22 12:55:31
1
4,886
Vincent Claes
77,703,591
3,747,486
Debug mode not stop at breakpoint when VS Code workspace is under Python installation directory and justMyCode is true
<p>I am trying to learn how to use break points.</p> <p>As you can see in below screenshot, the program didn't stop at break point and the variables window is empty.</p> <p>I press the button in orange circle. I have also tried press F5 Start debugging. Both have same result.</p> <p>What could be the problem?</p> <p><a href="https://i.sstatic.net/X4oBq.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/X4oBq.png" alt="enter image description here" /></a></p> <p>Here is my code. There is no error message. The program run from line 1 to line 9 without error.</p> <pre><code>a = 33 b = 200 if b&gt;a: print(&quot;b is larger than b&quot;) c = 1000 d = 9999 if d&gt;c: print(&quot;d is larger than c&quot;) </code></pre> <p>Here is my debug configuration launch.json</p> <pre><code>{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 &quot;version&quot;: &quot;0.2.0&quot;, &quot;configurations&quot;: [ { &quot;name&quot;: &quot;Python: Current File&quot;, &quot;type&quot;: &quot;python&quot;, &quot;request&quot;: &quot;launch&quot;, &quot;program&quot;: &quot;${file}&quot;, &quot;console&quot;: &quot;integratedTerminal&quot;, &quot;justMyCode&quot;: true } ] } </code></pre>
<python><visual-studio-code><vscode-debugger>
2023-12-22 12:17:14
4
326
Mark
77,703,490
2,526,586
PyQt/PySide: QFileDialog to select both existing and non-existing directory
<p>In my Python GUI(PyQt/PySide) application, I am using <code>QFileDialog</code> to let users to pick <strong>ONLY ONE directory</strong> so that the application will save multiple files in that directory. This directory can be either exiting or non-existing. If the directory does not exist, my application will create the directory for the users via <code>os.makedirs(dir)</code></p> <p>So initially, I had this for opening <code>QFileDialog</code>:</p> <pre><code>dir = QFileDialog.getExistingDirectory(self, &quot;Please pick a directory...&quot;, path) </code></pre> <p>This will limit users to pick directory only and not files. However, this won't allow users to pick a non-existing directory. So I had to change it to this:</p> <pre><code>dir, _filter = QFileDialog.getSaveFileName(self, &quot;Please pick a directory...&quot;, path, &quot;Directory&quot;, &quot;&quot;, QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks) </code></pre> <p>This way, I allow users to &quot;save&quot; a new directory. However, this won't allow users to pick an existing directory. (Also, I am not sure if my filters above are correct if I want users to only see directories)</p> <p>By sticking with the static functions of <code>QFileDialog</code>, is there a way for me to allow users to pick a directory that can be either existing and non-existing?</p> <p>If I have to go to the non-static functions path to achieve that, I may need more assistance on that, as I have no experience in working with non-static functions of <code>QFileDialog</code>. Some sample code would be welcome, as I don't know how to set up a <code>QFileDialog</code> as close to the native file dialog as possible.</p>
<python><directory><pyqt><pyside><qfiledialog>
2023-12-22 11:53:09
1
1,342
user2526586
77,703,424
9,182,414
Differences between import filename and import directoryname in Python
<p>In Python, when we do <code>import modulename</code>, is there any material difference between</p> <ul> <li>a file <code>modulename.py</code></li> <li>a directory with the same contents in <code>modulename/__init__.py</code>?</li> </ul> <p>Concretely: consider a file <code>m.py</code> containing <code>s = &quot;hello&quot;</code>:</p> <pre><code>&gt;&gt;&gt; import m &gt;&gt;&gt; m.s 'hello' </code></pre> <p>If instead we have a directory <code>m</code> with a file <code>__init__.py</code> containing the same <code>s = &quot;hello&quot;</code>, we get the identical result.</p> <p>Obviously the value of <code>__file__</code> is different during execution, and the directory structure can have submodules.</p> <p><strong>Are there any other differences at all? With any variant of <code>import</code> (<code>from</code>/<code>as</code>/etc) ?</strong></p> <hr /> <p><em>I'm really only concerned with Python 3, but version-specific details also welcomed for historic interest.</em></p>
<python>
2023-12-22 11:38:12
0
449
jonathanjo
77,703,309
8,275,139
Dump dictionary with a field containing an already encoded JSON string
<p>I'm JSON encoding a Dictionary using its avro schema to make it a stringify JSON:</p> <pre><code>import json from datetime import datetime import fastavro message = { &quot;name&quot;: &quot;any&quot;, &quot;ingestion_ts&quot;: datetime.utcnow(), &quot;values&quot;: { &quot;amount&quot;: 5, &quot;countries&quot;: [&quot;se&quot;, &quot;nl&quot;], &quot;source&quot;: { &quot;name&quot;: &quot;web&quot;, &quot;url&quot;: &quot;whatever&quot; } } } avro_schema = &quot;&quot; # import avro schema fo = StringIO() fastavro.json_writer(fo, avro_schema, [message]) message_str = fo.getvalue() </code></pre> <p>This works just as expected and returns me a JSON encoded string meeting the provided schema which looks like this:</p> <pre><code>'{&quot;name&quot;: &quot;any&quot;, &quot;ingestion_ts&quot;: 1703192665965373, &quot;values&quot;: {&quot;amount&quot;: 5, &quot;countries&quot;: [&quot;se&quot;, &quot;nl&quot;], &quot;source&quot;: {&quot;name&quot;: &quot;web&quot;, &quot;url&quot;: &quot;whatever&quot;}}}' </code></pre> <p>However, now I need to wrap this str in a dictionary on the <code>payload</code> key, and publish it to a messaging queue which is expecting this schema:</p> <pre><code>{ &quot;type&quot;: &quot;record&quot;, &quot;namespace&quot;: &quot;CDCEvent&quot;, &quot;name&quot;: &quot;CDCEvent&quot;, &quot;fields&quot;: [ { &quot;doc&quot;: &quot;The system that generated the event&quot;, &quot;type&quot;: &quot;string&quot;, &quot;name&quot;: &quot;sys&quot; }, { &quot;doc&quot;: &quot;The operation performed on the event&quot;, &quot;type&quot;: &quot;string&quot;, &quot;name&quot;: &quot;op&quot; }, { &quot;doc&quot;: &quot;The content of the event&quot;, &quot;type&quot;: &quot;string&quot;, &quot;name&quot;: &quot;payload&quot; } ] } </code></pre> <p>So I'm just doing like this:</p> <pre><code>wrap = { &quot;sys&quot;: &quot;my_system&quot;, &quot;op&quot;: &quot;c&quot;, &quot;payload&quot;: message_str } wrap_str = json.dumps(wrap) </code></pre> <p>The problem is that, as <code>message_str</code> has been previously encoded, when I encode the wrap again by calling <code>json.dumps</code>, the payload is being encoded again and the double quotes inside of it are being escaped, and the message cannot be properly decoded by the consumers:</p> <pre><code>'{&quot;sys&quot;: &quot;my_system&quot;, &quot;op&quot;: &quot;c&quot;, &quot;payload&quot;: &quot;{\\&quot;name\\&quot;: \\&quot;any\\&quot;, \\&quot;ingestion_ts\\&quot;: 1703192665965373, \\&quot;values\\&quot;: {\\&quot;amount\\&quot;: 5, \\&quot;countries\\&quot;: [\\&quot;se\\&quot;, \\&quot;nl\\&quot;], \\&quot;source\\&quot;: {\\&quot;name\\&quot;: \\&quot;web\\&quot;, \\&quot;url\\&quot;: \\&quot;whatever\\&quot;}}}&quot;}' </code></pre> <p>How could I avoid this double encoding? I've been trying to redesign the solution, but maybe I'm already obfuscated and I'm missing a pretty straightforward way. Remember that the queue is expecting a str for the <code>payload</code> field</p>
<python><json><avro>
2023-12-22 11:10:25
1
1,077
Luiscri
77,703,296
2,062,965
Can I combine pip installation based on requirements.txt with optional extra packages PEP508?
<p>For some while, I have been looking for a method to use a <code>requirements.txt</code> file (see <a href="https://pip.pypa.io/en/stable/reference/requirements-file-format/" rel="nofollow noreferrer">format specification</a>) with optional package extras depending on the use case, e.g., for testing purposes:</p> <pre><code># requirements.txt pandas &gt;= 2 pytest [test] &gt;= 7 pytest-testdox [test] </code></pre> <p>I follow the standard definition in <a href="https://peps.python.org/pep-0508/#extras" rel="nofollow noreferrer">PEP 508</a> for defining and grouping these optional extras.</p> <p>I would like to use a command like the following one, which does not work:</p> <pre><code>pip install -r requirements.txt[test] </code></pre> <p>Ideally, there would be a flag for specifying the extras involved but there is none as far as I know.</p> <h2>Workaround</h2> <p>I was writing in the end a <code>pyproject.toml</code>, which allows the following workaround as proposed in <a href="https://pip.pypa.io/en/stable/cli/pip_install/" rel="nofollow noreferrer">the official documentation</a>:</p> <pre><code>pip install '.[test]' </code></pre> <p>This command runs successfully based on the following (probably minimal) file:</p> <pre><code># pyproject.toml [tool.setuptools] packages = [&quot;myproject&quot;] [project] name = &quot;myproject&quot; version = &quot;0.1&quot; dependencies = [ &quot;pandas&quot;, ] [project.optional-dependencies] test = [ &quot;pytest &gt;= 7&quot;, &quot;pytest-testdox&quot;, ] </code></pre> <p>This approach, however, builds a new unnecessary package <code>myproject</code> out of the given file and folder, which I want to avoid.</p>
<python><pip><requirements.txt>
2023-12-22 11:07:49
2
2,784
strpeter
77,703,244
20,176,161
Generate a simple id from string
<p>I have a dataframe where I am trying to generate an id (without the complexity of a hash etc) based on an information from a string. The code is as follows:</p> <pre><code>df['id'] = df.City.str[:3] + '-' + df.Name.str[:3] +'-' + df.index.astype(str) City Name Id Paris John Par-Joh-1 Paris Paul Par-Pau-2 Paris Pierre Par-Pie-3 Paris Paula Par-Pau-4 Rome Riccardo Rom-Ric-5 Rome Jean-Paul Rom-Jea-6 Rome Franc Rom-Fra-7 </code></pre> <p>My problem is that the code does not restart count when the name of the column <code>City</code> changes (see above). How can I adapt the code to reach the desired output (see below)?</p> <pre><code>City Name Id Paris John Par-Joh-1 Paris Paul Par-Pau-2 Paris Pierre Par-Pie-3 Paris Paula Par-Pau-4 Rome Riccardo Rom-Ric-1 Rome Jean-Paul Rom-Jea-2 Rome Franc Rom-Fra-3 </code></pre> <p>Thank you</p>
<python><pandas>
2023-12-22 10:56:56
1
419
bravopapa
77,703,108
7,556,522
Resolving Type Support Errors in Polars Series
<p>I am working with the Polars library in Python and encountering type support errors while trying to implement a series operation function.</p> <p><strong>minimal reproducible example</strong></p> <pre class="lang-py prettyprint-override"><code>from polars import Series, Float64 def range_norm(serie: Series) -&gt; Series: &quot;&quot;&quot;Normalize the Series by its range.&quot;&quot;&quot; min_val = serie.min() range_val = serie.max() - min_val return (serie - min_val) / range_val </code></pre> <p>When running this function, Pylance in strict mode generates the following errors:</p> <pre><code>Operator &quot;-&quot; not supported for types &quot;PythonLiteral | None&quot; and &quot;PythonLiteral | None&quot; Operator &quot;-&quot; not supported for types &quot;int&quot; and &quot;date&quot; Operator &quot;-&quot; not supported for types &quot;int&quot; and &quot;time&quot; Operator &quot;-&quot; not supported for types &quot;int&quot; and &quot;datetime&quot; Operator &quot;-&quot; not supported for types &quot;int&quot; and &quot;timedelta&quot; Operator &quot;-&quot; not supported for types &quot;int&quot; and &quot;str&quot; Operator &quot;-&quot; not supported for types &quot;int&quot; and &quot;bytes&quot; Operator &quot;-&quot; not supported for types &quot;int&quot; and &quot;List[Any]&quot; Operator &quot;-&quot; not supported for types &quot;int&quot; and &quot;None&quot; Operator &quot;-&quot; not supported for types &quot;int&quot; and &quot;None&quot; [...] </code></pre> <p>I attempted to explicitly cast the min and max values to Float64 to ensure the correct type operation, but the errors persist. <code>pl.Float64(serie.max()) - pl.Float64(serie.min())</code></p> <p><strong>Question</strong></p> <blockquote> <p>How can I resolve these type support issues to ensure that my function works with polars data types in Polars? What are the best practices for handling these types of errors and ensuring type safety, especially in strict mode with tools like Pylance?</p> </blockquote>
<python><python-typing><python-polars><pyright>
2023-12-22 10:30:31
0
968
Olivier D'Ancona
77,703,068
22,221,987
How to precompile large text in QTextEdit to avoid freezes on widget first screen appearance
<p>I have <code>QTextEdit</code> widget, located in a <code>QTabWidget</code> tab with <code>index 1</code>. I set html file with this code.</p> <pre><code> def set_help_text_edit_html(self): f = QFile(&quot;app/resources/help_tab.html&quot;) f.open(QFile.ReadOnly | QFile.Text) stream = QTextStream(f) self.ui.help_textEdit.setHtml(stream.readAll()) f.close() </code></pre> <p>This function is called in <code>Main Window</code> <code>__init__</code> method, after loading UI class, before calling <code>show()</code> for <code>Main_Window</code>.</p> <p>Program starts with tab with <code>index 0</code>. So, when i switch tabs to tab with <code>index 1</code> (which contains <code>QTextWidget</code>), all this html is going to be drawn in real time and that causes lags.<br /> How can i avoid freezes, while loading text document?</p>
<python><python-3.x><qt><pyqt><pyside6>
2023-12-22 10:22:20
0
309
Mika
77,703,015
10,240,072
Dataframe sum columns according to dictionary of list of columns
<p>I am trying to find the most pytonic way to do the following :</p> <p>I have a dataframe and a dictionary</p> <pre><code>import pandas as pd df = pd.DataFrame([[4,8,52,7,54],[0,20,2,21,35],[2,33,12,1,87]], columns = ['A', 'B', 'C', 'D', 'E']) dic = {'x':['A','D'], 'y' : ['E'], 'z':['B','C']} </code></pre> <p>I am trying to have a dataframe with the keys of the dictionary as columns and each columns would be the sum of the columns from the original dataframe in the list of the corresponding key. For example, column 'x' would be the row-wise sum of the column 'A' and 'D'.</p> <p>This is easily doable with some loops but I am wandering if there is any elegant solution similar to list comprehension for example.</p>
<python><pandas><dataframe>
2023-12-22 10:12:44
3
313
Fred Dujardin
77,702,922
3,274,299
Pytorch in docker with read-only mode
<p>I'm running pytorch in docker. The requirements from security team is to run docker in read-only mode.</p> <p>I need to fork main process with models, that's why I use function <code>module.share_memory()</code> to move all models to shared memory and use <code>torch.multiprocessing.set_sharing_strategy('file_system')</code> because otherwise in <code>file_descriptor</code> mode 1024 open file descriptors is not enough for me, and I can't increase it because it is hardcoded in Linux. I use gunicorn is sync mode, it <a href="https://man7.org/linux/man-pages/man2/select.2.html" rel="nofollow noreferrer">uses linux select</a> under the hood.</p> <p>So when I run docker in read-only mode I'm getting an error:</p> <pre><code> File &quot;/app/.venv/lib/python3.9/site-packages/torch/nn/modules/module.py&quot;, line 1515, in share_memory return self._apply(lambda t: t.share_memory_()) File &quot;/app/.venv/lib/python3.9/site-packages/torch/nn/modules/module.py&quot;, line 387, in _apply module._apply(fn) File &quot;/app/.venv/lib/python3.9/site-packages/torch/nn/modules/module.py&quot;, line 387, in _apply module._apply(fn) File &quot;/app/.venv/lib/python3.9/site-packages/torch/nn/modules/module.py&quot;, line 387, in _apply module._apply(fn) [Previous line repeated 2 more times] File &quot;/app/.venv/lib/python3.9/site-packages/torch/nn/modules/module.py&quot;, line 409, in _apply param_applied = fn(param) File &quot;/app/.venv/lib/python3.9/site-packages/torch/nn/modules/module.py&quot;, line 1515, in &lt;lambda&gt; return self._apply(lambda t: t.share_memory_()) File &quot;/app/.venv/lib/python3.9/site-packages/torch/tensor.py&quot;, line 385, in share_memory_ self.storage().share_memory_() File &quot;/app/.venv/lib/python3.9/site-packages/torch/storage.py&quot;, line 143, in share_memory_ self._share_filename_() RuntimeError: std::exception at /pytorch/torch/lib/libshm/core.cpp:99 </code></pre> <p>I understand that I need to give an additional RW access to some directories but I can't figure out to which directories. Could you help me, how I can find these directories? Of course there is a RW access to /dev/shm, I even can see that pytorch creates files there but then crashes with above error.</p> <p>I'm using pytroch 1.8.1.</p>
<python><docker><pytorch>
2023-12-22 09:56:32
1
695
Tipok
77,702,581
16,436,095
How to send .xml file with correct name using as2?
<p>I have a partner with whom we exchange .edi messages using the as2 protocol.</p> <p>Now we need to switch to messaging in the .xml format. Moreover, my partner wants the files to have the correct names.</p> <p>I use my own library (based on pyas2lib). Judging by the information I found on the internet, I need to change the message headers. I changed &quot;Content-Disposition&quot; to &quot;attachment; filename=my_file.xml &quot;, added the parameter &quot;name&quot; = my_file.xml, changed the type to &quot;application/xml&quot;. But all to no avail - the file content is displayed correctly, but its name looks like a random set of characters.</p> <p>Is there any way I can send a file with the correct name? If so, how do I do it? Should the partner specify any settings for themselves?</p> <p>I will be glad of any help on this issue and will try to answer any questions that arise.</p>
<python><xml><edi>
2023-12-22 08:44:46
1
370
maskalev
77,702,579
11,038,017
Cannot add data to a ComplexField using Python SDK for Azure AI Search
<p>I want to upload a payload with a nested dictionary to Azure AI Search index. I am using a ComplexField in the index for a nested dictionary in my payload. The nested dictionary is not being recognized by the index and I get a null-error. Here is my code:</p> <pre><code> ComplexField, CorsOptions, SearchIndex, ScoringProfile, SearchFieldDataType, SimpleField, SearchableField, ) request_example = { &quot;id&quot;: &quot;1&quot;, &quot;text&quot;: &quot;bla&quot;, &quot;payload&quot;: { &quot;processId&quot;: &quot;00665&quot;, &quot;color&quot;: &quot;green&quot; } } # Create a search index index_client = SearchIndexClient(endpoint=service_endpoint, credential=credential) fields = [ SimpleField(name=&quot;id&quot;, type=SearchFieldDataType.String, key=True, sortable=True, filterable=True, facetable=True), SearchableField(name=&quot;text&quot;, type=SearchFieldDataType.String), ComplexField( name=&quot;payload&quot;, fields=[ SimpleField(name=&quot;processId&quot;, type=SearchFieldDataType.String), SimpleField(name=&quot;color&quot;, type=SearchFieldDataType.String), ], collection=True, ) ] # Configure the vector search configuration vector_search = VectorSearch( algorithms=[ HnswAlgorithmConfiguration( name=&quot;myHnsw&quot;, kind=VectorSearchAlgorithmKind.HNSW, parameters=HnswParameters( m=4, ef_construction=400, ef_search=500, metric=VectorSearchAlgorithmMetric.COSINE, ) ), ], profiles=[ VectorSearchProfile( name=&quot;myHnswProfile&quot;, algorithm_configuration_name=&quot;myHnsw&quot;, ), ], ) semantic_config = SemanticConfiguration( name=&quot;my-semantic-config&quot;, prioritized_fields=SemanticPrioritizedFields( # title_field=SemanticField(field_name=&quot;title&quot;), # keywords_fields=[SemanticField(field_name=&quot;color&quot;)], content_fields=[SemanticField(field_name=&quot;text&quot;)] ) ) # Create the semantic settings with the configuration semantic_search = SemanticSearch(configurations=[semantic_config]) cors_options = CorsOptions(allowed_origins=[&quot;*&quot;], max_age_in_seconds=60) from typing import List scoring_profiles: List[ScoringProfile] = [] # Create the search index with the semantic settings index = SearchIndex(name=&quot;complex_field_test&quot;, fields=fields, vector_search=vector_search, semantic_search=semantic_search,scoring_profiles=scoring_profiles, cors_options=cors_options) result = index_client.create_or_update_index(index) print(f'{result.name} created') # Upload some documents to the index search_client = SearchClient(endpoint=service_endpoint, index_name=&quot;complex_field_test&quot;, credential=credential) result = search_client.upload_documents([request_example]) print(f&quot;Uploaded {len(documents)} documents&quot;) </code></pre> <p>And the error I get:</p> <p><code>The request is invalid. Details: A null value was found for the property named 'payload', which has the expected type 'Collection(search.complex.payload)[Nullable=False]'. The expected type 'Collection(search.complex.payload)[Nullable=False]' does not allow null values.</code></p> <p>So, as I understand the nested dictionary &quot;payload&quot; is not being recognized and appears like empty, although the sub-fields are registered in the index and have no null values. Can you help me with this problem? How to add data to a ComplexField?</p>
<python><azure><indexing><azure-cognitive-search>
2023-12-22 08:44:44
2
333
Irina Kärkkänen
77,702,504
3,364,871
pydantic: exclude computed field from dump
<p>In pydantic v2, the following code:</p> <pre class="lang-py prettyprint-override"><code>from __future__ import annotations import pydantic from pprint import pprint class System(pydantic.BaseModel): id: int name: str subsystems: list[System] | None = None @pydantic.computed_field() @property def computed(self) -&gt; str: return self.name.upper() systems = System( id=1, name=&quot;Main system&quot;, subsystems=[ System(id=2, name=&quot;Subsystem A&quot;), System(id=3, name=&quot;Subsystem B&quot;), ], ) pprint(systems.model_dump(), indent=2) </code></pre> <p>prints:</p> <pre class="lang-py prettyprint-override"><code>{ 'computed': 'MAIN SYSTEM', 'id': 1, 'name': 'Main system', 'subsystems': [ { 'computed': 'SUBSYSTEM A', 'id': 2, 'name': 'Subsystem A', 'subsystems': None}, { 'computed': 'SUBSYSTEM B', 'id': 3, 'name': 'Subsystem B', 'subsystems': None}]} </code></pre> <p>I want to exclude the computed field <code>computed</code>.</p> <pre><code>pprint(systems.model_dump(exclude={'computed': True}), indent=2) </code></pre> <p>prints only root element without <code>computed</code>:</p> <pre class="lang-py prettyprint-override"><code>{ 'id': 1, 'name': 'Main system', 'subsystems': [ { 'computed': 'SUBSYSTEM A', 'id': 2, 'name': 'Subsystem A', 'subsystems': None}, { 'computed': 'SUBSYSTEM B', 'id': 3, 'name': 'Subsystem B', 'subsystems': None}]} </code></pre> <p>How to exclude computed field (e.g. <code>computed</code>) from dump?</p> <p>I want to serialize via <code>.model_dump()</code> because:</p> <ul> <li>I have many models and models those include <code>System</code> are serialized via <code>.model_dump()</code> method as well.</li> <li><code>.model_dump()</code> has some useful parameters like <code>exclude_defaults</code>, <code>by_alias</code> and more. I use them as well.</li> </ul>
<python><pydantic><pydantic-v2>
2023-12-22 08:28:20
2
5,735
Maxim Suslov
77,702,135
268,581
F8 the first time evaluates line in PowerShell, not in Python
<h1>Demonstration of Issue</h1> <p>I open a new python file:</p> <pre><code>code -n C:\temp\test-a.py </code></pre> <p>The contents of the file:</p> <p><a href="https://i.sstatic.net/2j4q7.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2j4q7.png" alt="enter image description here" /></a></p> <p>If I move the cursor to the line with <code>10</code> on it and press <code>F8</code> I see the following in the terminal window:</p> <p><a href="https://i.sstatic.net/kUCON.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/kUCON.png" alt="enter image description here" /></a></p> <p>Note that the <code>10</code> wasn't evaluated in Python, but in PowerShell.</p> <p>If I hit <code>F8</code> again on that line:</p> <p><a href="https://i.sstatic.net/jagdl.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/jagdl.png" alt="enter image description here" /></a></p> <p>now it's evaluated in Python.</p> <h1>Question</h1> <p>Is this a bug? Shouldn't the initial <code>F8</code> cause the line to be evaluated in Python, not PowerShell?</p> <h1>Misc</h1> <p><code>Help: About</code>:</p> <p><a href="https://i.sstatic.net/PYl7v.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/PYl7v.png" alt="enter image description here" /></a></p> <h1>Debugging info</h1> <p>After enabling <code>Developer: Toggle Keyboard Shortcuts Troubleshooting</code>, and pressing <code>F8</code>, the following is generated in the <code>OUTPUT</code> window:</p> <pre><code>2023-12-22 06:58:38.027 [info] [KeybindingService]: | Resolving F8 2023-12-22 06:58:38.028 [info] [KeybindingService]: \ From 5 keybinding entries, matched python.execSelectionInTerminal, when: editorTextFocus &amp;&amp; !findInputFocussed &amp;&amp; !jupyter.ownsSelection &amp;&amp; !notebookEditorFocused &amp;&amp; !replaceInputFocussed &amp;&amp; editorLangId == 'python', source: user. 2023-12-22 06:58:38.028 [info] [KeybindingService]: / Received keydown event - modifiers: [], code: F8, keyCode: 119, key: F8 2023-12-22 06:58:38.029 [info] [KeybindingService]: | Converted keydown event - modifiers: [], code: F8, keyCode: 66 ('F8') 2023-12-22 06:58:38.030 [info] [KeybindingService]: | Resolving F8 2023-12-22 06:58:38.030 [info] [KeybindingService]: \ From 5 keybinding entries, matched python.execSelectionInTerminal, when: editorTextFocus &amp;&amp; !findInputFocussed &amp;&amp; !jupyter.ownsSelection &amp;&amp; !notebookEditorFocused &amp;&amp; !replaceInputFocussed &amp;&amp; editorLangId == 'python', source: user. 2023-12-22 06:58:38.031 [info] [KeybindingService]: + Invoking command python.execSelectionInTerminal. 2023-12-22 06:58:40.678 [error] TextModelPart is disposed!: Error: TextModelPart is disposed! at d.g (vscode-file://vscode-app/c:/Users/dharm/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/workbench.desktop.main.js:121:22451) at d.getWordAtPosition (vscode-file://vscode-app/c:/Users/dharm/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/workbench.desktop.main.js:631:119008) at W.getWordAtPosition (vscode-file://vscode-app/c:/Users/dharm/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/workbench.desktop.main.js:736:9056) at k.h (vscode-file://vscode-app/c:/Users/dharm/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/workbench.desktop.main.js:760:68470) at new $ (vscode-file://vscode-app/c:/Users/dharm/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/workbench.desktop.main.js:760:68345) at new k (vscode-file://vscode-app/c:/Users/dharm/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/workbench.desktop.main.js:760:69207) at D (vscode-file://vscode-app/c:/Users/dharm/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/workbench.desktop.main.js:760:69734) at O.G (vscode-file://vscode-app/c:/Users/dharm/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/workbench.desktop.main.js:760:74294) at O.F (vscode-file://vscode-app/c:/Users/dharm/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/workbench.desktop.main.js:760:74091) at new O (vscode-file://vscode-app/c:/Users/dharm/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/workbench.desktop.main.js:760:70761) at q (vscode-file://vscode-app/c:/Users/dharm/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/workbench.desktop.main.js:760:75166) at u.value (vscode-file://vscode-app/c:/Users/dharm/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/workbench.desktop.main.js:760:75311) at f.y (vscode-file://vscode-app/c:/Users/dharm/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/workbench.desktop.main.js:87:1902) at f.z (vscode-file://vscode-app/c:/Users/dharm/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/workbench.desktop.main.js:87:1972) at f.fire (vscode-file://vscode-app/c:/Users/dharm/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/workbench.desktop.main.js:87:2188) at x.setModel (vscode-file://vscode-app/c:/Users/dharm/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/workbench.desktop.main.js:744:400) at k.setInput (vscode-file://vscode-app/c:/Users/dharm/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/workbench.desktop.main.js:2396:11447) at async k.setInput (vscode-file://vscode-app/c:/Users/dharm/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/workbench.desktop.main.js:2400:3886) </code></pre> <h1>Updated vscode</h1> <pre><code>Version: 1.84.2 (user setup) Commit: 1a5daa3a0231a0fbba4f14db7ec463cf99d7768e Date: 2023-11-09T10:51:52.184Z Electron: 25.9.2 ElectronBuildId: 24603566 Chromium: 114.0.5735.289 Node.js: 18.15.0 V8: 11.4.183.29-electron.0 OS: Windows_NT x64 10.0.22621 </code></pre> <h1>First press of <code>F8</code></h1> <pre><code>2023-12-22 19:29:15.355 [info] [KeybindingService]: | Resolving F8 2023-12-22 19:29:15.356 [info] [KeybindingService]: \ From 5 keybinding entries, matched python.execSelectionInTerminal, when: editorTextFocus &amp;&amp; !findInputFocussed &amp;&amp; !jupyter.ownsSelection &amp;&amp; !notebookEditorFocused &amp;&amp; !replaceInputFocussed &amp;&amp; editorLangId == 'python', source: user. 2023-12-22 19:29:15.357 [info] [KeybindingService]: / Received keydown event - modifiers: [], code: F8, keyCode: 119, key: F8 2023-12-22 19:29:15.357 [info] [KeybindingService]: | Converted keydown event - modifiers: [], code: F8, keyCode: 66 ('F8') 2023-12-22 19:29:15.358 [info] [KeybindingService]: | Resolving F8 2023-12-22 19:29:15.359 [info] [KeybindingService]: \ From 5 keybinding entries, matched python.execSelectionInTerminal, when: editorTextFocus &amp;&amp; !findInputFocussed &amp;&amp; !jupyter.ownsSelection &amp;&amp; !notebookEditorFocused &amp;&amp; !replaceInputFocussed &amp;&amp; editorLangId == 'python', source: user. 2023-12-22 19:29:15.360 [info] [KeybindingService]: + Invoking command python.execSelectionInTerminal. </code></pre> <p>Terminal output:</p> <pre><code>PS C:\Users\dharm&gt; 10 10 PS C:\Users\dharm&gt; C:/Users/dharm/miniconda3/Scripts/activate PS C:\Users\dharm&gt; conda activate base PS C:\Users\dharm&gt; &amp; C:/Users/dharm/miniconda3/python.exe Python 3.10.11 | packaged by Anaconda, Inc. | (main, May 16 2023, 00:55:32) [MSC v.1916 64 bit (AMD64)] on win32 Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. &gt;&gt;&gt; </code></pre> <h1>Second press of <code>F8</code></h1> <pre><code>2023-12-22 19:30:49.235 [info] [KeybindingService]: | Resolving F8 2023-12-22 19:30:49.235 [info] [KeybindingService]: \ From 5 keybinding entries, matched python.execSelectionInTerminal, when: editorTextFocus &amp;&amp; !findInputFocussed &amp;&amp; !jupyter.ownsSelection &amp;&amp; !notebookEditorFocused &amp;&amp; !replaceInputFocussed &amp;&amp; editorLangId == 'python', source: user. 2023-12-22 19:30:49.236 [info] [KeybindingService]: / Received keydown event - modifiers: [], code: F8, keyCode: 119, key: F8 2023-12-22 19:30:49.236 [info] [KeybindingService]: | Converted keydown event - modifiers: [], code: F8, keyCode: 66 ('F8') 2023-12-22 19:30:49.237 [info] [KeybindingService]: | Resolving F8 2023-12-22 19:30:49.237 [info] [KeybindingService]: \ From 5 keybinding entries, matched python.execSelectionInTerminal, when: editorTextFocus &amp;&amp; !findInputFocussed &amp;&amp; !jupyter.ownsSelection &amp;&amp; !notebookEditorFocused &amp;&amp; !replaceInputFocussed &amp;&amp; editorLangId == 'python', source: user. 2023-12-22 19:30:49.238 [info] [KeybindingService]: + Invoking command python.execSelectionInTerminal. </code></pre> <p>Terminal output:</p> <pre><code>&gt;&gt;&gt; 10 10 &gt;&gt;&gt; </code></pre>
<python><visual-studio-code>
2023-12-22 07:01:25
1
9,709
dharmatech
77,702,109
11,279,970
Extract concatenated p tags and table tag separately into a list
<p>I have a number of p tags with table tags I am retrieving in order into a list <code>content_items</code>. I am trying to join all p tags and then, once a table is found, append what I have collected already and then parse the table as a separate item in the list. I am able to collect the tables yet for some reason I am unable to collect and join all p tags until I hit a table tag. Code so far:</p> <pre><code>from bs4 import BeautifulSoup, NavigableString import html2text converter = html2text.HTML2Text() soup = BeautifulSoup(data3, 'html.parser') content_items = [] # List to store the content items for tag in soup.descendants: content_dict = {'Title': &quot;35.23.060 - DR Zone Standards&quot;, 'Content': ''} if tag.name == &quot;p&quot;: content_dict['Content'] += converter.handle(str(tag)) elif tag.name == &quot;table&quot;: if content_dict['Content']: content_items.append(content_dict) content_dict['Content'] = converter.handle(str(tag)) content_items.append(content_dict) # Print the extracted data print(json.dumps(content_items, indent=4)) </code></pre>
<python><beautifulsoup><htmltext>
2023-12-22 06:55:38
1
508
Simon Palmer
77,701,997
2,003,079
How to display the legend over another Axes in Matplotlib?
<p>As shown in the following example, the legend for the left Axes is always occluded by the right Axes, even if I change its zorder and the clip_on property. However, the legend for the right Axes is displayed over the left Axes by default (tested in Matplotlib 3.1.3).</p> <pre><code>import matplotlib.pyplot as plt fig, (ax1, ax2) = plt.subplots(1, 2) ax1.plot([0, 1, 2], [0, 1, 0], label='Line 1') ax2.plot([0, 1, 2], [2, 1, 2], label='Line 2') legend1 = ax1.legend(bbox_to_anchor=(1.4, 0.9), loc='upper right') legend1.set_zorder(100) legend1.set_clip_on(False) legend2 = ax2.legend(bbox_to_anchor=(0.2, 0.8), loc='upper right') plt.show() </code></pre> <p><a href="https://i.sstatic.net/BVi5b.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/BVi5b.png" alt="enter image description here" /></a></p>
<python><matplotlib>
2023-12-22 06:23:29
3
6,540
herrlich10
77,701,199
7,999,936
Concatenate/bind polars dataframes in a single dictionary with names
<p>I have a dictionary created by importing data from multiple Excel sheets using <code>polars.read_excel</code>. I'd like to combine them all, by row, into a single dataframe and preserve the sheet name as a column in the new combined dataframe to record which sheet the observation came from.</p> <p>I found a solution (<a href="https://stackoverflow.com/questions/71654966/how-can-i-append-or-concatenate-two-dataframes-in-python-polars">Similar Example</a>) that does almost what I'm looking for, but the solution explicitly calls the dataframes. I'm looking for a solution similar to the R Tidyverse solution. The Tidy solution to this type of concatenation would be really simple:</p> <pre><code>df &lt;- list %&gt;% bind_rows(.id = &quot;ID&quot;) </code></pre> <p>As I understand it, the most similar Polars function to <code>bind_rows</code> would be <code>concat(how=&quot;vertical&quot;)</code>.</p> <p>Is there something like this available in Polars? Something like the following perhaps:</p> <pre><code>df = dcty.polars.concat(how=&quot;vertical&quot;) </code></pre> <p>I've found that if I convert the dictionary to a list, the <code>concat</code> function works to combine the dataframes, but then I lose the dataframe names.</p> <p>Sample Data</p> <pre class="lang-py prettyprint-override"><code>dcty = { &quot;df1&quot;: pl.DataFrame({'col1': [1, 2], 'col2': [&quot;a&quot;, &quot;b&quot;]}), &quot;df2&quot;: pl.DataFrame({'col1': [3, 4], 'col2': [&quot;c&quot;, &quot;d&quot;]}), } </code></pre> <p>Expected Output:</p> <pre><code>shape: (4, 3) ┌──────┬──────┬──────┐ │ col1 ┆ col2 ┆ sheet│ │ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ str │ ╞══════╪══════╪══════╡ │ 1 ┆ a ┆ df1 │ │ 2 ┆ b ┆ df1 │ │ 3 ┆ c ┆ df2 │ │ 4 ┆ d ┆ df2 │ └──────┴──────┴──────┘ </code></pre>
<python><python-polars>
2023-12-22 00:33:26
1
3,215
hmhensen
77,701,135
13,838,385
How can I get IronPython in C# to run a script that requires an active VENV? Is this possible?
<p>I've installed IronPython 3.4 (<a href="https://github.com/IronLanguages/ironpython3/releases/tag/v3.4.1" rel="nofollow noreferrer">https://github.com/IronLanguages/ironpython3/releases/tag/v3.4.1</a>) and I'm trying to run several font-related python scripts that depend upon an active VENV (FontTools, ftCLI, and some other packages).</p> <p>Is this even possible? I have been doing some research on IronPython, but nothing mentions virtual environments.</p> <p>Is it possible to accomplish what I need? Is there another solution that will run a script in an active VENV using C#?</p> <p>Thank you for any guidance.</p>
<python><c#><ironpython>
2023-12-22 00:06:25
1
577
fmotion1
77,701,100
13,844,017
Github self-hosted runner complains of python version -
<p>I am trying to set a GitHub self-hosted runner for my project and I keep getting the following error:</p> <blockquote> <p>Run actions/setup-python@v3<br /> Version 3.9 was not found in the local cache<br /> Error: Version 3.9 with arch x64 not found<br /> The list of all available versions can be found here: <code>https://raw.githubusercontent.com/actions/python-versions/main/versions-manifest.json</code></p> </blockquote> <p>I have to install pytorch, and so I could not use the runners provided by GitHub. The python version of the machine where the runner is installed is <code>Python 3.9.13</code>, and the operational system is <code>AlmaLinux release 9.3 (Shamrock Pampas Cat)</code>.</p> <p>I am also linking the .yaml file responsible for the workflow:</p> <pre><code>name: Python application on: push: branches: [ &quot;main&quot; ] pull_request: branches: [ &quot;main&quot; ] permissions: contents: read jobs: build: # Due to cuda constraings, I needed to set up a self-hosted runner! #runs-on: ubuntu-latest runs-on: self-hosted steps: - uses: actions/checkout@v3 - name: Set up Python 3.9 uses: actions/setup-python@v3 with: python-version: &quot;3.9&quot; cache: &quot;pip&quot; env: AGENT_TOOLSDIRECTORY: /opt/hostedtoolcache - name: Install dependencies run: | python -m pip install --upgrade pip pip install flake8 pytest # Do I need to create the full enviroment =p #conda env create -f environment.yml #conda activate flow_corrections if [ -f requirements.yml ]; then pip install -r requirements.yml; fi - name: Lint with flake8 run: | # stop the build if there are Python syntax errors or undefined names flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics - name: Test with pytest run: | pytest *.py </code></pre> <p>I know that the python version written here is 3.9, but I also tested writing 3.9.13 and I got the same error!</p> <p>I am also making available the requirements.yml for the condo environment:</p> <pre><code>name: flow_corrections channels: - conda-forge - defaults dependencies: - _libgcc_mutex=0.1=conda_forge - _openmp_mutex=4.5=2_kmp_llvm - _py-xgboost-mutex=2.0=gpu_0 - alsa-lib=1.2.8=h166bdaf_0 - attr=2.5.1=h166bdaf_1 - boost-histogram=1.4.0=py310hd41b1e2_1 - brotli=1.1.0=hd590300_1 - brotli-bin=1.1.0=hd590300_1 - bzip2=1.0.8=hd590300_5 - ca-certificates=2023.11.17=hbcca054_0 - cairo=1.16.0=hbbf8b49_1016 - certifi=2023.11.17=pyhd8ed1ab_0 - click=8.1.7=unix_pyh707e725_0 - colorama=0.4.6=pyhd8ed1ab_0 - contourpy=1.2.0=py310hd41b1e2_0 - cramjam=2.7.0=py310hcb5633a_1 - cuda-cudart=12.0.107=hd3aeb46_7 - cuda-cudart_linux-64=12.0.107=h59595ed_7 - cuda-nvrtc=12.0.76=hd3aeb46_2 - cuda-nvtx=12.0.76=h59595ed_1 - cuda-version=12.0=hffde075_2 - cudnn=8.8.0.121=h264754d_4 - cycler=0.12.1=pyhd8ed1ab_0 - dbus=1.13.6=h5008d03_3 - exceptiongroup=1.2.0=pyhd8ed1ab_0 - expat=2.5.0=hcb278e6_1 - fastparquet=2023.10.1=py310h1f7b6fc_0 - filelock=3.13.1=pyhd8ed1ab_0 - font-ttf-dejavu-sans-mono=2.37=hab24e00_0 - font-ttf-inconsolata=3.000=h77eed37_0 - font-ttf-source-code-pro=2.038=h77eed37_0 - font-ttf-ubuntu=0.83=h77eed37_1 - fontconfig=2.14.2=h14ed4e7_0 - fonts-conda-ecosystem=1=0 - fonts-conda-forge=1=0 - fonttools=4.46.0=py310h2372a71_0 - freetype=2.12.1=h267a509_2 - fsspec=2023.12.1=pyhca7485f_0 - gettext=0.21.1=h27087fc_0 - glib=2.78.3=hfc55251_0 - glib-tools=2.78.3=hfc55251_0 - gmp=6.3.0=h59595ed_0 - gmpy2=2.1.2=py310h3ec546c_1 - graphite2=1.3.13=h58526e2_1001 - gst-plugins-base=1.22.3=h938bd60_1 - gstreamer=1.22.3=h977cf35_1 - harfbuzz=7.3.0=hdb3a94d_0 - hep_ml=0.7.2=pyhd8ed1ab_0 - hist=2.7.2=ha770c72_1 - hist-base=2.7.2=pyhd8ed1ab_1 - histoprint=2.4.0=pyhd8ed1ab_0 - icu=72.1=hcb278e6_0 - iminuit=2.24.0=py310hc6cd4ac_0 - iniconfig=2.0.0=pyhd8ed1ab_0 - jinja2=3.1.2=pyhd8ed1ab_1 - joblib=1.3.2=pyhd8ed1ab_0 - keyutils=1.6.1=h166bdaf_0 - kiwisolver=1.4.5=py310hd41b1e2_1 - krb5=1.20.1=h81ceb04_0 - lame=3.100=h166bdaf_1003 - lcms2=2.15=h7f713cb_2 - ld_impl_linux-64=2.40=h41732ed_0 - lerc=4.0.0=h27087fc_0 - libabseil=20230802.1=cxx17_h59595ed_0 - libblas=3.9.0=20_linux64_openblas - libbrotlicommon=1.1.0=hd590300_1 - libbrotlidec=1.1.0=hd590300_1 - libbrotlienc=1.1.0=hd590300_1 - libcap=2.69=h0f662aa_0 - libcblas=3.9.0=20_linux64_openblas - libclang=16.0.6=default_hb11cfb5_3 - libclang13=16.0.6=default_ha2b6cf4_3 - libcublas=12.0.1.189=hd3aeb46_3 - libcufft=11.0.0.21=hd3aeb46_2 - libcups=2.3.3=h36d4200_3 - libcurand=10.3.1.50=hd3aeb46_1 - libcusolver=11.4.2.57=hd3aeb46_2 - libcusparse=12.0.0.76=hd3aeb46_2 - libdeflate=1.19=hd590300_0 - libedit=3.1.20191231=he28a2e2_2 - libevent=2.1.12=hf998b51_1 - libexpat=2.5.0=hcb278e6_1 - libffi=3.4.2=h7f98852_5 - libflac=1.4.3=h59595ed_0 - libgcc-ng=13.2.0=h807b86a_3 - libgcrypt=1.10.3=hd590300_0 - libgfortran-ng=13.2.0=h69a702a_3 - libgfortran5=13.2.0=ha4646dd_3 - libglib=2.78.3=h783c2da_0 - libgpg-error=1.47=h71f35ed_0 - libhwloc=2.9.3=default_h554bfaf_1009 - libiconv=1.17=h166bdaf_0 - libjpeg-turbo=2.1.5.1=hd590300_1 - liblapack=3.9.0=20_linux64_openblas - libllvm16=16.0.6=h5cf9203_2 - libmagma=2.7.2=h173bb3b_1 - libmagma_sparse=2.7.2=h173bb3b_1 - libnsl=2.0.1=hd590300_0 - libnvjitlink=12.0.76=hd3aeb46_2 - libogg=1.3.4=h7f98852_1 - libopenblas=0.3.25=pthreads_h413a1c8_0 - libopus=1.3.1=h7f98852_1 - libpng=1.6.39=h753d276_0 - libpq=15.3=hbcd7760_1 - libprotobuf=4.24.4=hf27288f_0 - libsndfile=1.2.2=hc60ed4a_1 - libsqlite=3.44.2=h2797004_0 - libstdcxx-ng=13.2.0=h7e041cc_3 - libsystemd0=255=h3516f8a_0 - libtiff=4.6.0=h29866fb_1 - libuuid=2.38.1=h0b41bf4_0 - libuv=1.46.0=hd590300_0 - libvorbis=1.3.7=h9c3ff4c_0 - libwebp-base=1.3.2=hd590300_0 - libxcb=1.15=h0b41bf4_0 - libxgboost=1.7.6=cuda120_h75debf4_6 - libxkbcommon=1.6.0=h5d7e998_0 - libxml2=2.11.5=h0d562d8_0 - libzlib=1.2.13=hd590300_5 - llvm-openmp=17.0.6=h4dfa4b3_0 - lz4-c=1.9.4=hcb278e6_0 - magma=2.7.2=h51420fd_1 - markupsafe=2.1.3=py310h2372a71_1 - matplotlib=3.8.2=py310hff52083_0 - matplotlib-base=3.8.2=py310h62c0568_0 - mkl=2022.2.1=h84fe81f_16997 - mpc=1.3.1=hfe3b2da_0 - mpfr=4.2.1=h9458935_0 - mpg123=1.32.3=h59595ed_0 - mplhep=0.3.31=pyhd8ed1ab_0 - mplhep_data=0.0.3=pyhd8ed1ab_0 - mpmath=1.3.0=pyhd8ed1ab_0 - munkres=1.1.4=pyh9f0ad1d_0 - mysql-common=8.0.33=hf1915f5_6 - mysql-libs=8.0.33=hca2cd23_6 - nccl=2.19.4.1=h3a97aeb_0 - ncurses=6.4=h59595ed_2 - networkx=3.2.1=pyhd8ed1ab_0 - nspr=4.35=h27087fc_0 - nss=3.95=h1d7d5a4_0 - numpy=1.26.2=py310hb13e2d6_0 - openjpeg=2.5.0=h488ebb8_3 - openssl=3.1.4=hd590300_0 - packaging=23.2=pyhd8ed1ab_0 - pandas=2.1.3=py310hcc13569_0 - pcre2=10.42=hcad00b1_0 - pillow=10.0.1=py310h29da1c1_1 - pip=23.3.1=pyhd8ed1ab_0 - pixman=0.42.2=h59595ed_0 - pluggy=1.3.0=pyhd8ed1ab_0 - ply=3.11=py_1 - pthread-stubs=0.4=h36c2ea0_1001 - pulseaudio-client=16.1=hb77b528_5 - py-xgboost=1.7.6=cuda120_py310h6bc6e9e_6 - pyparsing=3.1.1=pyhd8ed1ab_0 - pyqt=5.15.9=py310h04931ad_5 - pyqt5-sip=12.12.2=py310hc6cd4ac_5 - pytest=7.4.3=pyhd8ed1ab_0 - python=3.10.13=hd12c33a_0_cpython - python-dateutil=2.8.2=pyhd8ed1ab_0 - python-tzdata=2023.3=pyhd8ed1ab_0 - python_abi=3.10=4_cp310 - pytorch=2.1.0=cuda120py310ha3a684c_301 - pytz=2023.3.post1=pyhd8ed1ab_0 - pyyaml=6.0.1=py310h5eee18b_0 - qt-main=5.15.8=h01ceb2d_12 - readline=8.2=h8228510_1 - scikit-learn=1.3.2=py310h1fdf081_2 - scipy=1.11.4=py310hb13e2d6_0 - setuptools=68.2.2=pyhd8ed1ab_0 - sip=6.7.12=py310hc6cd4ac_0 - six=1.16.0=pyh6c4a22f_0 - sleef=3.5.1=h9b69904_2 - sympy=1.12=pypyh9d50eac_103 - tbb=2021.11.0=h00ab1b0_0 - threadpoolctl=3.2.0=pyha21a80b_0 - tk=8.6.13=noxft_h4845f30_101 - toml=0.10.2=pyhd8ed1ab_0 - tomli=2.0.1=pyhd8ed1ab_0 - tornado=6.3.3=py310h2372a71_1 - typing-extensions=4.8.0=hd8ed1ab_0 - typing_extensions=4.8.0=pyha770c72_0 - tzdata=2023c=h71feb2d_0 - uhi=0.4.0=pyhd8ed1ab_0 - unicodedata2=15.1.0=py310h2372a71_0 - wheel=0.42.0=pyhd8ed1ab_0 - xcb-util=0.4.0=hd590300_1 - xcb-util-image=0.4.0=h8ee46fc_1 - xcb-util-keysyms=0.4.0=h8ee46fc_1 - xcb-util-renderutil=0.3.9=hd590300_1 - xcb-util-wm=0.4.1=h8ee46fc_1 - xgboost=1.7.6=cuda120_py310h6bc6e9e_6 - xkeyboard-config=2.40=hd590300_0 - xorg-kbproto=1.0.7=h7f98852_1002 - xorg-libice=1.1.1=hd590300_0 - xorg-libsm=1.2.4=h7391055_0 - xorg-libx11=1.8.7=h8ee46fc_0 - xorg-libxau=1.0.11=hd590300_0 - xorg-libxdmcp=1.1.3=h7f98852_0 - xorg-libxext=1.3.4=h0b41bf4_2 - xorg-libxrender=0.9.11=hd590300_0 - xorg-renderproto=0.11.1=h7f98852_1002 - xorg-xextproto=7.3.0=h0b41bf4_1003 - xorg-xf86vidmodeproto=2.3.1=h7f98852_1002 - xorg-xproto=7.0.31=h7f98852_1007 - xz=5.2.6=h166bdaf_0 - yaml=0.2.5=h7f98852_2 - zlib=1.2.13=hd590300_5 - zstd=1.5.5=hfc55251_0 - pip: - zuko==1.0.1 prefix: /home/home1/institut_3a/daumann/.conda/envs/flow_corrections </code></pre> <p>I cannot really see what is wrong, and I don't have much experience with this, so I would appreciate any help! Thanks in advance.</p>
<python><github><continuous-integration><github-actions>
2023-12-21 23:52:32
1
373
Matthew D.
77,701,070
11,037,602
How to split a tree in branches based on depth
<p>I'm unsure if this is a hard problem, or I'm just way too rusty in DSA, but I can't find a way to write a function to split a tree in multiple branches, based on an arbitrary value of depth.</p> <p><strong>What I mean is:</strong> I want to write a function <code>split_tree</code> that receives AT LEAST, the parameters: <code>tree</code> and <code>level</code> the latter being the level of depth in the tree. The function should explore the tree until it reaches the determined level and then returns a copy of that branch, with all the unrelated nodes trimmed. Repeat it until all nodes of the same level are done.</p> <p>Consider the Tree in the image bellow.</p> <p><a href="https://i.sstatic.net/sXpkI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/sXpkI.png" alt="Tree" /></a></p> <p>The <code>level</code> determines which nodes are the base nodes (or relevant nodes) for splitting the branches. Considering the ROOT node is 0, if <code>level=1</code> the base nodes are <strong>B, C and D</strong>, if <code>level=2</code> the base nodes would be <strong>E, F, C, H and I</strong>.</p> <p>So, calling <code>split_tree(tree, level=1)</code> would return three different branches:</p> <pre><code>[ROOT, B, [E, F]] [ROOT, C] [ROOT, D, [H, I, [J, K]]] </code></pre> <p>While calling <code>split_tree(tree, level=2)</code> would return five different branches:</p> <pre><code>[ROOT, B, E] [ROOT, B, F] [ROOT, C] [ROOT, D, H] [ROOT, D, I, [J, K]] </code></pre> <p>Notice that</p> <ul> <li>If a branch doesn't reach the depth of <code>level</code> it returns a branch that is as dept as it could be. E.g: <strong>[ROOT, C]</strong></li> <li>If a base node has child nodes, they are included in the branch. E.g: <strong>[ROOT, D, I, [J, K]]</strong></li> <li>All siblings of the base node and other unrelated branches got trimmed.</li> </ul> <p>I specially appreciate any help in pseudo code or python, but feel free to use whatever.</p>
<python><algorithm><data-structures><tree><logic>
2023-12-21 23:42:11
2
2,081
Justcurious
77,701,068
1,232,087
Referenced Notebook not found
<p>I'm given a <code>notebook</code> to run in <code>Azure Databricks</code>. I imported the notebook to my user folder <code>Workspace\Users\MyUserName@CompanyName.com</code>. Following command in the notebook gives the error shown below.</p> <p><strong>Question</strong>: Where is the referenced notebook <code>qc_notebook</code> located in Databricks?</p> <p>My notebook that I am running following command on is at <code>Workspace\Users\MyUserName@CompanyName.com</code> location in Databricks:</p> <pre><code>%run ../../qc_functions </code></pre> <p>Error:</p> <blockquote> <p>Notebook not found: qc_functions. Notebooks can be specified via a relative path (./Notebook or ../folder/Notebook) or via an absolute path (/Abs/Path/to/Notebook). Make sure you are specifying the path correctly. <strong>Stacktrace</strong>: /Users/MyUserName@CompanyName.com/myNotebook: python</p> </blockquote>
<python><jupyter-notebook><databricks><azure-databricks><azure-notebooks>
2023-12-21 23:41:34
1
24,239
nam
77,700,850
15,163,418
How to prevent python from auto closing the terminal
<p>I created a CLI with python and built it as a exe with pyinstaller. When I double click the exe the terminal opens and if my code encounters few condition it will display some warning message and do <code>sys.exit()</code>. on <code>sys.exit()</code> the terminal closes automatically. So I cant even read that warning message. It also happens with <code>os.system('cls')</code>. But when I open an empty terminal and then run my exe (/my_app&gt;./my_app.exe) it works fine and <code>os.system('cls')</code> works too. It only happens when I double click the exe to run</p> <pre class="lang-py prettyprint-override"><code>if some_condition == False: sys.exit() </code></pre>
<python><terminal><command-line-interface><pyinstaller>
2023-12-21 22:31:07
1
541
Raghavan Vidhyasagar
77,700,822
443,854
Numpy large square matrix with repetition
<p>I need to construct a large square <code>N*M</code> by <code>N*M</code> matrix to be used with <code>numpy.matmul</code>. There is a lot of repetition, such that the elements of each <code>M</code> by <code>M</code> square segment are repeated <code>N*N</code> times. To illustrate, for <code>M=2</code> and <code>N=3</code>:</p> <pre><code>s = np.array([[1,2], [3,4]]) S = np.array([1,2,1,2,1,2], [3,4,3,4,3,4], [1,2,1,2,1,2], [3,4,3,4,3,4], [1,2,1,2,1,2], [3,4,3,4,3,4],) </code></pre> <p>The idea here is to construct <code>S</code> as a view of <code>s</code>, in order to use less memory. This is my attempt at doing it using a combination of <code>broadcast_to</code> and <code>reshape</code>. Essentially, I am trying to &quot;broadcast&quot; a <code>M x M</code> matrix to a <code>N*M x N*M</code> one.</p> <pre><code>import numpy N = 10000 M = 10 w = numpy.random.rand(N*M, 1) s = numpy.random.rand(M, M) S4d = numpy.broadcast_to(s, shape=(N, N, M, M)) S = S4d.reshape(N*M, N*M) </code></pre> <p>Output:</p> <pre><code>numpy.core._exceptions._ArrayMemoryError: Unable to allocate 74.5 GiB for an array with shape (10000, 10000, 10, 10) and data type float64 </code></pre> <p>Is there a way to construct matrix <code>S</code> as described above?</p> <p>One workaround would be to write a function to do matrix multiplication for this case. But considering real-life values of <code>M ~ 1e3, N ~ 1e4</code>, I expect <code>w' * S * w</code> to take <code>O(1e14)</code> operations which would be slow.</p> <p><strong>Edit</strong> I realized that <code>w' * S * w</code> can be broken down into multiplications of slices of <code>w</code> with <code>s</code>. The whole product computes in just over 1 second. However, I would still be curious to know if there is a way to construct <code>S</code> as a view of <code>s</code>.</p>
<python><numpy>
2023-12-21 22:20:57
1
7,543
user443854
77,700,760
11,154,841
Can a Named Entity Recognition (NER) spaCy model or any code like an entity ruler around it catch my new further date patterns also as DATE entities?
<h2>Anonymization of entities found by a NER model</h2> <p>I try to anonymize files by means of a NER model for German text that sometimes may have a few English words. If I take spaCy NER models for German and English like de_core_news_sm and en_core_web_sm, they find town names or persons, and at least the English model finds &quot;Dezember 2022&quot;, but it does not find the full date like &quot;15. Dezember 2022&quot;.</p> <h2>Changing the entity recognition</h2> <p>I cannot change the matches of the model. I thought I could take an entity ruler to change the NER model, but the NER model seems to be fixed, and I do not know how my own entity ruler can outweigh the spaCy NER model, and also, how I can get any entity ruler to work at all, even if I disable the NER model. I shifted the entity ruler before the NER model in the spaCy pipeline, but I do not see any new replacements in the output.</p> <p>Easy example, mainly from the main spaCy guide at <a href="https://spacy.io/usage/rule-based-matching#entityruler-usage" rel="nofollow noreferrer">Using the entity ruler</a>:</p> <pre class="lang-py prettyprint-override"><code>from spacy.lang.de import German nlp = German() ruler = nlp.add_pipe(&quot;entity_ruler&quot;) patterns = [ {&quot;label&quot;: &quot;DATE&quot;, &quot;pattern&quot;: [ {&quot;lower&quot;: {&quot;regex&quot;: &quot;(?:0?[1-9]|[12][0-9]|3[01])[\.\s]{1,2}?(jan(?:uar)?|feb(?:ruar)?|mär(?:z)?|apr(?:il)?|mai|jun(?:i)?|jul(?:i)?|aug(?:ust)?|sep(?:t(?:ember)?)?|okt(?:ober)?|nov(?:ember)?|dez(?:ember)?)\.?\s?['`]?\d{0,4}&quot;}}, {&quot;shape&quot;: {&quot;regex&quot;: &quot;(?:0?[1-9]|[12][0-9]|3[01])[\.\s]{1,2}?(0?[1-9]|1[0-2])\.?\s?['`]?\d{0,4}&quot;}}, {&quot;lower&quot;: {&quot;regex&quot;: &quot;(?:jan(?:uar)?|feb(?:ruar)?|mär(?:z)?|apr(?:il)?|mai|jun(?:i)?|jul(?:i)?|aug(?:ust)?|sep(?:t(?:ember)?)?|okt(?:ober)?|nov(?:ember)?|dez(?:ember)?)\.?\s?['`]?\d{2,4}&quot;}}, {&quot;lower&quot;: {&quot;regex&quot;: &quot;(?:januar|feb(?:ruar)?|mär(?:z)?|apr(?:il)?|mai|jun(?:i)?|jul(?:i)?|aug(?:ust)?|sep(?:t(?:ember)?)?|okt(?:ober)?|nov(?:ember)?|dez(?:ember)?\.?)&quot;}}, {&quot;shape&quot;: &quot;dd&quot;}, {&quot;TEXT&quot;: {&quot;in&quot;: [&quot;15&quot;]}} ]}, {&quot;label&quot;: &quot;ORG1&quot;, &quot;pattern&quot;: {&quot;LOWER&quot;: &quot;apple&quot;}}, {&quot;label&quot;: &quot;GPE1&quot;, &quot;pattern&quot;: {&quot;LOWER&quot;: &quot;san&quot;}}, {&quot;label&quot;: &quot;DATE1&quot;, &quot;pattern&quot;: {&quot;TEXT&quot;: [{&quot;regex&quot;: &quot;^(?:0?[1-9]|[12][0-9]|3[01])$&quot;}]}} ] ruler.add_patterns(patterns) # Taking the German Dezember here for the test of the German RegEx doc = nlp(&quot;Apple eröffnet ein Büro in San Francisco am 15. Dezember 2022.&quot;) </code></pre> <p>Output:</p> <pre class="lang-bash prettyprint-override"><code>[] </code></pre> <h3>Question</h3> <p>Can I code around a Named Entity Recognition (NER) spaCy model to catch further date patterns also as DATE entities so that this will outweigh the choice of the NER model?</p> <p>The aim is that the full &quot;15. Dezember 2022&quot; is found as one DATE entity.</p> <hr /> <h2>PS</h2> <h3>Duplicate?</h3> <p>I found <a href="https://stackoverflow.com/q/67906945/11154841">spacy how to add patterns to existing Entity ruler?</a> that tells me to retrain the custom entity ruler and do not add patterns since the questioner has trained the NER model:</p> <blockquote> <p>I have an existing trained custom NER model with NER and Entity Ruler pipes. I want to update and retrain this existing pipeline.</p> </blockquote> <p>The question is &quot;how to add patterns to existing Entity ruler?&quot; asks more or less the same as I do here. But since the NER model is a custom one, the answers tell you to retrain the NER model with those patterns. That is why this question here is hopefully not a duplicate: I cannot retrain the NER model since it is a ready-made download from spaCy.</p> <h3>Catastrophic forgetting?</h3> <p>Mind that the answers there tell you not to ever add an entity ruler at all to the NER model if you can retrain your NER model since it may lead to &quot;catastrophic forgetting&quot; of the already trained NER model, read there for more. If that is right, I wonder what I am doing here at all since that would mean that I cannot merge the entity recognition that the spaCy NER model is trained on with another entity ruler. I highly doubt that this is true. Why should I not be able to check a text for some patterns of some entities and then run the spaCy NER model on top of that, and then let the first found entities outweigh the second? Why should that lead to catastrophic forgetting if we speak about two models? Catastrophic forgetting means that the NER model gets retrained on only the new text that I take for the entity ruler. My new input text would be just one sentence with a date. Then, it would be easy to find out whether catastrophic forgetting happens at all. I can just run the pipeline on a sentence with more entities other than dates and see what happens. Yet, I guess that my thoughts here are wrong, so that we do not have two models, but instead one entity recognition model that is a merger of the entity ruler and the NER model. That is also how I understood the entity ruler in the first place. But even then, I can still test this on catastrophic forgetting easily: if the entity recognition gets much worse on a big file, then I know that there is catastrophic forgetting. If you ask me, this sounds too strange to be true. I doubt that the answers of the other question are right.</p>
<python><python-3.x><spacy><named-entity-recognition><spacy-3>
2023-12-21 22:02:13
1
9,916
questionto42
77,700,738
11,748,924
No space device left tensorflow docker cloud shell with buildpacks
<p>I got this error after I run this script:</p> <pre><code>#/bin/bash # Build Image pack build deepcare_image --builder gcr.io/buildpacks/builder:v1 --path . &amp;&amp; # Push to GCR gcloud auth configure-docker &amp;&amp; docker tag deepcare_image:latest gcr.io/deep-care-capstone/deepcare_image:latest &amp;&amp; docker push gcr.io/deep-care-capstone/deepcare_image:latest &amp;&amp; # Deploy to CloudRun gcloud run deploy deepcare-api --image gcr.io/deep-care-capstone/deepcare_image:latest </code></pre> <p>Returning error:</p> <pre><code>v1: Pulling from buildpacks/builder Running &quot;python3 -m pip check&quot; No broken requirements found. Adding 1/1 app layer(s) Adding layer 'buildpacksio/lifecycle:launcher' Timer: Saving deepcare_image39876... started at 2023-12-21T21:46:59Z *** Images (983d9eff9e4d): deepcare_image39876 - loading image &quot;deepcare_image39876&quot;. first error: embedded daemon response: write /layers/google.python.pip/pip/lib/python3.11/site-packages/tensorflow/libtensorflow_cc.so.2: no space left on device Timer: Saving deepcare_image39876... ran for 1m18.845016348s and ended at 2023-12-21T21:48:18Z Timer: Exporter ran for 1m34.264716144s and ended at 2023-12-21T21:48:18Z ERROR: failed to export: failed to write image to the following tags: [deepcare_image39876: loading image &quot;deepcare_image39876&quot;. first error: embedded daemon response: write /layers/google.python.pip/pip/lib/python3.11/site-packages/tensorflow/libtensorflow_cc.so.2: no space left on device] ERROR: failed to build: executing lifecycle: failed with status code: 62 </code></pre> <p>I have no idea what to do, I tried to clean VM state but it was doing nothing.</p> <p>Note that, previously it was fine when last I tried to run the script.</p> <p>Update, here is output <code>df -ah</code>:</p> <pre><code>root@cs-179510100035-default:/home/c315bsy3271/deep-care-api# df -ah Filesystem Size Used Avail Use% Mounted on overlay 114G 106G 8.1G 93% / proc 0 0 0 - /proc tmpfs 64M 0 64M 0% /dev devpts 0 0 0 - /dev/pts mqueue 0 0 0 - /dev/mqueue sysfs 0 0 0 - /sys cgroup 0 0 0 - /sys/fs/cgroup /dev/sda1 114G 106G 8.1G 93% /root /dev/disk/by-id/google-home-part1 4.8G 192M 4.4G 5% /home /dev/sda1 114G 106G 8.1G 93% /etc/hostname /dev/root 2.0G 1.1G 849M 57% /lib/modules /dev/sda1 114G 106G 8.1G 93% /etc/hosts /dev/sda1 114G 106G 8.1G 93% /etc/resolv.conf shm 64M 0 64M 0% /dev/shm /dev/sda1 114G 106G 8.1G 93% /var/config/shared-secret /dev/sda1 114G 106G 8.1G 93% /etc/ssh/keys /dev/sda1 114G 106G 8.1G 93% /var/config/tmux /dev/sda1 114G 106G 8.1G 93% /var/lib/docker /dev/sda1 114G 106G 8.1G 93% /run/google/devshell tmpfs 3.2G 808K 3.2G 1% /google/host/var/run ramfs 0 0 0 - /google/host/var/run/credentials/systemd-sysctl.service ramfs 0 0 0 - /google/host/var/run/credentials/systemd-tmpfiles-setup-dev.service ramfs 0 0 0 - /google/host/var/run/credentials/systemd-tmpfiles-setup.service ramfs 0 0 0 - /google/host/var/run/credentials/systemd-resolved.service nsfs 0 0 0 - /google/host/var/run/netns/cni-a9f3920c-2960-a1bc-b258-4c98b67f50f9 shm 64M 0 64M 0% /google/host/var/run/containerd/io.containerd.grpc.v1.cri/sandboxes/bfa4c8c06ddcd3a48047a8a7d353778eeec9c51a2f2aab919c88857c9420e449/shm nsfs 0 0 0 - /google/host/var/run/netns/cni-8bdcebbb-d416-5cd8-139c-fb7f8a214316 gcfsd 0.0K 0.0K 0.0K - /google/host/var/run/gcfsd/mnt overlay 114G 106G 8.1G 93% /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/bfa4c8c06ddcd3a48047a8a7d353778eeec9c51a2f2aab919c88857c9420e449/rootfs overlay 114G 106G 8.1G 93% /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/111311c054717bf3571411c079cf7d7b01c508957985e7eb920531035f7e53a0/rootfs shm 64M 0 64M 0% /google/host/var/run/containerd/io.containerd.grpc.v1.cri/sandboxes/02b66ae35c39a39276841a435b7641f358ff6ff8eadd8715b8ac8b4b22dc5c78/shm nsfs 0 0 0 - /google/host/var/run/netns/cni-f1b6175d-4963-4c32-f897-1ffa38f60ae7 overlay 114G 106G 8.1G 93% /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/02b66ae35c39a39276841a435b7641f358ff6ff8eadd8715b8ac8b4b22dc5c78/rootfs overlay 114G 106G 8.1G 93% /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/5c915f9007228f47a4a9f57772f195223a6482ff05ab1919f4152b4ac83c6cb5/rootfs overlay 114G 106G 8.1G 93% /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs overlay 114G 106G 8.1G 93% /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs proc 0 0 0 - /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs/proc tmpfs 64M 0 64M 0% /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs/dev devpts 0 0 0 - /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs/dev/pts mqueue 0 0 0 - /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs/dev/mqueue shm 64M 0 64M 0% /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs/dev/shm sysfs 0 0 0 - /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs/sys cgroup 0 0 0 - /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs/sys/fs/cgroup /dev/sda1 114G 106G 8.1G 93% /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs/root /dev/disk/by-id/google-home-part1 4.8G 192M 4.4G 5% /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs/home /dev/sda1 114G 106G 8.1G 93% /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs/etc/hostname /dev/root 2.0G 1.1G 849M 57% /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs/lib/modules /dev/sda1 114G 106G 8.1G 93% /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs/etc/hosts /dev/sda1 114G 106G 8.1G 93% /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs/etc/resolv.conf /dev/sda1 114G 106G 8.1G 93% /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs/var/config/shared-secret /dev/sda1 114G 106G 8.1G 93% /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs/etc/ssh/keys /dev/sda1 114G 106G 8.1G 93% /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs/var/config/tmux /dev/sda1 114G 106G 8.1G 93% /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs/var/lib/docker /dev/sda1 114G 106G 8.1G 93% /google/host/var/run/containerd/io.containerd.runtime.v2.task/k8s.io/d6244b37b4ef9d4c2cd59d5d210159860933baa5acf24cab5c2dc7c11ca139e5/rootfs/run/google/devshell none 0 0 0 - /sys/kernel/security </code></pre>
<python><docker><tensorflow><google-cloud-platform>
2023-12-21 21:56:32
1
1,252
Muhammad Ikhwan Perwira
77,700,603
2,440,517
Generate a CSV object without a file (in python)
<p>So, I need to generate a CSV object just to POST it to an API (part of the script). I would prefer to avoid saving the file in the server storage (even if it's a temp file) before sending it in the request.</p> <p>So far, I found the CSV file to upload is a <strong>&lt;_io.TextIOWrapper name='file.csv' mode='r' encoding='cp1252'&gt;</strong> type, but not sure how to generate it from a list of lists.</p> <pre><code>[ ['HEADER1', HEADER2], ['value1', 'value2], .... ] </code></pre> <p>Any idea is appreciated!</p>
<python><csv><generate>
2023-12-21 21:24:50
1
611
Alejandro
77,700,489
1,472,253
How to perform a conditional sort in Polars
<p>I'm performing a binary classification and I want to manually review cases where the model either made an incorrect guess or it was correct but with low confidence. I want the most confident incorrect predictions to appear first, followed by less confident predictions, followed by correct predictions sorted from least to most confident. I want to manually check these examples to see if there's a pattern to the types of examples where the model needs help. My real project involves images created using Stable Diffusion, so I can create more targeted training examples if I see patterns.</p> <p>Here's a simplified example of my data.</p> <pre><code>import polars as pl pl.DataFrame({&quot;name&quot;:[&quot;Alice&quot;, &quot;Bob&quot;, &quot;Caroline&quot;, &quot;Dutch&quot;, &quot;Emily&quot;, &quot;Frank&quot;, &quot;Gerald&quot;, &quot;Henry&quot;, &quot;Isabelle&quot;, &quot;Jack&quot;], &quot;truth&quot;:[1,0,1,0,1,0,0,1,1,0], &quot;prediction&quot;: [1,1,1,0,0,1,0,1,1,0], &quot;confidence&quot;: [0.343474,0.298461,0.420634,0.125515,0.772971,0.646964,0.833705,0.837181,0.790773,0.144983]}).with_columns( (1*(pl.col(&quot;truth&quot;) == pl.col(&quot;prediction&quot;))).alias(&quot;correct_prediction&quot;) ) </code></pre> <p>Emily should appear first because she's the highest-confidence incorrect classification. After the other wrong predictions, Dutch should appear next because he has the lowest-confidence correct guess.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>name</th> <th>truth</th> <th>prediction</th> <th>confidence</th> <th>correct_prediction</th> </tr> </thead> <tbody> <tr> <td>Emily</td> <td>1</td> <td>0</td> <td>0.772971</td> <td>0</td> </tr> <tr> <td>Frank</td> <td>0</td> <td>1</td> <td>0.646964</td> <td>0</td> </tr> <tr> <td>Bob</td> <td>0</td> <td>1</td> <td>0.298461</td> <td>0</td> </tr> <tr> <td>Dutch</td> <td>0</td> <td>0</td> <td>0.125515</td> <td>1</td> </tr> <tr> <td>Jack</td> <td>0</td> <td>0</td> <td>0.144983</td> <td>1</td> </tr> <tr> <td>Alice</td> <td>1</td> <td>1</td> <td>0.343474</td> <td>1</td> </tr> <tr> <td>Caroline</td> <td>1</td> <td>1</td> <td>0.420634</td> <td>1</td> </tr> <tr> <td>Isabelle</td> <td>1</td> <td>1</td> <td>0.790773</td> <td>1</td> </tr> <tr> <td>Gerald</td> <td>0</td> <td>0</td> <td>0.833705</td> <td>1</td> </tr> <tr> <td>Henry</td> <td>1</td> <td>1</td> <td>0.837181</td> <td>1</td> </tr> </tbody> </table> </div> <p>I'm moving from Pandas to Polars and can't figure out how to perform this sort. According to <a href="https://pola-rs.github.io/polars/py-polars/html/reference/dataframe/api/polars.DataFrame.sort.html" rel="nofollow noreferrer">the documentation</a>, you can use an expression with <code>sort()</code>, but it's not clear how I can include an if statement in the expression. I'd also be open to calculating a new sort column and then performing a simple <code>sort()</code> on that, if there's some formula that would do what I want.</p> <p>I know I could split the DataFrame into <code>correct_predictions</code> and <code>incorrect_predictions</code>, use different sorting logic on each, and then <code>concat()</code> them back together. I'm looking for something more elegant and less messy.</p>
<python><python-polars>
2023-12-21 20:55:25
2
8,467
Andrew Brēza
77,700,357
2,976,366
Google API Python Client Firebase App Distribution HTTP 400
<p>I'm trying to list my builds that I have uploaded to Firebase App Distribution with the help of the <a href="https://googleapis.github.io/google-api-python-client/docs/dyn/firebaseappdistribution_v1.html" rel="nofollow noreferrer">google-api-python-client</a> however I always get a HTTP status code 400.</p> <p>I have created a <code>service-account.json</code> with full owner rights (for testing)<br /> I have copied my <code>project_id</code> from Firebase Console.<br /> I have copied my <code>app_id</code> from Firebase Console.</p> <p>My Python script:</p> <pre class="lang-py prettyprint-override"><code>import os from google.oauth2 import service_account from googleapiclient.discovery import build from googleapiclient.errors import HttpError script_dir = os.path.dirname(os.path.abspath(__file__)) service_account_file = os.path.join(script_dir, 'service-account.json') credentials = service_account.Credentials.from_service_account_file(service_account_file) project_id = credentials.project_id app_id = &quot;1:310501947997:android:4f5183af1eddc4004eabb4&quot; service = build('firebaseappdistribution', 'v1', credentials=credentials) try: parent = f&quot;projects/{project_id}/apps/{app_id}&quot; app_releases = service.projects().apps().releases().list(parent=parent).execute() print(app_releases) except HttpError as e: print('Error response status code : {0}, reason : {1}'.format(e.status_code, e.error_details)) </code></pre> <blockquote> <p>Error response status code : 400, reason : Request contains an invalid argument.</p> </blockquote> <p>Does somebody have any pointers on what argument is invalid which is causing the HTTP 400?</p>
<python><firebase><google-api-python-client><firebase-app-distribution>
2023-12-21 20:21:06
1
6,992
timr
77,700,324
11,188,487
Pandas Removing Rows Based on Previous Row
<p>Suppose I have a Pandas dataframe with columns first_date, label, last_date, where first_date &lt; last_date for all rows. I would like to remove any row (let's call this row z) if first_date of row Z is in between first_date and last_date of <em><strong>ANY</strong></em> row above row z of the same label (not just the the row directly above it of the same label), how can I do it? DataFrame is as follows:</p> <pre><code>first_date label last_date 2023-09-11 A 2023-09-17 2023-09-11 B 2023-09-15 2023-09-20 A 2023-09-28 2023-09-17 B 2023-09-30 2023-09-30 A 2023-10-05 2023-10-03 A 2023-10-07 2023-10-05 B 2023-10-15 2023-10-19 A 2023-10-20 2023-10-10 B 2023-10-15 </code></pre> <p>the correct output should be:</p> <pre><code>first_date label last_date 2023-09-11 A 2023-09-17 2023-09-11 B 2023-09-15 2023-09-20 A 2023-09-28 2023-09-17 B 2023-09-30 2023-09-30 A 2023-10-05 2023-10-05 B 2023-10-15 2023-10-19 A 2023-10-20 </code></pre> <p>where removed rows are:</p> <pre><code>2023-10-03 A 2023-10-07 2023-10-10 B 2023-10-15 </code></pre> <p>because 2023-10-03 for label A is in between 2023-09-30 and 2023-10-05, and 2023-10-10 for label B is in between 2023-10-05 and 2023-10-15</p> <p>The dataframe is huge, more than 10,000 rows, so should avoid loops as much as possible, thank you in advance!</p>
<python><pandas><dataframe>
2023-12-21 20:15:00
4
587
atjw94
77,700,314
6,632,214
detecting named pipe reader disconnect using select.poll fails on macOS, works on Linux
<p>I want to detect on the <strong>writer</strong> (producer) end of a named pipe, when the reader (consumer) disconnects. In particular, this should work on Linux and macOS (Windows is already requires a separate method anyway, so it's out of scope here).</p> <p>The general idea of using Python's <code>select.poll()</code> has been not least shown in <a href="https://stackoverflow.com/a/28471905">answer to &quot;Detect when reader closes named pipe (FIFO)&quot;</a>. Following is a fleshed-out test (<code>pype.py</code>) that first creates a named pipe and then forks to run consumer and producer in separate processes. The consumer will connect and eventually disconnect, while the producer polls the writing end of the named pipe for the consumer disconnecting. At least that's the theory...</p> <h2>Linux</h2> <p>Running <code>python3 pype.py</code> on Linux works &quot;as advertised&quot; and expected, as the reader/consumer disconnecting is duly reported:</p> <pre><code>named pipe /tmp/pype-ewocntg9/fifo reader: start... writer: start... sleeping... reader closed waiting for writer to terminate... reader has disconnected [(3, 8)] </code></pre> <h2>macOS</h2> <p>Running <code>python3 pype.py</code> on macOS (12.x, 13.x) instead gives this:</p> <pre><code>named pipe /var/folders/...../pype-j33ergsn/fifo reader: start... writer: start... sleeping... reader closed waiting for writer to terminate... ERROR: timed out, disconnect not detected </code></pre> <p>What am I doing (holding?) wrong here? Or is macOS broken? We see the same behavior on macos 12.x as well as 13.x.</p> <h2><code>pype.py</code></h2> <pre class="lang-py prettyprint-override"><code># pype.py import os import tempfile import atexit import shutil import time import select def writer(fifoname): print(&quot;writer: start...&quot;) w = open(fifoname, 'w') poller = select.poll() poller.register(w, select.POLLERR | select.POLLHUP) poll = poller.poll(4.0*1000) if len(poll) == 0: print(&quot;ERROR: timed out, disconnect not detected&quot;) return print(&quot;reader has disconnected&quot;, poll) def reader(fifoname): print(&quot;reader: start...&quot;) r = open(fifoname, 'r') print(&quot;sleeping...&quot;) time.sleep(2.0) r.close() print(&quot;reader closed&quot;) tmpdir = tempfile.mkdtemp(prefix=&quot;pype-&quot;) fifoname = os.path.join(tmpdir, &quot;fifo&quot;) print(&quot;named pipe&quot;, fifoname) os.mkfifo(fifoname, 0o600) atexit.register(shutil.rmtree, tmpdir) childpid = os.fork() if childpid == 0: writer(fifoname) else: atexit.unregister(shutil.rmtree) reader(fifoname) print(&quot;waiting for writer to terminate...&quot;) os.waitpid(childpid, 0) </code></pre> <p>Nota bene: this is a minimalist Python-based test to show the issue, mirroring the issue first seen as part of a more complex Go module, see also <a href="https://unix.stackexchange.com/questions/764906/named-pipe-mkfifo-how-to-detect-reading-end-consumer-has-disconnected-with">named pipe (mkfifo): how to detect on macos that the reading end (consumer) has disconnected, without consumer writing to the write end</a>.</p> <p>Having an independent and more minimal test compared to the Go+Ginkgo/Gomega based unit test excludes mistakes specific to the Go runtime and/or Go test harness.</p> <h2>fstat and st_link</h2> <p>Rewriting the detection based on a suggestion by Marcin Orlowski as follows doesn't work either on macOS, as <code>st_nlink</code> is always 1, and never changes during the lifespan of the producer.</p> <pre class="lang-py prettyprint-override"><code>def writer(fifoname): print(&quot;writer: start...&quot;) wfd = os.open(fifoname, os.O_WRONLY) wait = 0.250 # 250ms t = 0 while t &lt;= 4: stat = os.fstat(wfd) print(&quot;nlink&quot;, stat.st_nlink) t += wait time.sleep(wait) print(&quot;ERROR: timed out, disconnect not detected&quot;) </code></pre> <h2>kqueue</h2> <p>At least on macOS 12.7.2 using kqueue doesn't work either, despite the macOS documentation claiming that on pipes <code>EV_EOF</code> should be set when filtering for <code>EVFILT_WRITE</code>.</p> <pre class="lang-py prettyprint-override"><code># https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/kqueue.2.html # says: # # EVFILT_WRITE Takes a file descriptor as the identifier, and returns # whenever it is possible to write to the descriptor. For # sockets, pipes and fifos, data will contain the amount of # space remaining in the write buffer. The filter will set # EV_EOF when the reader disconnects, and for the fifo case, # this may be cleared by use of EV_CLEAR. # # However, the example below never sees an EV_EOF despite the macOS # documentation claiming so (at least on 12.7.2). import os import tempfile import atexit import shutil import time import select def writer(fifoname): print(&quot;writer: start...&quot;) wfd = os.open(fifoname, os.O_WRONLY) kq = select.kqueue() change_list = [ select.kevent( flags=select.KQ_EV_ADD|select.KQ_EV_EOF, filter=select.KQ_FILTER_WRITE, ident=wfd, ) ] events = kq.control(change_list, 0, 0.0) if len(events) != 0: print(&quot;didn't expect the Spanish Inquisition&quot;, events) return wait = 0.250 # ms t = 0 while t &lt;= 4.0: events = kq.control(None, 42, 0) if len(events) != 0 and events[0].flags &amp; select.KQ_EV_EOF != 0: print(&quot;reader has disconnected&quot;, events) return print(events) t+=wait time.sleep(wait) print(&quot;ERROR: timed out, disconnect not detected&quot;) def reader(fifoname): print(&quot;reader: start...&quot;) rfd = os.open(fifoname, os.O_RDONLY) print(&quot;sleeping...&quot;) time.sleep(2.0) os.close(rfd) print(&quot;reader closed&quot;) tmpdir = tempfile.mkdtemp(prefix=&quot;pype-&quot;) fifoname = os.path.join(tmpdir, &quot;fifo&quot;) print(&quot;named pipe&quot;, fifoname) os.mkfifo(fifoname, 0o600) atexit.register(shutil.rmtree, tmpdir) childpid = os.fork() if childpid == 0: writer(fifoname) else: atexit.unregister(shutil.rmtree) reader(fifoname) print(&quot;waiting for writer to terminate...&quot;) os.waitpid(childpid, 0) </code></pre>
<python><macos><named-pipes>
2023-12-21 20:12:43
0
2,761
TheDiveO
77,700,259
21,144,042
Problem in GitHub Actions when running a Python script
<p>I'm trying to write an action to automatically generate markdown summaries for a repository by running a <em>Python</em> script:</p> <pre class="lang-py prettyprint-override"><code>import os if __name__ == &quot;__main__&quot;: # Walk through all directories and files for root, dirs, files in os.walk('.'): # Ignore hidden directories if root.startswith('.\\.'): continue # Filepath to summary file summary_file_path = f'{root}/Summary.md' with open(summary_file_path, &quot;w&quot;) as summary_file: # Add title summary_file.write(&quot;# Summary\n\n&quot;) # Add directories to summary for dir in dirs: # Ignore hidden directories if not dir.startswith('.'): # Add to summary summary_file.write(f&quot;- [{dir}]({dir}/Summary.md)\n&quot;) # Add files to summary for file in files: # Ignore specific files if not (file == 'Summary.md' or file == 'Script.py'): # Remove extension filename = os.path.splitext(file)[0] # Replace underscores with spaces filename = filename.replace('_', ' ') # Add to summary summary_file.write(f&quot;- [{filename}]({file})\n&quot;) </code></pre> <p>And to run the script, I wrote the action:</p> <pre class="lang-yaml prettyprint-override"><code># This name will appear in the Actions name: Generate Summaries on: # Allows to manually run the job(s) at any time workflow_dispatch: # Run on every push on the master branch push: branches: - main # Jobs list jobs: # Job name generate-summaries: # Where the workflow will run runs-on: ubuntu-latest # Steps list steps: # Checkout the repository content - name: Checkout repository uses: actions/checkout@v4 # Setup python - name: Setup python uses: actions/setup-python@v4 with: python-version: '3.10' # Generate/Update summaries - name: Generate summaries run: python Script.py # Commit all changes - name: Commit changes run: | git config user.name 'github-actions[bot]' git config user.email 'github-actions[bot]@users.noreply.github.com' git add . git commit -m &quot;Updated summaries&quot; || exit 0 git push origin main env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} </code></pre> <p>The script should create a <em>Summary.md</em> file in each directory (excluding hidden ones), listing the contents of each one. In other words, considering this folder structure:</p> <pre><code>. ├── .github/ │ └── workflows/ │ └── main.yaml ├── ExampleFolder1/ │ ├── ExampleFolder1.md │ └── ExampleFolder11/ │ └── ExampleFolder11.md ├── ExampleFolder2/ │ └── ExampleFolder2.md └── Script.py </code></pre> <p>The result should be:</p> <pre><code>. ├── .github/ │ └── workflows/ │ └── main.yaml ├── ExampleFolder1/ │ ├── ExampleFolder1.md │ ├── Summary.md │ └── ExampleFolder11/ │ ├── ExampleFolder11.md │ └── Summary.md ├── ExampleFolder2/ │ ├── ExampleFolder2.md │ └── Summary.md ├── Script.py └── Summary.md </code></pre> <p>And it works properly when I run it locally, but it throws an error when it runs in the workflow:</p> <pre><code>Run git config user.name 'github-actions[bot]' git config user.name 'github-actions[bot]' git config user.email 'github-actions[bot]@users.noreply.github.com' git add . git commit -m &quot;Updated summaries&quot; || exit 0 git push origin main shell: /usr/bin/bash -e {0} env: pythonLocation: /opt/hostedtoolcache/Python/3.10.13/x64 PKG_CONFIG_PATH: /opt/hostedtoolcache/Python/3.10.13/x64/lib/pkgconfig Python_ROOT_DIR: /opt/hostedtoolcache/Python/3.10.13/x64 Python2_ROOT_DIR: /opt/hostedtoolcache/Python/3.10.13/x64 Python3_ROOT_DIR: /opt/hostedtoolcache/Python/3.10.13/x64 LD_LIBRARY_PATH: /opt/hostedtoolcache/Python/3.10.13/x64/lib GITHUB_TOKEN: *** To https://github.com/diegoborbadev/summariestest [main ec81c99] Updated summaries ! [remote rejected] main -&gt; main (refusing to allow a GitHub App to create or update workflow `.github/workflows/Summary.md` without `workflows` permission) error: failed to push some refs to 'https://github.com/diegoborbadev/summariestest' 4 files changed, 12 insertions(+) create mode 100644 .github/Summary.md create mode 100644 .github/workflows/Summary.md create mode 100644 FrontEnd/Summary.md create mode 100644 Summary.md Error: Process completed with exit code 1. </code></pre> <p>The error occurs due to permissions to modify the workflow, I understand, but <strong>the script shouldn't be modifying that folder</strong>. It has filters to prevent this from happening, and locally, it doesn't occur. So, <strong>why does it exhibit this behavior when executed in the workflow</strong>?</p>
<python><github><github-actions>
2023-12-21 19:57:07
1
2,435
Diego Borba
77,699,984
1,790,485
python 2 vs 3 compatibility test with pylint is giving error
<p>I'm currently working on migrating our codes from Python 2 to Python 3. For that, we thought of using <code>pylint</code> to check the compatibility test with below code with simple print.</p> <p>File_1.py</p> <pre><code>print &quot;Hello&quot; </code></pre> <p>File_2.py</p> <pre><code>print(&quot;Hello&quot;) </code></pre> <p>In above case both will work in Python 2, but <code>File_1.py</code> will have a syntax error in Python 3.</p> <p>When I run pylint on the below files I am getting same report on both files. Logically <code>File_2.py</code> is Python-compatible, then why is pylint showing it as error code <strong>E</strong>? Am i doing anything wrong...?</p> <pre><code>pylint --py3k File_1.py File_2.py No config file found, using default configuration ************* Module File_1 E: 1, 0: print statement used (print-statement) ************* Module File_2 E: 1, 0: print statement used (print-statement) ---------------------------------------------------------------------- Your code has been rated at -40.00/10 (previous run: -40.00/10, +0.00) </code></pre> <p>Code and python2.7 pylint Output <a href="https://i.sstatic.net/C2Nfn.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/C2Nfn.png" alt="" /></a></p> <p>Python3.7 pylint Output <a href="https://i.sstatic.net/g6mE4.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/g6mE4.png" alt="Python3.7 pylint Output" /></a></p> <p>Python2 pylint version</p> <p><a href="https://i.sstatic.net/FdfAI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/FdfAI.png" alt="pylit version" /></a></p> <p>Python3 pylint version</p> <p><a href="https://i.sstatic.net/hF5cY.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/hF5cY.png" alt="enter image description here" /></a></p>
<python><python-3.x><python-2.7><pylint>
2023-12-21 18:51:40
1
2,992
Rao
77,699,651
1,245,281
How to log OpenTelemetry data with python logger in an async app?
<p>So I've got this Python app. Basically it takes a job request, and runs a task. It is using asyncio so the methods are async/await. I wanted to create a logging Filter which added some trace context (trace/span IDs along with some attributes) to the log messages. But what ends up happening is it ends up calling <code>end()</code> on an ended span. I've narrowed the code down to demonstrate:</p> <pre class="lang-py prettyprint-override"><code>from logging import LogRecord import uvicorn import asyncio import logging from fastapi import FastAPI from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider tracer = trace.get_tracer(&quot;Demo&quot;) provider = TracerProvider() trace.set_tracer_provider(provider) class spanFilter(logging.Filter): def filter(self, record: LogRecord) -&gt; LogRecord: with trace.get_current_span() as span: print(&quot;OK!&quot;) return True logging.basicConfig(level=logging.INFO) task_logger = logging.getLogger(&quot;task&quot;) task_logger.addFilter(spanFilter()) class Task: async def run(self): with tracer.start_as_current_span(&quot;Run Task&quot;) as span: task_logger.info(&quot;Running task&quot;) await asyncio.sleep(2) app = FastAPI() # Enable instrumentation FastAPIInstrumentor.instrument_app(app) @app.post('/job') async def create_job(): with tracer.start_as_current_span(&quot;Job Request&quot;) as span: task = Task() await task.run() if __name__ == &quot;__main__&quot;: uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=7080) </code></pre> <p>The output I get is:</p> <pre><code>OK! INFO:task:Creating new session OK! WARNING:opentelemetry.sdk.trace:Calling end() on an ended span. WARNING:opentelemetry.sdk.trace:Calling end() on an ended span. INFO: 127.0.0.1:53663 - &quot;POST /job HTTP/1.1&quot; 200 OK </code></pre>
<python><python-asyncio><open-telemetry>
2023-12-21 17:38:21
0
551
RedBullet
77,699,632
10,466,809
Why can I omit the space after -m when executing python scripts at the command line?
<p>If I make a file like</p> <pre><code># test.py print('Hello World') </code></pre> <p>and I run</p> <pre><code>python -m test </code></pre> <p>then the python script runs. But if I run</p> <pre><code>python -mtest </code></pre> <p>the program ALSO runs.</p> <p>I would expect omitting that space causes some kind of error. Is this expected behavior? Is this typical behavior when running commands at the command line?</p>
<python><command-line-arguments>
2023-12-21 17:34:39
2
1,125
Jagerber48
77,699,631
15,959,591
Empty rows in confusion matrix of a neural network
<p>Could you please say what's wrong with my confusion matrix? Two rows are empty, however, when I print out the confusion matrix (without plotting) the rows are not empty. That is the code that I use:</p> <pre><code>num_classes = 2 confusion_mat = confusion_matrix(y_test, predicted_labels) # Calculate total counts for each label label_counts = np.sum(confusion_mat, axis=1) # Create a new confusion matrix with an additional row and column for label counts confusion_mat_with_counts = np.zeros((num_classes + 1, num_classes + 1), dtype=np.int64) confusion_mat_with_counts[:num_classes, :num_classes] = confusion_mat confusion_mat_with_counts[:num_classes, num_classes] = label_counts confusion_mat_with_counts[num_classes, :num_classes] = np.sum(confusion_mat, axis=0) confusion_mat_with_counts[num_classes, num_classes] = np.sum(confusion_mat) plt.figure(figsize=(8, 6)) sns.heatmap(confusion_mat_with_counts, annot=True, cmap=&quot;YlGnBu&quot;, fmt=&quot;d&quot;, xticklabels=list(label_encoder.classes_) + ['Total'], yticklabels=list(label_encoder.classes_) + ['Total'], cbar=False) plt.title(&quot;Confusion Matrix&quot;) plt.xlabel(&quot;True Labels&quot;) plt.ylabel(&quot;Predicted Labels&quot;) plt.show() </code></pre> <p>I tried to simplify the code like this:</p> <pre><code>num_classes = 2 confusion_mat = confusion_matrix(y_test, predicted_labels) sns.heatmap(confusion_mat, annot=True, cmap='Blues', fmt='g') plt.title('Confusion Matrix') plt.ylabel('True Label') plt.xlabel('Predicted Label') plt.savefig('confusion_matrix.png') plt.show() </code></pre> <p>The printed confusion matrix is:</p> <pre><code>[[ 28 23 51] [ 19 104 123] [ 47 127 174]] </code></pre> <p>But the problem is not resolved. The image shows the issue with the confusion matrix plot. <a href="https://i.sstatic.net/Yvr3T.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Yvr3T.jpg" alt="enter image description here" /></a></p>
<python><tensorflow><neural-network><seaborn><confusion-matrix>
2023-12-21 17:34:34
0
554
Totoro
77,699,561
903,011
How to reset py's database?
<p>A vscode extension needs to use <a href="https://docs.python.org/3/using/windows.html#launcher" rel="nofollow noreferrer"><code>py</code></a> launcher. I installed Python via <a href="https://scoop.sh/" rel="nofollow noreferrer"><code>scoop</code></a> and it works:</p> <pre><code>PS C:\Users\W&gt; python --version Python 3.12.1 </code></pre> <p>When checking for <code>py</code>, it is where it is expected to be:</p> <pre><code>PS C:\Users\W&gt; Get-Command py CommandType Name Version Source ----------- ---- ------- ------ Application py.exe 3.12.1150… C:\Users\W\scoop\apps\python\current\py.exe </code></pre> <p>So far so good. Now when I actually want to launch <code>py</code> I get</p> <pre><code>PS C:\Users\W&gt; py Unable to create process using 'C:\Users\W\scoop\apps\python\3.11.3\python.exe': The system cannot find the file specified. </code></pre> <p><code>py</code> seems to point to an old version that I may have had in the past.</p> <p>I uninstalled Python, checked that <code>py</code> is now unknown, and reinstalled it afterwards. The effect is the same - this information must have been saved somewhere, and worse, this is the only Python installation <code>py</code> knows about:</p> <pre><code>PS C:\Users\W&gt; py --list -V:3.11 * Python 3.11 (64-bit) </code></pre> <p><code>3.11</code> is nowhere to be found and <code>py.exe</code> directly comes from the <code>3.12</code> installation</p> <pre><code>PS C:\Users\W&gt; ls C:\Users\W\scoop\apps\python Directory: C:\Users\W\scoop\apps\python Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 21/12/2023 17:35 3.12.1 l-r-- 21/12/2023 17:35 current -&gt; C:\Users\W\scoop\apps\python\3.12.1 </code></pre> <p>I am now at the end of my journey to try to understand where th eproblem is, thus my question: <strong>how to reset the <code>py</code> database of installed Python versions?</strong></p>
<python><windows><scoop-installer>
2023-12-21 17:18:21
1
30,596
WoJ
77,699,459
2,551,923
Extract the output path from step function trasnform job in python script
<p>I have a step function which has a infrence/tranform job and it needs to do thigs calculate prediction result and prediction probablity .</p> <pre><code>{ &quot;Comment&quot;: &quot;A description of my state machine for model onboarding&quot;, &quot;StartAt&quot;: &quot;Transform&quot;, &quot;States&quot;: { &quot;Transform&quot;: { &quot;Type&quot;: &quot;Parallel&quot;, &quot;Branches&quot;: [ { &quot;StartAt&quot;: &quot;Transform Job&quot;, &quot;States&quot;: { &quot;Transform Job&quot;: { &quot;Type&quot;: &quot;Task&quot;, &quot;Resource&quot;: &quot;arn:aws:states:::sagemaker:createTransformJob.sync&quot;, &quot;Parameters&quot;: { &quot;TransformJobName.$&quot;: &quot;States.Format('test-transform-{}', $$.Execution.Input.currentTimestamp)&quot;, &quot;ModelName&quot;: &quot;model-name&quot;, &quot;TransformInput&quot;: { &quot;DataSource&quot;: { &quot;S3DataSource&quot;: { &quot;S3DataType&quot;: &quot;S3Prefix&quot;, &quot;S3Uri&quot;: &quot;s3://test/input.pq&quot; } }, &quot;ContentType&quot;: &quot;application/x-npy&quot;, &quot;SplitType&quot;: &quot;None&quot;, &quot;CompressionType&quot;: &quot;None&quot; }, &quot;TransformOutput&quot;: { &quot;S3OutputPath&quot;: &quot;s3://test/output&quot; }, &quot;TransformResources&quot;: { &quot;InstanceType&quot;: &quot;ml.m5.4xlarge&quot;, &quot;InstanceCount&quot;: 1 }, &quot;BatchStrategy&quot;: &quot;SingleRecord&quot;, &quot;MaxConcurrentTransforms&quot;: 1, &quot;MaxPayloadInMB&quot;: 90 }, &quot;End&quot;: true } } } ], &quot;End&quot;: true }, &quot;Prem Prediction&quot;: { &quot;Type&quot;: &quot;Parallel&quot;, &quot;Branches&quot;: [ { &quot;StartAt&quot;: &quot;Prem Prediction Job&quot;, &quot;States&quot;: { &quot;Prem Prediction Job&quot;: { &quot;Type&quot;: &quot;Task&quot;, &quot;Resource&quot;: &quot;arn:aws:states:::sagemaker:createProcessingJob.sync&quot;, &quot;Parameters&quot;: { &quot;ProcessingJobName.$&quot;: &quot;States.Format('test-post-prediction-{}', $$.Execution.Input.currentTimestamp)&quot;, &quot;ProcessingInputs&quot;: [ { &quot;InputName&quot;: &quot;code&quot;, &quot;S3Input&quot;: { &quot;S3Uri.$&quot;: &quot;States.Format('s3://{}/code/', $$.Execution.Input.s3Bucket)&quot;, &quot;LocalPath&quot;: &quot;/opt/ml/processing/input/code/&quot;, &quot;S3DataType&quot;: &quot;S3Prefix&quot;, &quot;S3InputMode&quot;: &quot;File&quot;, &quot;S3DataDistributionType&quot;: &quot;FullyReplicated&quot; } } ], &quot;ProcessingResources&quot;: { &quot;ClusterConfig&quot;: { &quot;InstanceType&quot;: &quot;ml.m5.12xlarge&quot;, &quot;InstanceCount&quot;: 1, &quot;VolumeSizeInGB&quot;: 60 } }, &quot;NetworkConfig&quot;: { &quot;EnableNetworkIsolation&quot;: false, &quot;VpcConfig&quot;: { &quot;SecurityGroupIds&quot;: [ &quot;sg-asdasd&quot; ], &quot;Subnets&quot;: [ &quot;subnet-asdasd&quot; ] } }, &quot;RoleArn.$&quot;: &quot;$$.Execution.Input.roleArn&quot;, &quot;Environment&quot;: { &quot;http_proxy&quot;: &quot;http://google.com&quot; }, &quot;AppSpecification&quot;: { &quot;ImageUri.$&quot;: &quot;$$.Execution.Input.imageUri&quot;, &quot;ContainerArguments&quot;: [ &quot;--s3bucket&quot;, &quot;test&quot; ], &quot;ContainerEntrypoint&quot;: [ &quot;python3&quot;, &quot;/opt/ml/processing/input/code/premPrediction.py&quot; ] } }, &quot;End&quot;: true } } } ], &quot;End&quot;: true } } } </code></pre> <p>the python code running in tranform job is this</p> <pre><code>def generate_predictions(data:pd.DataFrame, data_format:str): &quot;&quot;&quot; Return in data format that was recieved: csv, parquet, gzip, json &quot;&quot;&quot; print('predicting') predictions = ScoringService.predict(data) print(type(predictions)) predictions_prob = ScoringService.predict_proba(data) print(type(predictions_prob)) print(predictions_prob.shape) print('predictions generated') if data_format == &quot;text/csv&quot;: out = io.StringIO() predictions.to_csv(out, index=False) elif data_format in [&quot;application/parquet&quot;,&quot;application/gzip&quot;]: out = io.BytesIO() print('about to save {}'.format(out)) predictions=pd.DataFrame(predictions) elif data_format ==&quot;application/x-npy&quot;: s3_client = boto3.client(&quot;s3&quot;) ## save prediction out = io.BytesIO() np.save(out, predictions) upload_obj = io.BytesIO(out.getvalue()) bucket_name = &quot;test&quot; s3_path = f'output/y_pred_{today}.npy' s3_client.upload_fileobj(upload_obj, bucket_name, s3_path) ## save prediction probability out_pred_prob = io.BytesIO() np.save(out_pred_prob, predictions_prob) upload_obj_pred_prob = io.BytesIO(out_pred_prob.getvalue()) bucket_name = &quot;test&quot; s3_path = f'output/y_pred_prob_{today}.npy' s3_client.upload_fileobj(upload_obj_pred_prob, bucket_name, s3_path) elif data_format == &quot;application/json&quot;: out = io.StringIO() predictions.to_json(out, index=False) else: logging.error(f&quot;Unsupported data_format: {data_format}&quot;) out = None data_format = None return out, data_format </code></pre> <p>In this the condition data_format ==&quot;application/x-npy&quot;: , is there a way i can retrieve the s3output path here rather than harcoding the s3bucket . so that i dont have use hardcoding and get he tranform out value in the python code and then split it to get the sc3 bucket name.</p>
<python><amazon-sagemaker><aws-step-functions>
2023-12-21 16:59:06
1
970
divyanayan awasthi
77,699,109
13,147,413
Replace nan values in a column with values from a different column from the same df in polars
<p>I'm very new to polars and i'm trying to translate some pandas statements.</p> <p>The pandas line is as follows:</p> <pre><code>df.loc[df['col_x'].isna(), 'col_y'] = df['col_z'] </code></pre> <p>that is to say: replace the values of col_y corresponding to null values of col_x with values of col_z.</p> <p>In polars i'm trying with <em>select</em>, but to no avail.</p>
<python><python-polars>
2023-12-21 15:57:19
1
881
Alessandro Togni
77,699,086
607,846
Wrap a Model instance field
<p>I have a model instance which has an attribute called parent which is a string containing the parent's id.</p> <p>When I serialise this instance, I want to wrap the parent id so that it appears as follows:</p> <pre><code>{ name = &quot;John&quot; parent = {&quot;id&quot;: &quot;123-345&quot;} } </code></pre> <p>What is the correct way to do this in marshmallow?</p> <p>This is what I am currently doing:</p> <pre><code>class IdSchema(Schema): id = fields.String() @pre_dump def wrap(self, data, **_): return {&quot;id&quot;: data} class UserSchema(Schema): name = fields.String() parent = fields.Nested(IdSchema) </code></pre>
<python><marshmallow>
2023-12-21 15:52:53
1
13,283
Baz
77,698,979
532,054
Django Rest Framework Token Auth > Remove user foreign Key from POSTs while keeping it for GETs
<p>I'm struggling to make this work. I have the following model:</p> <pre><code>class Message(models.Model): text = models.CharField(max_length=500) date = models.DateTimeField(&quot;date published&quot;) user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) def __str__(self): return self.text </code></pre> <p>Here is my serializer:</p> <pre><code>class MessageSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer() class Meta: model = Message fields = ['id', 'text', 'date', 'user', 'room'] </code></pre> <p>I've changed the serializer to have the user &quot;expanded&quot; when I retrieve my Message list with a GET request.</p> <p>So what I hoping to achieve - with my token authentication - is to avoid passing the user in my POST request. As I pass the token for authentication, there should be a way to retrieve the user with it.</p> <p>Here are my ViewSets:</p> <pre><code>class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class MessageViewSet(viewsets.ModelViewSet): serializer_class = MessageSerializer def get_queryset(self): authentication_classes = [] room_id = self.request.query_params.get('room_id') return Message.objects.filter(room=room_id) </code></pre> <p>My settings:</p> <pre><code>REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication', ] } </code></pre> <p>How can I do this?</p> <p>Thanks!</p>
<python><django><django-rest-framework>
2023-12-21 15:29:46
1
1,771
lorenzo
77,698,907
9,686,037
Pytorch problem with shape of model output
<p>I'm trying to use an implementation of the D-Linear model in Pytorch.</p> <p>Here is the model architecture</p> <pre><code>from re import X import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class moving_avg(nn.Module): &quot;&quot;&quot; Moving average block to highlight the trend of time series &quot;&quot;&quot; def __init__(self, kernel_size, stride): super(moving_avg, self).__init__() self.kernel_size = kernel_size self.avg = nn.AvgPool1d(kernel_size=kernel_size, stride=stride, padding=0) def forward(self, x): # padding on the both ends of time series front = x[:, 0:1, :].repeat(1, (self.kernel_size - 1) // 2, 1) end = x[:, -1:, :].repeat(1, (self.kernel_size - 1) // 2, 1) x = torch.cat([front, x, end], dim=1) x = self.avg(x.permute(0, 2, 1)) x = x.permute(0, 2, 1) return x class series_decomp(nn.Module): &quot;&quot;&quot; Series decomposition block &quot;&quot;&quot; def __init__(self, kernel_size): super(series_decomp, self).__init__() self.moving_avg = moving_avg(kernel_size, stride=1) def forward(self, x): moving_mean = self.moving_avg(x) res = x - moving_mean return res, moving_mean class Model(nn.Module): &quot;&quot;&quot; DLinear &quot;&quot;&quot; def __init__(self, seq_len, pred_len, individual, enc_in, kernel_size = 25): super(Model, self).__init__() self.seq_len = seq_len self.pred_len = pred_len # Decompsition Kernel Size self.kernel_size = kernel_size self.decompsition = series_decomp(self.kernel_size) self.individual = individual self.channels = enc_in if self.individual: self.Linear_Seasonal = nn.ModuleList() self.Linear_Trend = nn.ModuleList() self.Linear_Decoder = nn.ModuleList() for i in range(self.channels): self.Linear_Seasonal.append(nn.Linear(self.seq_len,self.pred_len)) self.Linear_Seasonal[i].weight = nn.Parameter((1/self.seq_len)*torch.ones([self.pred_len,self.seq_len])) self.Linear_Trend.append(nn.Linear(self.seq_len,self.pred_len)) self.Linear_Trend[i].weight = nn.Parameter((1/self.seq_len)*torch.ones([self.pred_len,self.seq_len])) self.Linear_Decoder.append(nn.Linear(self.seq_len,self.pred_len)) else: self.Linear_Seasonal = nn.Linear(self.seq_len,self.pred_len) self.Linear_Trend = nn.Linear(self.seq_len,self.pred_len) self.Linear_Decoder = nn.Linear(self.seq_len,self.pred_len) self.Linear_Seasonal.weight = nn.Parameter((1/self.seq_len)*torch.ones([self.pred_len,self.seq_len])) self.Linear_Trend.weight = nn.Parameter((1/self.seq_len)*torch.ones([self.pred_len,self.seq_len])) def forward(self, x): # x: [Batch, Input length, Channel] seasonal_init, trend_init = self.decompsition(x) seasonal_init, trend_init = seasonal_init.permute(0,2,1), trend_init.permute(0,2,1) if self.individual: seasonal_output = torch.zeros([seasonal_init.size(0),seasonal_init.size(1),self.pred_len],dtype=seasonal_init.dtype).to(seasonal_init.device) trend_output = torch.zeros([trend_init.size(0),trend_init.size(1),self.pred_len],dtype=trend_init.dtype).to(trend_init.device) for i in range(self.channels): seasonal_output[:,i,:] = self.Linear_Seasonal[i](seasonal_init[:,i,:]) trend_output[:,i,:] = self.Linear_Trend[i](trend_init[:,i,:]) else: seasonal_output = self.Linear_Seasonal(seasonal_init) trend_output = self.Linear_Trend(trend_init) x = seasonal_output + trend_output return x.permute(0,2,1) # to [Batch, Output length, Channel] </code></pre> <p>My dataframe has 15 features and one target variable, for a total of 16 columns. I want to use the past values of the features and the target to predict the next n staps.</p> <pre><code>from sklearn.preprocessing import StandardScaler import pandas as pd from sklearn.model_selection import train_test_split import torch import torch.nn as nn from torch.utils.data import DataLoader, TensorDataset import torch.optim as optim # creating random dataframe df = pd.DataFrame(np.random.randint(0,100,size=(1000, 5)), columns=list('ABCDE')) np.random.seed(42) # Parameters seq_len = 12 pred_len = 3 kernel_size = 5 batch_size = 4 individual = True # Extract the target target_column = 'A' # Function to create sequences for training def create_sequence(data, seq_len, pred_len): sequences = [] targets = [] for i in range(len(data) - seq_len - pred_len + 1): sequence = data.iloc[i:i + seq_len].values target = data.iloc[i + seq_len:i + seq_len + pred_len][target_column].values sequences.append(sequence) targets.append(target) return np.array(sequences), np.array(targets) sequences, targets = create_sequence(df, seq_len, pred_len) </code></pre> <pre><code># split the data train_data, test_data, train_target, test_target = train_test_split(sequences, targets, test_size = 0.25, random_state = 42) train_data, val_data, train_target, val_target = train_test_split(train_data, train_target, test_size = 0.33, random_state = 42) # standardize data scaler = StandardScaler() train_data = scaler.fit_transform(train_data.reshape(-1, train_data.shape[-1])).reshape(train_data.shape) val_data = scaler.transform(val_data.reshape(-1, val_data.shape[-1])).reshape(val_data.shape) test_data = scaler.transform(test_data.reshape(-1, test_data.shape[-1])).reshape(test_data.shape) train_data_tensor = torch.Tensor(train_data) train_target_tensor = torch.Tensor(train_target) val_data_tensor = torch.Tensor(val_data) val_target_tensor = torch.Tensor(val_target) test_data_tensor = torch.Tensor(test_data) test_target_tensor = torch.Tensor(test_target) # Create DataLoader train_dataset = TensorDataset(train_data_tensor, train_target_tensor) train_loader = DataLoader(train_dataset, batch_size = batch_size, shuffle = True) model_config = {'seq_len':seq_len, 'pred_len':pred_len, 'individual': individual, 'enc_in':len(features_column), 'kernel_size': kernel_size} model = Model(seq_len = seq_len, pred_len = pred_len, individual = individual, enc_in = df.shape[1], kernel_size = kernel_size) optimizer = optim.Adam(model.parameters(), lr = 0.001) criterion = nn.MSELoss() num_epoch = 30 </code></pre> <p>But when I try to run the training loop</p> <pre><code>for epoch in range(num_epoch): model.train() for inputs, targets in train_loader: optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() model.eval() with torch.no_grad(): val_inputs = val_data_tensor val_targets = val_target_tensor val_outputs = model(val_inputs) val_loss = criterion(val_outputs, val_targets) with torch.no_grad(): test_inputs = test_data_tensor test_targets = test_target_tensor test_outputs = model(test_inputs) test_loss = criterion(test_outputs, test_targets) print(f'EPOCH: {epoch + 1}') print(f'TRAINING LOSS {loss.item()}') print(f'VALIDATION LOSS {val_loss.item()}') print(f'TEST LOSS {test_loss.item()}') </code></pre> <p>I get the following error</p> <pre><code>Using a target size (torch.Size([4, 3])) that is different to the input size (torch.Size([4, 3, 5])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size. return F.mse_loss(input, target, reduction=self.reduction) Output exceeds the size limit. Open the full output data in a text editor --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_3124\1828251915.py in &lt;module&gt; 9 10 outputs = outputs.squeeze(dim=1) ---&gt; 11 loss = criterion(outputs, targets) 12 loss.backward() 13 optimizer.step() ~\AppData\Roaming\Python\Python37\site-packages\torch\nn\modules\module.py in _call_impl(self, *input, **kwargs) 1128 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks 1129 or _global_forward_hooks or _global_forward_pre_hooks): -&gt; 1130 return forward_call(*input, **kwargs) 1131 # Do not call functions when jit is used 1132 full_backward_hooks, non_full_backward_hooks = [], [] ~\AppData\Roaming\Python\Python37\site-packages\torch\nn\modules\loss.py in forward(self, input, target) 528 529 def forward(self, input: Tensor, target: Tensor) -&gt; Tensor: --&gt; 530 return F.mse_loss(input, target, reduction=self.reduction) 531 532 ~\AppData\Roaming\Python\Python37\site-packages\torch\nn\functional.py in mse_loss(input, target, size_average, reduce, reduction) 3277 reduction = _Reduction.legacy_get_string(size_average, reduce) ... ---&gt; 73 return _VF.broadcast_tensors(tensors) # type: ignore[attr-defined] 74 75 RuntimeError: The size of tensor a (5) must match the size of tensor b (3) at non-singleton dimension 2 </code></pre>
<python><deep-learning><pytorch><neural-network><tensor>
2023-12-21 15:18:25
1
425
ianux22
77,698,870
10,192,593
Aggregating within Numpy array in Python
<p>I have a multi-dimensional numpy array where one of the dimensions is age in years. I would like to convert this into 5 year increments.</p> <p>So I have array with (10,2) where the first dimension represents age in years and the second dimension represents sex. I would like to calculate the mean for every 5 years for the two sexes individually.</p> <pre><code>import numpy as np arr = np.array([[0,1], [2,3], [3,4], [4,5], [5,6], [7,8], [8,9], [9,10], [10,11], [11,12]]) arr.shape mean_1st_5_yrs_female = np.mean([0,2,3,4,5]) mean_1st_5_yrs_male = np.mean([1,3,4,5,6]) mean_2nd_5_yrs_female = np.mean([7,8,9,10,11]) mean_2nd_5_yrs_male = np.mean([8,9,10,11,12]) arr = np.array([[mean_1st_5_yrs_female, mean_1st_5_yrs_male],[mean_2nd_5_yrs_female, mean_2nd_5_yrs_male]]) arr </code></pre> <p>How would I do this automatically in numpy?</p> <p>Thank you.</p>
<python><numpy>
2023-12-21 15:11:40
2
564
Stata_user
77,698,776
13,142,245
SageMaker pipelines CDK: All steps defined in Python script
<p>I'm interested in using SageMaker pipelines for the full ML Life cycle. From <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/build-and-manage-steps.html" rel="nofollow noreferrer">AWS SageMaker Documentation</a> I see that discrete steps can be defined in python, such steps could include Processing, Training, Tuning, RegisterModel, etc.</p> <p>What I'd like to better understand is how to define such a SageMaker pipeline using CDK? Ideally, the CDK would not explicitly define discrete steps, containerization of code/packages for each step, etc. But rather, the CDK would point to a python package (or script) that contains these discrete steps.</p> <p>The advantage of such a design is that one could add or remove steps using Python alone without making any changes to CDK, diffs on the relevant python package/script would bubble up, mutating the SageMaker pipeline.</p> <p>Pessimistically, I anticipate that there is a 1:1 relationship between steps defined in python and configurations declared in CDK. However, based on this documentation, I think it might be possible fr CDK to define an abstract pipeline where the specific steps are purely a function of python code.</p> <p>Questions</p> <ol> <li>Is this possible or am I overly optimistic about ML Ops automation using SageMaker pipelines?</li> <li>Could you link a resource, tutorial, etc. that demonstrates the CDK resource declarations that would realize such a design? (The specific python steps don't matter, so long as Python <em>alone</em> is defining the steps and sequence.)</li> </ol>
<python><pipeline><amazon-sagemaker>
2023-12-21 14:54:41
0
1,238
jbuddy_13
77,698,625
10,972,079
Alexa Skills Kit widget - "Problem installing widget - There were problems in your install widget request"
<p>I have a rather simple widget with APL, however, when I attempt to install said widget onto my Echo Show 10&quot;, a pop-up appears titled, &quot;Problem installing widget&quot; and with the message &quot;There were problems in your install widget request&quot; followed by a time stamp. For reference, here is the APL:</p> <pre><code>{ &quot;type&quot;: &quot;APL&quot;, &quot;version&quot;: &quot;2023.3&quot;, &quot;license&quot;: &quot;Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.\nSPDX-License-Identifier: LicenseRef-.amazon.com.-AmznSL-1.0\nLicensed under the Amazon Software License http://aws.amazon.com/asl/&quot;, &quot;import&quot;: [ { &quot;name&quot;: &quot;alexa-layouts&quot;, &quot;version&quot;: &quot;1.7.0&quot; } ], &quot;extensions&quot;: [ { &quot;uri&quot;: &quot;alexaext:datastore:10&quot;, &quot;name&quot;: &quot;DataStore&quot; } ], &quot;settings&quot;: { &quot;DataStore&quot;: { &quot;dataBindings&quot;: [ { &quot;namespace&quot;: &quot;widget_bin_datastore&quot;, &quot;key&quot;: &quot;binData&quot;, &quot;dataBindingName&quot;: &quot;dsBinData&quot;, &quot;dataType&quot;: &quot;OBJECT&quot; } ] } }, &quot;onDisplayStateChange&quot;: [ { &quot;type&quot;: &quot;Sequential&quot;, &quot;sequencer&quot;: &quot;displaySequencer&quot;, &quot;commands&quot;: [ { &quot;type&quot;: &quot;SendEvent&quot;, &quot;arguments&quot;: [ &quot;${event.displayState}&quot; ], &quot;flags&quot;: { &quot;interactionMode&quot;: &quot;STANDARD&quot; } } ] } ], &quot;mainTemplate&quot;: { &quot;parameters&quot;: [ &quot;payload&quot; ], &quot;items&quot;: [ { &quot;type&quot;: &quot;AlexaPhoto&quot;, &quot;headerTitle&quot;: &quot;Salford Bins&quot;, &quot;imageSource&quot;: &quot;https://i.imgur.com/B90CXAo.png&quot;, &quot;primaryText&quot;: &quot;${payload.dsBinData.bin_text}&quot;, &quot;secondaryText&quot;: &quot;${payload.dsBinData.postcode}&quot;, &quot;buttonText&quot;: &quot;Refresh&quot;, &quot;imageHideScrim&quot;: true, &quot;theme&quot;: &quot;dark&quot;, &quot;primaryAction&quot;: [ { &quot;type&quot;: &quot;SendEvent&quot;, &quot;arguments&quot;: [ &quot;widgetRefresh&quot; ] } ] } ] } } </code></pre> <p>Edit: For additional info, here's the widget package manifest:</p> <pre><code>{ &quot;manifest&quot;: { &quot;id&quot;: &quot;widget&quot;, &quot;version&quot;: &quot;1.0.0&quot;, &quot;installStateChanges&quot;: &quot;INFORM&quot;, &quot;updateStateChanges&quot;: &quot;INFORM&quot;, &quot;presentationDefinitions&quot;: [ { &quot;url&quot;: &quot;presentations/default.tpl&quot; } ], &quot;appliesTo&quot;: &quot;${viewport.mode == 'HUB' &amp;&amp; location == 'FAVORITE'}&quot; }, &quot;packageVersion&quot;: &quot;1.0&quot;, &quot;packageType&quot;: &quot;APL_PACKAGE&quot;, &quot;publishingInformation&quot;: { &quot;schemaVersion&quot;: &quot;1.0&quot;, &quot;locales&quot;: { &quot;en-GB&quot;: [ { &quot;targetViewport&quot;: &quot;WIDGET_M&quot;, &quot;metadata&quot;: { &quot;name&quot;: &quot;Widget name&quot;, &quot;description&quot;: &quot;Widget description&quot;, &quot;keywords&quot;: [ &quot;keyword1&quot;, &quot;keyword2&quot; ], &quot;iconUri&quot;: &quot;https://d3ozx4qyxcxwzd.cloudfront.net/default_icon.png&quot;, &quot;previews&quot;: [ &quot;https://d3ozx4qyxcxwzd.cloudfront.net/default_preview.png&quot; ] } } ] } } } </code></pre> <p>2nd Edit: Here's the request handler and the functions it uses:</p> <p>Functions:</p> <pre><code>def get_access_token(): return requests.post(&quot;https://api.amazon.com/auth/o2/token&quot;, { &quot;grant_type&quot;: &quot;client_credentials&quot;, &quot;client_id&quot;: &quot;[redacted]&quot;, &quot;client_secret&quot;: &quot;[redacted]&quot;, &quot;scope&quot;: &quot;alexa::datastore&quot; }).json()['access_token'] def _post_put_namespace(datastore_namespace, access_token=None): if access_token == None: access_token = get_access_token() requests.post( url='https://api.eu.amazonalexa.com/v1/datastore/commands', headers={'access_token': get_access_token(), 'type': 'PUT_NAMESPACE', 'namespace': datastore_namespace } ) def _post_put_object(namespace, key, content, access_token=None): if access_token == None: access_token = get_access_token() requests.post( url='https://api.eu.amazonalexa.com/v1/datastore/commands', headers={&quot;access_token&quot;: get_access_token(), 'type': 'PUT_OBJECT', 'namespace': namespace, 'key': key, 'content': content } ) def put_bin_data_to_datastore(postcode, bin_colours): access_token = get_access_token() _post_put_namespace('widget_bin_datastore', access_token=access_token) _post_put_object( namespace='widget_bin_datastore', key='binData', content=str({ &quot;postcode&quot;: postcode, &quot;bin_text&quot;: &quot;, &quot;.join(bin_colours) }) ) def _check_user_events(handler_input, arguments_possibilites): for arguments in arguments_possibilites: if is_request_type(&quot;Alexa.Presentation.APL.UserEvent&quot;)(handler_input): user_event = handler_input.request_envelope.request if user_event.arguments == arguments: return True return False </code></pre> <p>WidgetRefreshHandler:</p> <pre><code>class WidgetRefreshHandler(AbstractRequestHandler): def can_handle(self, handler_input): # type: (HandlerInput) -&gt; bool return _check_user_events( handler_input, [ ['widgetRefresh'], ['foreground'], ['background'] ] ) or ( is_request_type(&quot;Alexa.DataStore.PackageManager.UsagesInstalled&quot;)(handler_input) ) or ( is_request_type(&quot;Alexa.DataStore.PackageManager.UpdateRequest&quot;)(handler_input) ) or ( is_intent_name('WidgetRefreshIntent')(handler_input) ) def handle(self, handler_input): # type: (HandlerInput) -&gt; Response attr = handler_input.attributes_manager.persistent_attributes postcode = attr.get('postcode') saved_collections = attr.get('saved_collections') timestamp_now = datetime.datetime.now().timestamp() for saved_collection_day in saved_collections: collection_timestamp = datetime.datetime.strptime(saved_collection_day, &quot;%A %d %B %Y %H:%M:%S&quot;).timestamp() if timestamp_now &lt; collection_timestamp: bin_colours = saved_collections[saved_collection_day] break put_bin_data_to_datastore(postcode=postcode, bin_colours=bin_colours) return handler_input.response_builder.response </code></pre>
<python><json><widget><alexa-skills-kit>
2023-12-21 14:28:36
1
1,338
CauseYNot
77,698,393
8,456,253
SQLAlchemy error on replacing child in an one-to-one relationship
<p>I want to have a one-to-one relationship between a user and their last message. I expect that when I update their last message, the previous last message will get deleted from the database. Below is the minimal reproducible example</p> <pre class="lang-py prettyprint-override"><code>from sqlalchemy import ForeignKey, create_engine from sqlalchemy.orm import mapped_column, relationship, Mapped, DeclarativeBase class Base(DeclarativeBase): pass class UserEntity(Base): __tablename__ = &quot;user&quot; id: Mapped[str] = mapped_column(primary_key=True) last_message: Mapped[&quot;MessageEntity&quot;] = relationship(&quot;MessageEntity&quot;, uselist=False) class MessageEntity(Base): __tablename__ = &quot;message&quot; id: Mapped[str] = mapped_column(primary_key=True) content: Mapped[str] = mapped_column() from_user_id: Mapped[str] = mapped_column(ForeignKey('user.id')) from_user: Mapped[&quot;UserEntity&quot;] = relationship(&quot;UserEntity&quot;, back_populates=&quot;last_message&quot;, foreign_keys=[from_user_id]) DEFAULT_SQL_URL = &quot;sqlite+pysqlite:///:memory:&quot; engine = create_engine(DEFAULT_SQL_URL, echo=True) Base.metadata.create_all(engine) from sqlalchemy.orm import Session with Session(engine) as session: user1 = UserEntity(id=&quot;1&quot;) user2 = UserEntity(id=&quot;2&quot;) user1.last_message = MessageEntity(id=&quot;1&quot;, content=&quot;hello&quot;, from_user_id=&quot;1&quot;) session.add(user1) session.add(user2) session.commit() user1.last_message = MessageEntity(id=&quot;2&quot;, content=&quot;hello&quot;, from_user_id=&quot;1&quot;) session.add(user1) session.commit() </code></pre> <p>This fails with an error</p> <pre><code>sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: message.from_user_id [SQL: UPDATE message SET from_user_id=? WHERE message.id = ?] [parameters: (None, '1')] (Background on this error at: https://sqlalche.me/e/20/gkpj) </code></pre> <p>I'm unsure how <code>from_user_id</code> is not found, when I provide it explicitly within <code>MessageEntity</code> constructor.</p>
<python><sqlalchemy><orm>
2023-12-21 13:49:01
1
830
kuco 23
77,698,326
13,566,716
render cloud pre-deploy error: "alembic": executable file not found in $PATH
<p>Im trying to deploy my Python app to Render cloud and it doesn't recognize alembic:</p> <pre><code>==&gt; Starting pre-deploy: alembic upgrade head ==&gt; Pre-deploy has failed ==&gt; There was a problem running your pre-deploy command: &quot;alembic&quot;: executable file not found in $PATH </code></pre> <p>I have alembic in the requirements.txt and I checked that it was successfully installed during build.</p> <p>Here is my dockerfile: Here is my dockerfile: Here is my dockerfile: Here is my dockerfile:</p> <pre><code># &quot;v4-&quot; stacks use our new, more rigorous buildpacks management system. They # allow you to use multiple buildpacks in a single application, as well as to # use custom buildpacks. # # - `v2-` images work with heroku-import v3.x. # - `v4-` images work with heroku-import v4.x. (We synced the tags.) ARG IMPORT_VERSION=v4 ARG HEROKU_STACK=${IMPORT_VERSION}-heroku-22 FROM ghcr.io/renderinc/heroku-app-builder:${HEROKU_STACK} AS builder # Below, please specify any build-time environment variables that you need to # reference in your build (as called by your buildpacks). If you don't specify # the arg below, you won't be able to access it in your build. You can also # specify a default value, as with any Docker `ARG`, if appropriate for your # use case. # ARG MY_BUILD_TIME_ENV_VAR # ARG DATABASE_URL # The FROM statement above refers to an image with the base buildpacks already # in place. We then run the apply-buildpacks.py script here because, unlike our # `v2` image, this allows us to expose build-time env vars to your app. RUN /render/build-scripts/apply-buildpacks.py ${HEROKU_STACK} # We strongly recommend that you package a Procfile with your application, but # if you don't, we'll try to guess one for you. If this is incorrect, please # add a Procfile that tells us what you need us to run. RUN if [[ -f /app/Procfile ]]; then \ /render/build-scripts/create-process-types &quot;/app/Procfile&quot;; \ fi; # For running the app, we use a clean base image and also one without Ubuntu development packages # https://devcenter.heroku.com/articles/heroku-20-stack#heroku-20-docker-image FROM ghcr.io/renderinc/heroku-app-runner:${HEROKU_STACK} AS runner # Here we copy your build artifacts from the build image to the runner so that # the image that we deploy to Render is smaller and, therefore, can start up # faster. COPY --from=builder --chown=1000:1000 /render /render/ COPY --from=builder --chown=1000:1000 /app /app/ # Here we're switching to a non-root user in the container to remove some categories # of container-escape attack. USER 1000:1000 WORKDIR /app # This sources all /app/.profile.d/*.sh files before process start. # These are created by buildpacks, and you probably don't have to worry about this. # https://devcenter.heroku.com/articles/buildpack-api#profile-d-scripts ENTRYPOINT [ &quot;/render/setup-env&quot; ] # 3. By default, we run the 'web' process type defined in the app's Procfile # You may override the process type that is run by replacing 'web' with another # process type name in the CMD line below. That process type must have been # defined in the app's Procfile during build. CMD [ &quot;/render/process/web&quot; ] </code></pre> <p>Any help would be appreciated!</p>
<python><python-3.x><sqlalchemy><fastapi><alembic>
2023-12-21 13:36:48
1
369
3awny
77,698,169
11,046,379
Create multiple columns by splitting value from other column with one assignment
<p>There is DataFrame as:</p> <pre><code>timestamp filename 2023-12-20 10:09:52.011 2023/12/20/1703056183.log </code></pre> <p>How to create new columns &quot;year&quot;,&quot;month&quot;,&quot;day&quot; in one assignment by splitting of &quot;filename&quot; column?</p> <p>Wished result is :</p> <pre><code>timestamp year month day filename 2023-12-20 10:09:52.011 2023 12 20 2023/12/20/1703056183.log </code></pre>
<python><pandas><dataframe>
2023-12-21 13:08:06
2
1,658
harp1814
77,697,685
5,805,893
Python generic type annotation for pandas series
<p>I am encountering a type checking error when running my code through <code>typeguard</code>.</p> <p>I the following file in my package:</p> <pre><code>from __future__ import annotations import pandas as pd def col_sum(x: pd.Series[float]) -&gt; pd.Series[float]: return x*(x.sum()-1) </code></pre> <p>Originally, I was using <code>pd.Series</code> for these type-hints, but when I run my code through <code>mypy</code> it requires that I explicitly subscript a type on the generic type, so I changed it to <code>pd.Series[float]</code> (this makes sense as it is more explicit and allows <code>mypy</code> to be certain that <code>x.sum()</code> is a float).</p> <p>I also have a test script which performs some unit tests on this function.</p> <p>However, my test-suite also includes running <code>pytest --typeguard-packages={MyPackage}</code>, but this is failing due to this function. Here is the error:</p> <pre><code>&gt; def col_sum(x: pd.Series[float]) -&gt; pd.Series[float]: E TypeError: 'type' object is not subscriptable </code></pre> <p>From my understanding, this is because <code>mypy</code> is importing the <code>pd.Series</code> from the <code>pandas-stubs</code> package which is a generic type (thus the requirement for the subscript). But <code>pytest</code> passes my code through the <code>install_import_hook()</code> function from <code>typeguard</code> which imports <code>pd.Series</code> as a class/type from the regular <code>pandas</code> package (which cannot be subscripted).</p> <h2>How can I make my code pass <em>both</em> of these tests?</h2> <p>For clarity, I am using a trimmed down version of the <a href="https://cookiecutter-hypermodern-python.readthedocs.io/" rel="nofollow noreferrer">hypermodern cookiecutter template</a>. I am using <code>nox</code> to manage my test-suite, and it runs the following Sessions:</p> <pre><code>* pre-commit -&gt; Lint using pre-commit. * safety -&gt; Scan dependencies for insecure packages. * mypy-3.10 -&gt; Type-check using mypy. * mypy-3.11 -&gt; Type-check using mypy. * tests-3.10 -&gt; Run the test suite. * tests-3.11 -&gt; Run the test suite. * coverage -&gt; Produce the coverage report. * typeguard -&gt; Runtime type checking using Typeguard. * xdoctest-3.10 -&gt; Run examples with xdoctest. * xdoctest-3.11 -&gt; Run examples with xdoctest. * docs-build -&gt; Build the documentation. </code></pre> <p>All of which are passing, except for <code>typeguard</code> Relevant package versions:</p> <pre><code>python = &quot;3.10.11&quot; pandas = &quot;2.1.4&quot; pandas-stubs = &quot;2.1.4.231218&quot; typeguard = &quot;4.1.5&quot; pytest = &quot;7.4.3&quot; </code></pre>
<python><pandas><mypy><typeguards><nox>
2023-12-21 11:33:02
1
1,261
Michael Barrowman
77,697,080
2,604,247
How to Read the Result of Query into a Dask Dataframe in a Distributed Client?
<p>Trying to read the results of a query (from an AWS athena database) to a dask dataframe. Following the <a href="https://docs.dask.org/en/latest/generated/dask.dataframe.read_sql_query.html#dask.dataframe.read_sql_query" rel="nofollow noreferrer"><code>read_sql_query</code></a> method of the official documentation.</p> <p>Here is how I am calling it.</p> <pre class="lang-py prettyprint-override"><code>from dask import dataframe query:sqlalchemy.Query engine:sqlalchemy.Engine dataframe.read_sql_query(sql=query.statement, con=str(engine.url), index_col='date') # AttributeError: 'OptionEngine' object has no attribute 'execute' </code></pre> <p>So, why this <code>AttributeError</code> when the documentation says I have to pass a string for the <code>con</code> argument? Should it be some other string? Note that the query is working fine without dask, so the database configuration parameters are alright.</p> <p>Also, I am looking for a read method that can scale to a multinode dask cluster without having to collect all the results at the driver node.</p>
<python><sql><dask><dask-distributed>
2023-12-21 09:52:42
0
1,720
Della
77,697,045
8,030,794
How to check status service on remote server Ubuntu using python?
<p>I have couple servers with services on Ubuntu 22.04</p> <ol> <li>Local server addresses = [<code>*.*.*.*</code>, <code>*.*.*.*</code>, <code>*.*.*.*</code>]</li> <li>Services name = [<code>my_service1.service</code>,<code>my_service2.service</code>,<code>my_service3.service</code>]</li> </ol> <p>How to check services status from python on one of servers? All servers are connected to a local network with each other.</p>
<python>
2023-12-21 09:48:05
1
465
Fresto
77,696,915
6,694,814
Python problem with opening password protected Excel file
<p>I would like to open my Excel file which is password protected. I've used some of the ways but without any success so far.</p> <p>My recent approach is based on the Pandas library, which cannot read the password-protected Excel file.</p> <p>The code looks like this:</p> <pre><code> import pandas as pd import os, sys import win32com.client def unprotect_xlsx(filename): xcl = win32com.client.Dispatch('Excel.Application') pw_str = 'Protektor' wb = xcl.workbooks.open(filename) wb.Unprotect(pw_str) wb.UnprotectSharing(pw_str) xcl.DisplayAlerts = False wb.Save() xsc.Quit if __name__ == '__main__': filename = 'C:\my\Cost.xlsx' unprotect_xslx(filename) df = pd.read_excel('C:\my\Cost.xlsx') print (df) </code></pre> <p>I am getting an error:</p> <pre><code> NameError: name 'unprotect_xslx' is not defined </code></pre> <p>Which means, that the implementation of above doesn't work.</p> <p>Is there any solution of how could I open the password-protected file?</p>
<python><excel>
2023-12-21 09:25:48
1
1,556
Geographos
77,696,881
4,429,265
Scraping indicator results from tradingview - steps and instructions
<p>Before you deem this question duplicated, I read all the questions with the topic of scraping and tradingview, none of those question covered the points here completely, so I asked my own question. Thank you very much for your time and help.</p> <p>I want to extract indicator results from TradingView's website. There are a few challenges:</p> <ol> <li>I need to log in.</li> <li>I have to open multiple sessions for different symbols (This is an important step).</li> <li>I need to add indicators to each session (This is an important and complicated step).</li> <li>I must click the &quot;data window&quot; button.</li> <li>I want to scrape the results from the data window.</li> </ol> <p>I am completely new to scraping, and after a bit of research, I understand that one of the best ways that can handle these steps is Selenium. Although, I do not have any clue on if all these steps are possible to do in Selenium + Python, and if they are, how much time will they require. Now, I am not asking about the time, but:</p> <ol> <li>First, if it is possible to do these steps in Selenium</li> <li>It would be amazing if you can give me a few keywords on how can I complete these steps in Selenium.</li> </ol> <p>UPDATE:</p> <p>Clarifications on the question: 1- I understand that scraping is not he easiest option, as I have developed over 200 indicators and candle patterns before in Python, and now there are reasons that I have to use scraping. 2- I am new to scraping, not new to programming. Please write your full answer guide without considering my expertise level. 3- I do not need any code, I just want keywords on what will I do and what will I use in every step.</p>
<python><selenium-webdriver>
2023-12-21 09:19:58
5
417
Vahid
77,696,759
5,533,078
code documentation with calls traceback (python)
<p>I am trying to find an automatic documentation tool that tells me what happens (which other functions or classes are called, and when) e.g. when I instantiate a given (python) class, or run one of its methods, in terms of calls traceback (but better rendered than a usual error log)</p> <p>Ideally without running the code, using static code analysis (e.g. like <code>pyreverse</code> <a href="https://modeling-languages.com/uml-tools/#python" rel="nofollow noreferrer">https://modeling-languages.com/uml-tools/#python</a>)</p> <p>(it doesn't need to be LLM-based)</p> <p>any idea if such tool exists?</p> <p>thanks</p>
<python><static-analysis><documentation-generation>
2023-12-21 08:56:41
0
1,168
jjrr
77,696,537
2,964,428
Can finding patterns between numbers in the rock paper scissors game improve program performance?
<p>I recently read a book for computer beginners listing a code snip about the rock paper scissors game. The program uses primitive integers 0, 1, and 2 to represent rock, scissors, and paper.</p> <p>The most straightforward algorithm is to enumerate all the 3x3=9 situations.</p> <pre class="lang-py prettyprint-override"><code>a = rand.randint(0, 2) b = rand.randint(0, 2) if a == 0 and b == 0: print(&quot;draw game&quot;) elif a ==0 and b ==1: print(&quot;winner is A&quot;) ... </code></pre> <p>Then, the author hints that if we use little mathematical skills to find the relationship between the three numbers and three possible outcomes, the program can be simplified and run faster.</p> <pre class="lang-py prettyprint-override"><code>if a == b: print(&quot;draw game&quot;) elif a == (b + 1) % 3: print(&quot;winner is B&quot;) else: print(&quot;winner is A&quot;) </code></pre> <p>Assuming that the probabilities of entering all if-else branches in the two algorithms are not much different (excluding the situation where a player always gestuers stone), then <strong>I think there are no significant performance differences between the two algorithms or even the performance of the latter may be slightly worse,</strong> because the remainder(<code>%</code>) operation seems to consume more CPU cycles than <code>==</code>.</p> <p>However, I did a performance test with the following code(<code>$ time python3 game.py</code>), which showed that the latter algorithm runs faster. I am curious why this is happening.</p> <p>I was considering that either <code>rand.randint(0, 2)</code> or <code>print()</code> is much slower than the comparison operation, so I pre-generated some test cases, put them into the list, and used <code>pass</code> instead of <code>print()</code>.</p> <pre class="lang-py prettyprint-override"><code>def brute_force(a, b): if a == 0 and b == 0: pass ... def mod(a, b): if a == b: pass elif a == (b + 1) % 3: pass else: pass if __name__ == '__main__': testcases = [...] num_repetions = 1_000_000 for i in range(num_repetions): for a, b in testcases: brute_force(a, b) # mod(a, b) </code></pre> <p><code>time</code> with <code>brute_force</code> samples(in second): [17.014, 18.069, 16.956, 17.931, 17.919, 17.211, 17.983, 16.984, 17.581, 17.048] <code>time</code> with <code>mod</code> samples: [15.921,14.817,15.723,15.715,15.715,16.917,14.957,15.196,16.115,14.763]</p>
<python><algorithm><performance><performance-testing>
2023-12-21 08:07:48
2
393
da_miao_zi
77,696,429
5,466,652
ConnectTimeout: HTTPSConnectionPool(host='fc.yahoo.com', port=443) - Error attempting yfinance.Ticker(..).info
<p>I am trying to work with yfinance library (This is my first time attempting to work with it).</p> <p>I attempted the following and it worked <code>pip install yfinance --upgrade --no-cache-dir </code></p> <p>I attempted the following in jupyter notebook and it worked <code> import yfinance as yf sp500=yf.Ticker(&quot;^GSPC&quot;) print (&quot;got sp500&quot;) </code></p> <p>I am able to see the following line printed in the jupyter notebook</p> <p><code>got sp500</code></p> <p>When I attempt the following with or without the proxy, it errors out <code> sp500.proxy=&quot;http://my-proxy.org.com:xxx&quot; sp500.info </code></p> <p>I see the following error <code> ConnectTimeout: HTTPSConnectionPool(host='fc.yahoo.com', port=443): Max retries exceeded with url: / (Caused by ConnectTimeoutError(&lt;urllib3.connection.HTTPSConnection object at 0x0000028F3FA23590&gt;, 'Connection to fc.yahoo.com timed out. (connect timeout=30)')) </code></p> <p>I am behind a proxy and I believe that this has something to do with it. Need a fix for this.</p>
<python><jupyter-notebook><yahoo-finance><yfinance>
2023-12-21 07:40:34
0
1,877
kathikeyan A
77,696,389
23,002,898
In Django, i can't see the user registration form on the home page
<p>I'm new to Django, i would like to display the <code>register.html</code> registration form on the home page (<code>index.html</code>) and NOT on <code>http://127.0.0.1:8000/register</code> or similar. On the home page I want to see the various input textboxes. I don't get any errors, but the form doesn't display.</p> <p>In the <code>index.html</code> page i don't use anything to call the form (<code>register.html</code>). Maybe I'm doing this wrong?</p> <p>What am I doing wrong? How can I solve it?</p> <p><strong>App1/templates/registration/register.html</strong></p> <pre><code>{% extends &quot;index.html&quot; %} {% block content %} &lt;!--Register--&gt; &lt;div class=&quot;container py-5&quot;&gt; &lt;h1&gt;Register&lt;/h1&gt; &lt;form method=&quot;POST&quot;&gt; {% csrf_token %} {{ register_form.as_p }} &lt;button class=&quot;btn btn-primary&quot; type=&quot;submit&quot;&gt;Register&lt;/button&gt; &lt;/form&gt; &lt;p class=&quot;text-center&quot;&gt;If you already have an account, &lt;a href=&quot;/login&quot;&gt;login&lt;/a&gt; instead.&lt;/p&gt; &lt;/div&gt; {% endblock %} </code></pre> <p><strong>App1/forms.py</strong></p> <pre><code>from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User # Create your forms here. class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = (&quot;username&quot;, &quot;email&quot;, &quot;password1&quot;, &quot;password2&quot;) def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user </code></pre> <p><strong>App1/urls.py</strong></p> <pre><code>from django.urls import path from . import views urlpatterns=[ path('', views.index, name='index'), </code></pre> <p><strong>App1/views.py</strong></p> <pre><code>from .forms import NewUserForm from django.contrib import messages from django.contrib.auth.decorators import login_required def index(request): &quot;&quot;&quot;View function for home page of site.&quot;&quot;&quot; return render(request, 'index.html') def register_request(request): if request.method == &quot;POST&quot;: form = NewUserForm(request.POST) if form.is_valid(): user = form.save() login(request, user) messages.success(request, &quot;Registration successful.&quot; ) return redirect(&quot;index.html&quot;) messages.error(request, &quot;Unsuccessful registration. Invalid information.&quot;) form = NewUserForm() return render (request=request, template_name=&quot;registation/register.html&quot;, context={&quot;register_form&quot;:form}) </code></pre> <p><strong>MYSITE (PROJECT)</strong></p> <p><strong>urls.py</strong></p> <pre><code>from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from django.contrib.auth.views import LoginView urlpatterns = [ path('admin/', admin.site.urls), path('', include('App1.urls')), path(&quot;login/&quot;, LoginView.as_view(), name=&quot;login&quot;), </code></pre>
<python><python-3.x><django><django-forms><django-templates>
2023-12-21 07:31:16
3
307
Nodigap
77,696,381
10,832,127
Same records being added on unique constraints
<p>I have added a unique together (badge_id, speech_id, badge_type) however I can still add data with same information, Attaching my schema as well <a href="https://i.sstatic.net/vA41r.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/vA41r.png" alt="enter image description here" /></a></p> <p>I can explain one thing. unique constrain was applied and those column relation was <code>DO_NOTHING</code> and then in next migrations I updated it to <code>CASCADE</code> not sure if that is causing this misleading behavior of adding same rows.</p> <p>I double check if my django migrations were successful by extracting schema info from mysql, attached image.</p>
<python><mysql><django><django-migrations><unique-constraint>
2023-12-21 07:30:08
0
799
ThunderMind
77,696,211
4,382,305
predict float number by neural network
<p>I want to create a neural network to predict some outputs. two samples of data are here:</p> <pre><code>290,11,2,2700,14.7,43.7,77.6 320,2.1,2,2700,2.2,31.6,62.3 </code></pre> <p>The first 4 columns are inputs and The last 3 columns are outputs. I use torch. how many layers are needed for this problem. or what is best learning rate. I create neural network with 4 layers as below:</p> <pre><code>self.fc1 = nn.Linear(4, 16) self.fc2 = nn.Linear(16, 8) self.fc3 = nn.Linear(8, 8) self.fc4 = nn.Linear(8, 4) self.fc5 = nn.Linear(4, 3) x = torch.relu(self.fc1(x)) x = torch.relu(self.fc2(x)) x = torch.relu(self.fc3(x)) x = torch.relu(self.fc4(x)) x = self.fc5(x) </code></pre> <p>learning rate and epochs are:</p> <pre><code>lr=0.5 epoch=200000 </code></pre> <p>But in training process Loss value stop in about 242 and it does not decrease.</p> <pre><code>Epoch 7000, Loss: 242.69976806640625 Epoch 7050, Loss: 242.69976806640625 Epoch 22730, Loss: 242.69976806640625 Epoch 22740, Loss: 242.69976806640625 Epoch 35600, Loss: 242.69976806640625 Epoch 35610, Loss: 242.69973754882812 Epoch 35620, Loss: 242.69976806640625 Epoch 35630, Loss: 242.69976806640625 Epoch 160260, Loss: 242.69973754882812 Epoch 160270, Loss: 242.69973754882812 Epoch 160280, Loss: 242.69973754882812 </code></pre> <p>Others information are:</p> <pre><code>criterion = nn.MSELoss() optimizer = torch.optim.Adam(model.parameters(), lr=lr) </code></pre>
<python><pytorch><neural-network><prediction>
2023-12-21 06:50:39
3
2,091
Darwin
77,696,099
5,800,969
Click a dropdown search result item at random location in the dropdown result python selenium library
<p>I have been trying my head around to select the searched elements in the screenshot below. I tried the below methods none of them seems to be able to find the dropdown searched results elements.</p> <p><a href="https://i.sstatic.net/wUq6m.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wUq6m.png" alt="enter image description here" /></a> Sharing the corresponding source code of the dropdown result below based on inspecting the result.</p> <p><a href="https://i.sstatic.net/WOH28.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/WOH28.png" alt="enter image description here" /></a></p> <p>Following methods I have tried so far using <code>selenium</code> python library.</p> <pre><code> span_class=&quot;Roboto--ezzN4 text-5--NzQT7&quot; tag_name = &quot;aria-label&quot; drop_down_tag_result = driver.find_element(by=&quot;class name&quot;, value=span_class) drop_down_tag_result = driver.find_element(by=&quot;tag name&quot;, value=tag_name) drop_down_result = driver.find_element(by=&quot;xpath&quot;, value=&quot;//div[text()=&quot;+&quot;'&quot;+brand_name+&quot;'&quot;+&quot;]&quot;) drop_down_result.click() </code></pre> <p>All of above three methods can't locate the element and getting similar error below.</p> <pre><code>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {&quot;method&quot;:&quot;css selector&quot;,&quot;selector&quot;:&quot;.Roboto--ezzN4 text-5--NzQT7&quot;} (Session info: chrome=120.0.6099.109); </code></pre> <p>Can anyone help me guide in the right direction? I am new to selenium.</p>
<python><selenium-webdriver><web-scraping><selenium-chromedriver>
2023-12-21 06:22:17
1
2,071
iamabhaykmr
77,696,017
3,789,703
How can I pass a parameter or value from a test case to a fixture?
<p>I have a fixture <code>pretest()</code> like the example below which is intended to be called before every test case. I understand that this fixture is run before running the test case code.</p> <p>Is there any way to get a value from the test case function so that I can use it inside the fixture?</p> <p>For example, I need to read <code>json_name</code> defined in the test case and print it inside the <code>pretest</code> fixture before running the test case.</p> <pre><code>@pytest.fixture(autouse=True) def pretest(request): tc_name = request.node.name json_name = # ==&gt; how can i get this parameter or value from testcase and use here ? yield def test_case_EVA_01(): json_name = file1.json def test_case_EVA_02(): json_name = file2.json </code></pre>
<python><pytest><pytest-fixtures>
2023-12-21 05:59:26
2
417
Sunil Kumar